Powershell AWS Automation Management (12)-Create a highly available WordPress blog (bottom)

Source: Internet
Author: User
Tags wordpress blog

This is the third part of PowerShell's creation of the AWS high-availability blog, and let's look at how the post-half work is done.


  1. Create EC2-S3 role, which is assigned to EC2 virtual machines so that they automatically have access to S3 content after they are created.

  2. Create a VPC Network

  3. Create 2 subnets of a VPC, located in different AZ

  4. Create an Internet gateway

  5. Configure the routing table

  6. Create and configure the EC2 security Group to ensure that 80 and 22 ports are available

  7. Create a highly available MARIADB database

  8. Configure the security Group for the database to ensure that port 3306 is available

  9. Create a S3 Bucket and configure policy

  10. Create CloudFront distribution points, bind S3 buckets

  11. Preparing the WordPress configuration document

  12. Preparing the configuration document for VirtualHost

  13. Uploading the configuration document into the S3 bucket

  14. Configure bash shell scripts, including Lamp,wordpress,aws,crontab and S3 synchronization, and more

  15. Create a EC2 virtual machine, specify the bootstrap command created in 14 steps

  16. Update DNS records, point to the virtual machine

  17. Generate image file after confirmation is correct

  18. Configure Elb

  19. Update DNS records to ELB address

  20. Configuring launch Configuration

  21. Configure Auto Scaling



11. First to prepare the WordPress configuration document.


Download WordPress saved in the corresponding directory, then you can modify the contents of the wp-config.php to bind the database

$content =get-content C:\Users\yli\Downloads\wordpress-4.5.3\wordpress\wp-config-sample.php$content. Replace ("define (' db_name ', ' Database_name_here ')", "Define (' db_name ', ' WordPress ')"). ' Replace (' Define ' (' Db_user ', ' Username_here ') "," Define (' Db_user ', ' WordPress ') "). ' Replace (' Define (' Db_password ', ' password_here ') ', ' Define (' DB _password ', ' WordPress '). ' Replace (' Define (' db_host ', ' localhost ') ', ' Define (' db_host ', ' $adddress ') ') | Set-content C:\USERS\YLI\DOWNLOADS\WORDPRESS-4.5.3\WORDPRESS\WP-CONFIG.PHPGC C:\Users\yli\Downloads\ wordpress-4.5.3\wordpress\wp-config.php


12 Next, you need to configure Apache Vhost file, here I specify the root directory, domain name, already very important point, redirect the local image path to S3 up.


[Email protected] "<virtualhost *:80> ServerName blog.beanxyz.comServerAdmin [email protected] D ocumentroot/var/www/wordpress errorlog ${apache_log_dir}/error.log Customlog ${apache_log_dir}/access.log C ombined rewriteengine on Rewritecond%{http_host}!^$ rewriterule ^/wp-content/uploads (. *) $ http://$ ( $CFD. DomainName)/uploads$1 [r=302]</virtualhost> "@ $vhost | Set-content C:\Users\yli\Downloads\wordpress-4.5.3\wordpress.conf


13. Finally upload to me in the S3 bucket

Write-s3object-bucketname Yuanliwordpress-folder C:\Users\yli\Downloads\wordpress-4.5.3\wordpress-KeyPrefix Wordpress-recursewrite-s3object-bucketname Yuanliwordpress-key Wordpress_vhosts-file C:\users\yli\Downloads\ Wordpress-4.5.3\wordpress.confget-s3object-bucketname yuanliwordpress

650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M01/84/61/wKioL1ePDwrxd1s4AAHf1H0iQyE032.png "style=" float: none; "title=" 9.PNG "alt=" Wkiol1epdwrxd1s4aahf1h0iqye032.png "/>


14-15 These 2 steps are the most troublesome, I need to bind role, install lamp and WordPress script, also have to automatically copy the configuration file from S3, configure scheduled Tasks, synchronize every minute, and redirect. After the shell script is processed, you can generate an instance of EC2.

#Create  ami image# Create EC2 instance # bindings rolenew-iaminstanceprofile -instanceprofilename  "WordPress"  Add-IAMRoleToInstanceProfile -RoleName EC2-S3 -InstanceProfileName  "WordPress" $ Groupid=get-ec2securitygroup | where-object {$_. groupname -eq  "WordPress"} | select -expandproperty groupid# configuration lamp and wordpress[ Email protected] "#!/bin/bashapt-get updateapt-get upgrade -yapt-get install -y  mysql-client libmysqlclient15-dev apache2 apache2-doc apache2-mpm-prefork  Apache2-utils libexpat1 ssl-cert libapache2-mod-php5 php5 php5-common php5-curl  php5-dev php5-gd php5-idn php-pear php5-imagick php5-mcrypt php5-mysql  php5-ps php5-pspell php5-recode php5-xsl python-pip && pip  install awscliaws s3 cp --recursive s3://yuanliwordpress/wordpress /var/www/wordpress/chown -r www-data.www-data wordpresschmod 755 /var/ Www/wordpress/aws s3 cp s3://yuanliwordpress/wordpress_vhosts /etc/apache2/sites-available /wordpress.confcd /etc/apache2/sites-avaiablea2ensite wordpress.confservice apache2  Restartchmod 777 /var/www/wordpress/wp-contentsecho */1 * * * * root  aws s3 sync /var/www/wordpress/wp-content/uploads s3://yuanliwordpress/uploads  >> /etc/crontaba2enmod rewriteservice apache2 restart "@ $b =[system.text.encoding]:: UTF8. GetBytes ($userdata) $a =[system.convert]::tobase64string ($b) $instance =new-ec2instance -imageid  ami-6c14310f -instancetype t2.micro -keyname aws -subnetid  $subnet 1 - securitygroupid  $groupid  -MinCount 1 -MaxCount 1 -InstanceProfile_Name  " WordPress " -UserData $a $instanceid= ($instance | select -expand instances) .instanceidwrite-host  "Initilizing &NBSP;EC2&NBSP;INSTANCE,&NBSP;PLEASE&NBSP;WAIT&NBSP: " -foregroundcolor cyan -nonewline$state = $falsewhile ($state  -eq  $false) {   $name =  (get-ec2instance -instanceid $ Instanceid | select -expandproperty instances | select -expandproperty  state). Name  if ($name. value -eq  "Running") {   $state = $true   }else{    start-sleep  -Seconds 2  write-host  "..."  -ForegroundColor Cyan -NoNewline   }}


It will be available in a few minutes.

650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M02/84/61/wKioL1ePDw2C1HfhAABMLigVUyk533.png "style=" float: none; "title=" 10.PNG "alt=" Wkiol1epdw2c1hfhaabmligvuyk533.png "/>


The following part of the code is optional, I'm trying to test whether the template works. His main role is actually to update the DNS point to my template EC2 public IP


$publicip =get-ec2instance -instanceid  $instanceid  | select -ExpandProperty  instances | select -expandproperty publicipaddress# Update DNS record write-host  "Updating  Dns record. "  -foregroundcolor cyan$domain=get-r53hostedzonesbyname -dnsname beanxyz.com$hostid=$ Domain.id.Split ("/") [2] $recordsets =get-r53resourcerecordset -hostedzoneid  $domain. Id.split ("/") [2]   $currentip = $recordsets  | select -ExpandProperty resourceRecordSets |  where-object {$_.name -eq  "blog.beanxyz.com."}  | select -ExpandProperty ResourceRecords | select -ExpandProperty  Value$type= $recordsets  | select -ExpandProperty resourceRecordSets |  where-object {$_.name -eq  "blog.beanxyz.com."}  | select -expandproperty type | select -expandproperty value$change1  = nEw-object amazon.route53.model.change$change1. action =  "DELETE" $change 1. Resourcerecordset = new-object amazon.route53.model.resourcerecordset$change1. resourcerecordset.name =  "blog.beanxyz.com" $change 1. resourcerecordset.type =  $type $change1. Resourcerecordset.ttl = 300$change1. RESOURCERECORDSET.RESOURCERECORDS.ADD (@{value= $currentip}) $change 3 = new-object  Amazon.route53.model.change$change3. action =  "CREATE" $change 3. Resourcerecordset = new-object amazon.route53.model.resourcerecordset$change3. resourcerecordset.name =  "Blog.beanxyz.com" $change 3. resourcerecordset.type =  "A" $change 3. Resourcerecordset.ttl = 300$change3. RESOURCERECORDSET.RESOURCERECORDS.ADD (@{value= $publicip}) $params  = @{     hostedzoneid= $hostidChangeBatch _comment= "Replace a record of blog.beanxyz.com from   $currentip  to  $publiciP "changebatch_change= $change 1, $change 3}edit-r53resourcerecordset  @params   $TAGEC 2=new-object  Amazon.ec2.model.tag -property @{key= "Name"; value= "WordPress"}new-ec2tag -resource $ instanceid -tag  $tagec 2write-host  "The wordpress blog is ready. please  login to blog.beanxyz.com to finish the inital setup " - Foregroundcolor cyanstart-process http://blog.beanxyz.com


It's easy to go down again. Configure mirroring


#14. Configuring the AMI image new-ec2image-description Templatewordpress-name templatewordpress-instanceid $instanceidGet-ec2image- Owner Self | Unregister-ec2image-passthru


Configure ELB, update DNS records


#Create  elb and auto scaling#15. Configuring Elb#create elb$httplistener = new-object  -TypeName  ' Amazon.ElasticLoadBalancing.Model.Listener ' $HTTPListener .protocol =  ' http ' $ Httplistener.instanceport = 80$httplistener.loadbalancerport = 80$groupid= ( Get-ec2securitygroup| where-object {$_. groupname -eq  "WordPress"}). Groupid$subnet1= (get-ec2subnet | where-object {$_. cidrblock -eq  "10.2.1.0/24"}). Subnetid$subnet2= (get-ec2subnet | where-object {$_. cidrblock -eq  "10.2.2.0/24"}). subnetid$elb=new-elbloadbalancer -loadbalancername  "Myloadbalance"  -Listener  $HTTPListener  -SecurityGroup  $groupid  -subnet @ ($subnet 1, $subnet 2)  # $elb =get-elbloadbalancer# register-elbinstancewithloadbalancer -loadbalancername  "Myloadbalance"  -Instance @ ($ INSTANCE2ID) #更新DNS到LoadBalancer上write-host  "updating dns Record: "  -foregroundcolor cyan$domain=get-r53hostedzonesbyname -dnsname beanxyz.com$hostid=$ Domain.id.Split ("/") [2] $recordsets =get-r53resourcerecordset -hostedzoneid  $domain. Id.split ("/") [2]   $currentip = $recordsets  | select -ExpandProperty resourceRecordSets |  where-object {$_.name -eq  "blog.beanxyz.com."}  | select -ExpandProperty ResourceRecords | select -ExpandProperty  Value$change1 = new-object amazon.route53.model.change$change1. action =  "DELETE" $change 1. Resourcerecordset = new-object amazon.route53.model.resourcerecordset$change1. resourcerecordset.name =  "blog.beanxyz.com" $change 1. resourcerecordset.type =  "A" $change 1. Resourcerecordset.ttl = 300$change1. RESOURCERECORDSET.RESOURCERECORDS.ADD (@{value= $currentip}) $change 3 = new-object  Amazon.route53.model.change$change3. action =  "CREATE" $change 3. Resourcerecordset = new-object amazon.route53.model.resourcerecordset$change3. resourcerecordset.name =  "Blog.beanxyz.com" $change 3. resourcerecordset.type =  "CNAME" $change 3. Resourcerecordset.ttl = 300$change3. RESOURCERECORDSET.RESOURCERECORDS.ADD (@{value= $elb}) $params  = @{    hostedzoneid = $hostidChangeBatch _comment= "replace a record of blog.beanxyz.com from $ currentip to  $newname "changebatch_change= $change 1, $change 3}edit-r53resourcerecordset  @params


Finally, configure the launch config file and Auto Scaling group. Don't forget to configure Cloudwatch so that he can automatically add or remove instances based on the load

#配置  launch configuration- userdata (Bootstrap) new-aslaunchconfiguration -imageid  ( get-ec2image -owner self) .imageid -launchconfigurationname  "My-launchconfigurationfile"  -InstanceType  "T2.micro"  -SecurityGroup  $groupid  -UserData  $a  -keyname  awsNew-ASAutoScalingGroup -AutoScalingGroupName  "MY-ASG"  -LaunchConfigurationName  " My-launchconfigurationfile " -MinSize 1 -MaxSize 3 -LoadBalancerName " Myloadbalance " "-vpczoneidentifier  $subnet 1write-asscalingpolicy -autoscalinggroupname  my-asg -adjustmenttype  "changeincapacity"  -PolicyName  "Myscaleinpolicy"  - scalingadjustment 1  #Remove-asautoscalinggroup -autoscalinggroupname  "MY-ASG" $ stepadjustment=new-object amazon.autoscaling.model.stepadjustment  $stepadjustment. Metricintervallowerbound=20$stepadjustment. Scalingadjustment=-1write-asscalingpolicy -autoscalinggroupname my-asg -adjustmenttype  "Changeincapacity"  -PolicyName   "MyScaleInPolicy1"  -PolicyType  "stepscaling"  -stepadjustment $ stepadjustmentwrite-cwmetricalarm -actionsenabled  $true  -Alarmname  "Testonly"  - Alarmaction {arn:aws:autoscaling:ap-southeast-2:503646143282:scalingpolicy: Fba2d6ec-1566-459a-a3d5-bb800e88f7ad:autoscalinggroupname/my-asg:policyname/myscaleinpolicy1} -namespace   "AWS/EC2"  -Period 300 -Statistic  "Average"  -MetricName  "Cpuutlilization"   '-comparisonoperator  ' Lessthanorequaltothreshold " -threshold 60 -evaluationperiod  1
$stepadjustment =new-object Amazon.AutoScaling.Model.StepAdjustment $stepadjustment. Metricintervallowerbound=20$stepadjustment. Scalingadjustment=-1write-asscalingpolicy-autoscalinggroupname My-asg-adjustmenttype "ChangeInCapacity"- PolicyName "MyScaleInPolicy1"-policytype "stepscaling"-stepadjustment $stepadjustmentWrite-cwmetricalarm- actionsenabled $true-alarmname "Testonly"-alarmaction {arn:aws:autoscaling:ap-southeast-2:503646143282: SCALINGPOLICY:4CB293A4-1E6F-4D3E-8C02-2BAEC06EE663:AUTOSCALINGGROUPNAME/MY-ASG:POLICYNAME/MYSCALEINPOLICY1}- Namespace "AWS/EC2"-period 300-statistic "Average"-metricname "cpuutlilization" '-comparisonoperator ' Lessthanorequaltothreshold "-threshold 60-evaluationperiod 1

Last login to see, success

650) this.width=650; "src=" Http://s2.51cto.com/wyfs02/M01/84/61/wKiom1ePDxDA4WJtAAE2Z31VsPI509.png "style=" float: none; "title=" 11.PNG "alt=" Wkiom1epdxda4wjtaae2z31vspi509.png "/>



My script is simply the implementation of the above functions, the length of about 500 lines, various exception handling has not been added. If you are interested, you can contact me to see the full source code.

This article is from the "Mapo Tofu" blog, please be sure to keep this source http://beanxyz.blog.51cto.com/5570417/1828052

Powershell AWS Automation Management (12)-Create a highly available WordPress blog (bottom)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.