Highly Available Cloud Deployments
local graph
Chapter 11 — Highly Available Cloud Deployments
Section titled “Chapter 11 — Highly Available Cloud Deployments”Continuing with our AWS deployment, we will start to deploy services into the network we created in the previous chapter, and by the end of the chapter, we will be left with a highly available WordPress installation.
Building on top of the roles we created in the previous chapter, we will be doing the following:
- Launching and configuring an Application Load Balancer
- Launching and configuring Amazon Relational Database Service (RDS) (database)
- Launching and configuring Amazon Elastic File System (EFS) (shared storage)
- Launching an Elastic Compute Cloud (EC2) instance and creating an Amazon Machine Image (AMI) from it (deploying the WordPress code)
- Launching and configuring a launch template to use the newly created AMI and autoscaling group (high availability)
The chapter covers the following topics:
- Planning the deployment
- The Playbook
- Running the Playbook
- Terminating all the resources
Technical requirements
Section titled “Technical requirements”As in the previous chapter, we will be using AWS; you will need the access key and secret key we created in the previous chapter to launch the resources needed for our highly available WordPress installation. Please note that we will be launching resources that incur charges. Again, you can find the complete playbook in the Chapter11 folder of the accompanying GitHub repository at https://github.com/PacktPublishing/Learn-Ansible-Second-Edition/tree/main/Chapter11/.
Planning the deployment
Section titled “Planning the deployment”Before diving into the playbooks, we should get an idea of what we are trying to achieve. As mentioned, we will build on our AWS Virtual Private Cloud (VPC) role by adding instances and storage; our final deployment will look like the following diagram:

Figure 11.1 – An overview of what we shall be launching
In the diagram, we have the following:
- 2 x EC2 instances (t2.micro), deployed across different availability zones
- 1 x RDS instances (t2.micro)
- 1 x EFS storage across three availability zones
Before we talk about the deployment itself, based on the diagram and specifications here, how much is this deployment going to cost us to run?
Costing the deployment
Section titled “Costing the deployment”The cost of running this deployment in the EU-West-1 region is as follows:
| Instance Type | # Number | Instance cost | Total Monthly Cost |
|---|---|---|---|
| EC2 instances (t2.micro) | x2 | $9.20 | $18.40 |
| RDS instance (t2.micro) | x1 | $13.14 | $13.14 |
| Application Load Balancer | x1 | $24.24 | $24.24 |
| EFS | 5GB | $0.88 | $4.40 |
| Total | $61.83 |
Table 11.1 – Cost of running the deployment
There will be a few other minor costs, such as bandwidth and storing the AMI that contains our software stack. We could also consider increasing these costs by adding additional redundancy, such as updating our RDS instance to a multi-AZ RDS primary and stand-by instance deployment and increasing the number of EC2 instances.
However, this introduces additional complexity to our deployment, as we are about to spend the rest of the chapter covering the playbook, which will be deploying the resources. I want to keep this playbook as simple as possible for now.
WordPress considerations and high availability
Section titled “WordPress considerations and high availability”So far, we have been launching WordPress on a single server, which is fine. Still, as we are trying to remove as many of the single points of failure within our deployment as possible, we must put a little thought into how we initially configure and launch our deployment.
First, let’s discuss the order we need to launch our deployment. The primary order in which we will need to tackle the elements is as follows:
- VPC, subnets, internet gateway, routing, and security groups: These are all needed to launch our deployment.
- The Application Elastic Load Balancer: We will be using the public hostname of the Elastic Load Balancer for our installation, so this needs to be launched before we start our installation.
- The RDS database instance: Our database instance must be available before we launch our installation, as we need to create the WordPress database and bootstrap the installation.
- The EFS storage: We need some storage to share between the EC2 instances we will be launching next.
So far, so good; however, this is where we have to start taking WordPress into account.
As some of you may know from experience, the current version of WordPress is not designed to be spread across multiple servers. We can apply plenty of hacks and workarounds to make WordPress play nicely in this sort of deployment; however, this chapter is about something other than the finer points of deploying WordPress. Instead, it is about using Ansible to deploy a multi-tiered web application.
Because of this, we will be going for the most basic of the multi-instance WordPress options by deploying our code and content on the EFS volume. This means that all we must do is install our LEMP stack. It should be noted that this option could be more performant at a large scale, but it will serve our needs.
Now, back to the list of tasks. When it comes to launching our instances, we need to do the following:
- Launch a temporary EC2 instance running Ubuntu to reuse parts of existing playbooks.
- Update the operating system and install the software stack, supporting tools, and configuration needed for us to install and run our WordPress installation.
- Mount the EFS volume, set the correct permissions, and configure it to mount when the instance boots.
- Bootstrap WordPress itself.
- Create an AMI from our temporary instance and then terminate the temporary instance as it will not be needed now.
- Create a launch template that uses the AMI we just created.
- Create an autoscaling group and attach the launch configuration; it should also register our WordPress instances with the Elastic Load Balancer.
Further playbook runs, which will update the operating system and non-WordPress configuration, should repeat the process with the existing instances up and running, and then, once the AMI is built, it should be deployed alongside the current instances, which will then be terminated once the new instances are registered with the Elastic Load Balancer and receiving traffic.
This will allow us to update our operating system packages and configurations without downtime if everything goes as planned!
Now that we have an idea of what we are trying to achieve, let’s make a start on our playbook.
The Playbook
Section titled “The Playbook”We will use the Playbook we looked at in Chapter 10, Building Out a Cloud Network, as a starting point, as all the roles are relevant to our deployment, and it already has the structure we need for our playbook.
We will also be using the roles to deploy and configure WordPress and the supporting software stack we used in Chapter 9, Moving to the Cloud, with a few tweaks, which are needed as we are targeting AWS and not Microsoft Azure; I will let you know when we get to them.
Unlike previous chapters, we will first look at the site.yml file to get an idea of the order in which we will run the roles.
There are three stages in the file, starting with the stage that deploys and configures our underlying AWS resources:
- name: "Deploy and configure the AWS Environment" hosts: localhost connection: local gather_facts: true vars: state: "present" vars_files: - group_vars/common.yml roles: - vpc - subnets - gateway - securitygroups - elb - efs - rds - ec2tmp - endpointsAs you can see, this is the same as the site.yml file from Chapter 10, Building Out a Cloud Network, with additional roles added to the list from the securitygroups role downwards.
By the time our Playbook run gets to the second stage:
- name: "Install and configure Wordpress" hosts: vmgroup gather_facts: true become: true become_method: "ansible.builtin.sudo" vars_files: - group_vars/common.yml - group_vars/generated_aws_endpoints.yml roles: - stack_install - stack_config - wordpressA file called group_vars/generated_aws_endpoints.yml will have been generated, and there should be a temporary virtual machine instance up and running, meaning SSH should be accessible to the host running the Playbook.
Once this stage has been completed, our temporary virtual machine instance should have our software stack installed. WordPress will be freshly installed if this is the first time the playbook has been run, or if the playbook has detected an existing WordPress installation and left it alone unless there have been any changes to the plugin configuration from within the playbook.
The final stage is then run:
- name: "Create AMI and update the Auto Scaling Group" hosts: localhost connection: local gather_facts: true vars: state: "present" vars_files: - group_vars/common.yml roles: - ec2ami - autoscalingThis stage creates an AMI from the temporary virtual machine instance, terminates the temporary instance as we no longer need it, creates a new version of our launch template, and then creates/updates the Auto Scaling Group to deploy the new version on the EC2 instances.
Sounds simple? Well, let’s find out.
The variables
Section titled “The variables”Out of the box, there is a single variables file called group_vars/common.yml that contains all the static variables needed to deploy our environment.
Some additional files will be created in the group_vars folder throughout the Playbook run; they will contain some dynamically generated resources, such as passwords, resource names/endpoints, and other information.
We will discuss these files in more detail when we look at the tasks that create and interact with them; for now, we will look at the static variables defined within group_vars/common.yml, starting with the base application configuration.
Application and resource configuration
Section titled “Application and resource configuration”We start the configuration with the option to enable/disable debug when running the Playbook. By default, it is set to false; however, when running the Playbook, I recommend switching it to true and reviewing the output:
debug_output: falseNext, we have the application name, region, and environment reference:
app: name: "learnansible" region: "eu-west-1" env: "prod"The next block of variables defines details for the WordPress database; as we will be using the Amazon RDS service, we are just using the variables that are defined later in the file, so we only have to update the information in one place:
wp_database: name: "{{ rds.db_name }}" username: "{{ rds.db_username }}" password: "{{ rds.db_password }}"The next block is the various variables used to configure WordPress itself:
wordpress: domain: "http://{{ aws_endpoints.elb }}/" title: "WordPress installed by Ansible on {{ os_family }}" username: "ansible" password: "{{ rds.db_password }}" email: "[email protected]" plugins: - "jetpack" - "wp-super-cache" - "wordpress-seo" - "wordfence" - "nginx-helper"There are no significant changes to when we last defined these in Chapter 9*, Moving to the Cloud*, apart from using the aws_endpoints.lb variable, which won’t be known until the Elastic Load Balancer has been launched. Also, for ease of use, we are reusing the password, which will be dynamically generated later in the file, as the WordPress admin password.
Stack configuration
Section titled “Stack configuration”The next section overrides the defaults in the roles/stack_install role:
stack_packages: - "nginx" - "mariadb-client" - "php-cli" - "php-curl" - "php-fpm" - "php-gd" - "php-intl" - "php-mbstring" - "php-mysql" - "php-soap" - "php-xml" - "php-xmlrpc" - "php-zip" - "nfs-common" # Added for AWS - "nfs4-acl-tools" # Added for AWS - "autofs" # Added for AWS - "rpcbind" # Added for AWSWe have removed mariadb-server from the list of packages as we no longer need to install or configure a local database server, and we have added four packages at the end (all labeled # Added for AWS). These packages install the software required to mount the EFS filesystem using the NFS protocol, which leads us nicely into the next block:
nfs: mount_point: "/var/www/" mount_options: "nfsvers=4.1,rsize=1048576,wsize=1048576,hard,timeo=600,retrans=2" state: "mounted" fstype: "nfs4"As you can see, this defines some basic information on where the EFS filesystem should be mounted, with what options and the type of filesystem it is.
Resource names
Section titled “Resource names”This next section builds up the names of the resources we are going to be deploying; there is nothing too special happening here – it is just defined like this, so we don’t have to update repeated information in several places manually:
vpc_name: "{{ app.name }}-{{ app.env }}-{{ playbook_dict.vpc }}"internet_gateway_name: "{{ app.name }}-{{ app.env }}-{{ playbook_dict.internet_gateway }}"internet_gateway_route_name: "{{ internet_gateway_name }}-{{ playbook_dict.route }}"elb_target_group_name: "{{ app.name }}-{{ app.env }}-{{ playbook_dict.elb_target_group }}"elb_name: "{{ app.name }}-{{ app.env }}-{{ playbook_dict.elb }}"efs_name: "{{ app.name }}-{{ app.env }}-{{ playbook_dict.efs }}"rds_name: "{{ app.name }}-{{ app.env }}-{{ playbook_dict.rds }}"ec2_tmp_name: "{{ app.name }}-tmp-{{ playbook_dict.ec2 }}"ami_name: "{{ app.name }}-{{ app.env }}-{{ playbook_dict.ami }}"ec2_name: "{{ app.name }}-{{ app.env }}-{{ playbook_dict.ec2 }}"launch_template_name: "{{ app.name }}-{{ app.env }}-{{ playbook_dict.lt }}"asg_name: "{{ app.name }}-{{ app.env }}-{{ playbook_dict.asg }}"We will not be covering the full playbook_dict block here as there is not much to see, although as a reminder, this is what the start of it looks like:
playbook_dict: deployedBy: "Ansible" ansible_warning: "Resource managed by Ansible" vpc: "vpc"It just continues defining service names. The following section is where we start to define the variables used for the AWS resource deployment.
EC2 configuration
Section titled “EC2 configuration”The ec2 variable is split into a few different layers. Layers for the auto-scaling group, the AMI, and the SSH keypair follow some general settings:
ec2: instance_type: "t2.micro" public_ip: true ssh_port: "22"The variables are used across instances apart from the public_ip reference, which is only used when launching the temporary virtual machine instance to bootstrap WordPress.
The next layer defines some details about the auto-scaling group and launch template when used; they help define how many instances are launched, how updated instances are rolled out, and also, how the load balancer will check to see if they are healthy:
asg: min_size: 1 max_size: 3 desired_capacity: 2 health_check_type: "EC2" replace_batch_size: 1 health_check_period: 300 replace_all_instances: true wait_for_instances: true wait_timeout: 900 disable_api_termination: trueNext, we define the details about the base AMI we will use; as you can see, we are using Ubuntu 22.04, which is supplied by Canonical, the publisher and maintainer of Ubuntu:
ami: owners: "099720109477" filters: name: "ubuntu/images/hvm-ssd/ubuntu-jammy-22.04-amd64-server-*" virtualization_type: "hvm"Finally, we have some details on the keypair to upload to AWS and use when launching our Virtual Machine instances:
keypair: name: "ssh_keypair" key_material: "{{ lookup('file', '~/.ssh/id_rsa.pub') }}"Next up are the variables used when launching the RDS service.
RDS configuration
Section titled “RDS configuration”These are all standard, apart from the rds.db_password variable:
rds: db_username: "{{ app.name }}" db_password: "{{ lookup('password', 'group_vars/generated_rds_passwordfile chars=ascii_letters,digits length=30') }}" db_name: "{{ app.name }}" instance_type: "db.t2.micro" engine: "mysql" engine_version: "8.0" allocated_storage: "5"As you can see, we are using a lookup module to add a random password to the group_vars/generated_rds_passwordfile file; we are instructing the module to generate a 30-character random password comprising letters and numbers only.
EFS configuration
Section titled “EFS configuration”Here, we define the variables used to tell Ansible to wait and how long when creating the EFS resource:
efs: wait: "yes" wait_time: "1200"VPC and subnet configuration
Section titled “VPC and subnet configuration”This block remains unchanged from Chapter 10, Building Out a Cloud Network.
Security group configuration
Section titled “Security group configuration”Most of this block is unchanged from Chapter 10, Building Out a Cloud Network, as we now define the SSH port as ec2.ssh_port. I have updated the EC2 group to use this reference rather than hardcoding port 22 into the block. The only other addition is the following:
elb_seach_string: "elb"ec2_seach_string: "ec2"rds_seach_string: "rds"efs_seach_string: "efs"These will be used throughout the playbook when we query the AWS API for information on our security groups.
The final block
Section titled “The final block”As per Chapter 10, Building Out a Cloud Network, this contains the following:
region: "{{ app.region }}"That concludes our whistle-stop tour of the group_vars/common.yml file; as you can see, structure- and content-wise, we are following the same patterns as the last few chapters, where we group variables into logical blocks and trying to reuse references as much as possible throughout so that we don’t have to repeat information repeatedly.
The Playbook roles
Section titled “The Playbook roles”Now that we have covered the variables, we can work through the roles in the order they appear in the site.yml file.
The VPC, subnets, gateway, and security groups roles
Section titled “The VPC, subnets, gateway, and security groups roles”There are no changes to these roles from Chapter 10, Building Out a Cloud Network; they are just dropped in place and work as expected. The remaining roles in this section of the Playbook will reference the output of these roles when referring to subnets, security groups, and the VPC.
The Application Elastic Load Balancer (ELB) role
Section titled “The Application Elastic Load Balancer (ELB) role”In this role, we will deploy two resources, the first of which is a target group. This will be used when we launch our auto-scaling virtual machine instances – we attach our instances to the target group. Then, the target group is attached to the Application Elastic Load Balancer, which we will also launch in this role.
The task itself is pretty static, as you can see from the code for the following task:
- name: "Provision the target group" community.aws.elb_target_group: name: "{{ elb_target_group_name }}" region: "{{ region }}" state: "{{ state }}" protocol: "http" port: "80" deregistration_delay_timeout: "15" vpc_id: "{{ vpc_output.vpc.id }}" modify_targets: "false" tags: "Name": "{{ elb_target_group_name }}" "projectName": "{{ app.name }}" "environment": "{{ app.env }}" "deployedBy": "{{ playbook_dict.deployedBy }}" "description": "{{ playbook_dict.ansible_warning }}" "role": "target-group" register: elb_target_group_outputWe are just referencing variables, with the only dynamic content being the ID of the VPC, which is referenced from the vpc_output variable we registered when launching the VPC in the VPC role.
As we are registering some output in this role, we will continue by adding a debug task straight after; in this case, the task looks like the following:
- name: "Debug: ELB Target Group Output" ansible.builtin.debug: var: "elb_target_group_output" when: debug_outputAs we have already covered in Chapter 10, Building Out a Cloud Network, we will not be repeating these tasks in our overview of the Playbook unless we are doing something different – so, from now on, if we are registering an output, please assume that a debug task immediately follows.
There is one more bit of information we need before we create the ELB, and that’s the ID of the security group.
To get this, we can loop through the security_groups_with_rules_output variable and use set_fact to set the group_id when the group_name contains the contents of the elb_seach_string variable:
- name: Extract ELB Group ID ansible.builtin.set_fact: elb_group_id: "{{ item.group_id }}" loop: "{{ security_groups_with_rules_output.results }}" when: item.group_name is search(elb_seach_string)Whenever we need the ID of a security group, we will use this same pattern but update the name of the fact that is being set and the corresponding search steering variable.
The following task provisions the Application Elastic Load Balancer, which will be used to distribute HTTP requests across our auto-scaling managed virtual machine instances to serve our WordPress site:
- name: "Provision an application elastic load balancer" amazon.aws.elb_application_lb: region: "{{ region }}" name: "{{ elb_name }}" state: "{{ state }}" security_groups: "{{ elb_group_id }}" subnets: "{{ subnet_public_ids }}" listeners: - Protocol: "HTTP" Port: "80" DefaultActions: - Type: "forward" TargetGroupArn: "{{ elb_target_group_output.target_group_arn }}" tags: "Name": "{{ elb_name }}" "projectName": "{{ app.name }}" "environment": "{{ app.env }}" "deployedBy": "{{ playbook_dict.deployedBy }}" "description": "{{ playbook_dict.ansible_warning }}" "role": "load-balancer" register: loadbalancer_outputAs you can see, we are attaching the Application Elastic Load Balancer to the subnets defined listed in the subnet_public_ids, and we are attaching the security group with the ID defined in the elb_group_id fact that registered in the previous task.
We are then configuring a listener on port 80 to accept HTTP traffic and forward it to the Target Group we launched at the start of the role – which concludes the Application Elastic Load balancer role.
The Elastic File System (EFS) role
Section titled “The Elastic File System (EFS) role”The role starts with the task which sets the efs_group_id using the efs_seach_string variable. Once we know the ID of the security group we are applying to the EFS service, we can move on to the next task.
This task generates a file using a template and places it in the group_vars folder:
- name: "Generate the efs targets vars file" ansible.builtin.template: src: "targets.j2" dest: "group_vars/generated_efs_targets.yml" mode: "0644"The template file used to populate the file at group_vars/generated_efs_targets.yml looks like the following:
efs_targets:{% for item in subnet_storage_ids %} - subnet_id: "{{ item }}" security_groups: [ "{{ efs_group_id }}" ]{% endfor %}Here, we are using a Jinja2 for loop to loop through the contents of subnet_storage_ids, which will create a file that looks something like the following:
efs_targets: - subnet_id: "subnet01_id" security_groups: [ "efs_group_id" ] - subnet_id: "subnet02_id" security_groups: [ "efs_group_id" ] - subnet_id: "subnet03_id" security_groups: [ "efs_group_id" ]This means that when we create the EFS file system, it will be available across all the availability zones in our chosen region.
Well, it will be once we load in the contents of the file we have just loaded, which we do in the next task, as you can see here:
- name: "Include the efs targets vars file" ansible.builtin.include_vars: "group_vars/generated_efs_targets.yml"We now have everything in place to create the EFS file system, which is done using this task:
- name: "Create the EFS File System" community.aws.efs: name: "{{ efs_name }}" region: "{{ region }}" state: "{{ state }}" tags: "Name": "{{ efs_name }}" "projectName": "{{ app.name }}" "environment": "{{ app.env }}" "deployedBy": "{{ playbook_dict.deployedBy }}" "description": "{{ playbook_dict.ansible_warning }}" "role": "efs" targets: "{{ efs_targets }}" wait: "{{ efs.wait }}" wait_timeout: "{{ efs.wait_time }}" register: efs_outputIt can take a few minutes to create the file system, and we must wait until this task has succeeded before we continue, which is why we are using the wait flag. If we don’t wait, we increase the risk that the file system will not be ready by the time our virtual machine is launched and unable to mount it, which will cause the Playbook execution to fail.
Speaking of tasks that take a while, the next role deals with launching the Amazon RDS instance, which we will use as the database for our WordPress site. This task can take up to 10 minutes to complete.
The Amazon RDS role
Section titled “The Amazon RDS role”There are two main parts to the role; the first does a similar task to the one we had to do in the previous role when we created the targets for the EFS to be attached to.
The RDS service differs in that rather than passing in the subnets manually when we deploy the service, we can create a group natively on the AWS side and then reference it when we launch the RDS instance.
The task to create the RDS subnet group looks like the following:
- name: "Add RDS subnet group" amazon.aws.rds_subnet_group: name: "{{ rds_name }}" region: "{{ region }}" state: "{{ state }}" description: "{{ dict.ansible_warning }}" subnets: "{{ subnet_database_ids }}" tags: "Name": "{{ rds_name }}" "projectName": "{{ app.name }}" "environment": "{{ app.env }}" "deployedBy": "{{ playbook_dict.deployedBy }}" "description": "{{ playbook_dict.ansible_warning }}" "role": "rds" register: rds_subnet_group_outputOnce we have created the subnet group, we need to find the security group ID using the rds_seach_string variable and set a fact called rds_group_id.
Now we have all the information we need to launch the RDS instance, the task for which looks like the following:
- name: "Create the RDS instance" amazon.aws.rds_instance: id: "{{ rds_name }}" region: "{{ region }}" state: "{{ state }}" db_instance_class: "{{ rds.instance_type }}" engine: "{{ rds.engine }}" engine_version: "{{ rds.engine_version }}" allocated_storage: "{{ rds.allocated_storage }}" username: "{{ rds.db_username }}" password: "{{ rds.db_password }}" db_name: "{{ rds.db_name }}" db_subnet_group_name: "{{ rds_subnet_group_output.subnet_group.name }}" vpc_security_group_ids: ["{{ rds_group_id }}"] tags: "Name": "{{ rds_name }}" "projectName": "{{ app.name }}" "environment": "{{ app.env }}" "deployedBy": "{{ playbook_dict.deployedBy }}" "description": "{{ playbook_dict.ansible_warning }}" "role": "rds" register: rds_instance_outputAs mentioned at the end of the previous task, this can take quite a while to deploy, typically just over 10 minutes, so when we run the Playbook, this task will appear to have stalled.
So please do not worry – it is busy working away in the background.
Once this role has finished running, we will have all the core AWS resources we need to launch an EC2 instance, perform the software configuration, and install WordPress.
The temporary EC2 instance role
Section titled “The temporary EC2 instance role”Before we work through the tasks that launch the temporary instance, let’s go into a little more detail on why we need a temporary EC2 instance in the first place.
As we mentioned in the introduction, this instance will be running Ubuntu, and we will be targeting it with slightly modified copies of the stack_install, stack_config, and wordpress roles that we first ran locally in Chapter 5, Deploying WordPress, and against a single cloud instance in Chapter 9, Moving to the Cloud.
One of the modifications we will be making to the roles is installing the software needed to mount our EFS, which we will then use to store the WordPress code and supporting files for our WordPress installation, meaning that we have everything we need file-wise for WordPress on a shared file system we can then mount on multiple virtual machine instances.
The second change is that rather than installing a database server on our local instance, we will be using the Amazon RDS database service for WordPress, meaning that we can have multiple instances of WordPress, all being able to connect to a single remote database.
Great, you may be thinking to yourself, but that doesn’t explain why this is a temporary instance.
Well, once everything has been installed, mounted, configured, and WordPress bootstrapped, we will be making our own Amazon Machine Image (AMI) and terminating the temporary EC2 instance. Once it’s been terminated, we will take the AMI and configure our Auto Scaling Group to use the newly created image, which will either trigger the deployment of new hosts if it is our first time running the Playbook or it will launch more instances and terminate the old ones if we have already had virtual machine instances running our WordPress installation.
When these virtual machine instances boot up using our custom AMI, they will already have NGINX and PHP installed and configured, ready to serve WordPress, and the EFS containing our WordPress files will be mounted, meaning that our servers will be good to go as soon as they are deployed.
All of this means our WordPress installation should be sound to scale up if we have an influx of traffic hitting the site for whatever reason, and all instances of our virtual machines will be running a known good configuration; in fact, it will be the same configuration as the other hosts serving our WordPress site.
Just as important, as we are not relying on anything on the local virtual machine instances filesystem, we are just as good at automatically scaling down by terminating hosts automatically when the influx of traffic has subsided without the risk of data loss or availability.
If this approach is planned right – in theory, we don’t even need SSH access to the hosts launched by the Auto Scaling Group as we should never need to manage them manually, and we can treat them as short-lived instances where we don’t have to care if they are running or terminated – just that we have the desired of instances delivering our application.
So, now that we know why we are taking this approach, let’s return to the Playbook and look at the tasks needed to get this temporary EC2 instance up and running to the point where we can SSH to it and install our software and WordPress.
The first task is to get a list of all the Ubuntu AMIs using the variables we covered earlier in the chapter:
- name: "Gather information about AMIs with the specified filters" amazon.aws.ec2_ami_info: region: "{{ region }}" owners: "{{ ec2.ami.owners }}" filters: name: "{{ ec2.ami.filters.name }}" virtualization-type: "{{ ec2.ami.filters.virtualization_type }}" register: ubuntu_ami_infoThe list of AMIs returned will contain all of the various AMI versions for our chosen Ubuntu version; we only need to know the ID of the latest version published by Canonical (the publisher and maintainer of Ubuntu) so we know we are using the most up-to-date image that contains the latest patches and any bug fixes.
Luckily, each AMI returned in the list has a key called creation_date, the value of which, as you may have guessed, is the date and time the AMI was published. This means we can run the following task to get the ID of the latest version of the AMI:
- name: "Filter the list of AMIs to find the latest one" ansible.builtin.set_fact: ami: "{{ ubuntu_ami_info.images | sort(attribute='creation_date') | last }}"As you can see, this takes the content of the list, which is defined as ubuntu_ami_info.images, sorts the list by creation_date, and then takes the ID of the last AMI in the list as, by default, they are sorted in ascending order.
Now that we know the ID of the most up-to-date Ubuntu AMI, we can progress with more preparation work before launching our EC2 instance.
We now need to create an SSH key pair on the AWS side. This will contain the public portion of the SSH key we will use to access the EC2 instance when it is launched – the task to configure this looks like the following and uses the variables we covered earlier in the chapter to get the contents of the public portion of our SSH key:
- name: "Create a SSH Key Pair" amazon.aws.ec2_key: region: "{{ region }}" state: "{{ state }}" name: "{{ ec2.keypair.name }}" key_material: "{{ ec2.keypair.key_material }}" tags: "Name": "{{ ec2.keypair.name }}" "projectName": "{{ app.name }}" "environment": "{{ app.env }}" "deployedBy": "{{ playbook_dict.deployedBy }}" "description": "{{ playbook_dict.ansible_warning }}" "role": "ssh_keypair" register: keypair_outputFinally, before we launch our EC2 instance, we need the ID of the security group, which allows the public IP address of our host running Ansible SSH access to the EC2 instance. To do this, we set a fact called ec2_group_id using the ec2_seach_string variable to find the correct group ID.
Now, we have everything in place to launch the EC2 instance using the following task:
- name: "Create the temporary ec2 instance" amazon.aws.ec2_instance: name: "{{ ec2_tmp_name }}" region: "{{ region }}" state: "{{ state }}" vpc_subnet_id: "{{ subnet_compute_ids[0] }}" instance_type: "{{ ec2.instance_type }}" security_group: "{{ ec2_group_id }}" key_name: "{{ ec2.keypair.name }}" network: assign_public_ip: "{{ ec2.public_ip }}" image_id: "{{ ami.image_id }}" tags: Name: "{{ ec2_tmp_name }}" Description: "{{ dict.ansible_warning }}" Project: "{{ app.name }}" Environment: "{{ app.env }}" Deployed_by: "Ansible" Role: "tmp" register: ec2_tmp_instance_outputThe only thing pointed out in the preceding task is that when we add the value for the vpc_subnet_id we can only pass in a single ID. As we don’t need this virtual machine instance to be highly available, that is not a problem, so we are using the first ID in the list of subnet IDs by using the {{ subnet_compute_ids[0] }}.
When launching an EC2 instance in AWS, it goes through a few stages and, by default, the amazon.aws.ec2_instance module creates the instance and doesn’t wait for the status to change from creating to running.
Our next task polls the AWS API waiting for the status of our EC2 instance to be running:
- name: "Get information about the temporary EC2 instance to see if it is running" amazon.aws.ec2_instance_info: region: "{{ region }}" filters: instance-id: "{{ ec2_tmp_instance_output.instances[0].instance_id }}" register: ec2_tmp_instance_state delay: 5 retries: 50 until: ec2_tmp_instance_state.instances[0].state.name == "running"As you can see, the previous task takes the ID of our newly created EC2 instance and polls the AWS API every 5 seconds, a maximum of 50 times, until the value of ec2_tmp_instance_state.instances[0].state.name is equal to running.
You might think to yourself that it seems a bit overkill to do that, and 99% of the time, you would be correct – it usually takes no more than a few checks for the status to change. Still, there is the odd occasion that AWS might be on a “go-slow,” and during testing, I have seen it take up to 15 checks, or just over a minute, for the status to change, so we need to take this delay into account in our Playbook as it could break the Playbook execution if we don’t.
The next task takes the details, the DNS name and IP address, of our now-running EC2 instance and adds them to the host group called vmgroup:
- name: "Add the temporary EC2 instance to the vmgroup" ansible.builtin.add_host: name: "{{ ec2_tmp_instance_output.instances[0].public_dns_name }}" ansible_ssh_host: "{{ ec2_tmp_instance_output.instances[0].public_ip_address }}" groups: "vmgroup"Before we hand off to the next role, we should perform one more check.
Sometimes, the Ansible Playbook works through the tasks so quickly that it is possible that even though our EC2 instance has a status of running, it does not mean that the host has finished booting, and SSH is started and is accessible:
- name: "Wait for the temporary EC2 instance to be ready to accept SSH connections" ansible.builtin.wait_for: host: "{{ ec2_tmp_instance_output.instances[0].public_ip_address }}" port: "{{ ec2.ssh_port }}" delay: 10 timeout: 300Now that we have confirmation that our EC2 host is accessible to our machine running Ansible using SSH, we can proceed to the final role in this section of the site.yml file.
The endpoints role
Section titled “The endpoints role”This role has a single task, which creates a file at generated_aws_endpoints.yml containing the name of the AWS endpoints for the EFS, RDS, and ELB resources we have created:
- name: "Generate the aws endpoints file" ansible.builtin.template: src: "endponts.j2" dest: "group_vars/generated_aws_endpoints.yml" mode: "0644"The endponts.j2 template file looks like the following:
aws_endpoints: efs: "{{ efs_output.efs.filesystem_address.split(':')[0] }}" rds: "{{ rds_instance_output.endpoint.address }}" elb: "{{ loadbalancer_output.dns_name }}"Both the RDS and ELB endpoints are straightforward enough; for the EFS, you might notice something at the end – what is that for?
None of the output that is registered under the efs_output.efs variable contains just the address of the EFS endpoint. The one we are using, filesystem_address, has information on the file system mount, which is represented by appending :/ to the end of the DNS address we need.
To get around this, we are using the split function, passing : as the delimiter and then taking the first section, which is defined as 0, meaning that we end up with everything before the :, which is the DNS name we are after.
Now that we have a populated group_vars/generated_aws_endpoints.yml file, we can load it into the second section of the site.yml file as a variable file, saving us from having to interact with the AWS from our EC2 instance.
So, now that we have our EC2 instance up and running, let’s get our software stack installed, configured, and WordPress bootstrapped.
The stack install role
Section titled “The stack install role”The tasks in this role remain unchanged from the previous times we have executed the Playbook because all the changes we have made are in the stack_packages variable we are passing in.
As a reminder, this role does the following:
- Updates the APT cache and ensures that the installed packages are running the latest available versions – which shouldn’t be too many as we are using the newest AMI
- Imports the APT keys for the additional repositories we will be enabling
- Installs the packages containing details of the additional repositories and enables them
- Installs the packages listed in the
system_packages,extra_packages, andstack_packagesvariables –system_packagesandextra_packagescontain the default values we have been using throughout, and because we are passing the updatedstack_packagesvariable via thegroup_vars/common.ymlfile, this overrides the default values from previous chapters which are still defined in theroles/stack_install/defaults/main.ymlfile
This leaves us with all the base software we need to install on the EC2 instance.
The stack configuration role
Section titled “The stack configuration role”Unlike the previous role, there are some amendments to this role, starting with additional tasks out of the gate.
Three tasks are added to the top of roles/stack_config/tasks/main.yml, the first of which is a continuation of the checks we did towards the end of the roles in the last section of the site.yml file:
- name: "Check that the EFS volume is ready" ansible.builtin.wait_for: host: "{{ aws_endpoints.efs }}" port: "2049" delay: 10 timeout: 300As you can see, this checks that port 2049 is accessible at the endpoint defined in aws_endpoints.efs; the reason why this is there is that while the EFS service is ready, it may take a little while for the DNS records for the endpoint to be updated and accessible within the VPC. As we will soon attempt to mount the EFS filesystem, we must ensure it is accessible before proceeding.
The next task is to ensure that the RPC Bind service is up and running; we will need to mount the EFS file system:
- name: "ensure rpcbind service is running" ansible.builtin.service: name: "rpcbind" state: "started" enabled: trueThe final additional task mounts the EFS and ensures that it is added to the file system configuration to ensure that from now on, the EFS is mounted when the EC2 instance boots:
- name: "mount the EFS volume" ansible.posix.mount: src: "{{ aws_endpoints.efs }}:/" path: "{{ nfs.mount_point }}" opts: "{{ nfs.mount_options }}" state: "{{ nfs.state }}" fstype: "{{ nfs.fstype }}"As you will have already seen from when we covered the variables at the start of the chapter, we are mounting the EFS at /var/www/; we are making sure to do this before the following two tasks to ensure that our WordPress users home directory is created on the share.
These two tasks remain unchanged from the last time we installed WordPress, as does the value of wordpress_system.home, which is /var/www/wordpress.
So, now that we have created our WordPress user and group, we can proceed with the rest of the tasks:
- Update
/etc/nginx/nginx.confwith some sensible defaults - Create the configuration for our default host at
/etc/nginx/conf.d/default.conf - Create the
/etc/nginx/globaldirectory and copy therestrictions.confandwordpress_shared.conffiles there
The next task is more of a quality-of-life improvement to do with the way our Playbook deals with PHP, as this Playbook is designed to keep our WordPress installation up to date by taking the base Ubuntu image and bootstrapping from scratch each time rather than managing the configuration in place. It is possible that the version of PHP could change at some point during the life of our WordPress installation.
So far, whenever the stack_config role has been executed, it has been using the following variables:
php_fpm_path: "/etc/php/8.1/fpm/pool.d/www.conf"php_ini_path: "/etc/php/8.1/fpm/php.ini"php_service_name: "php8.1-fpm"As you can see, 8.1 is a hardcoded value. While we can overwrite these variables at the variable level elsewhere in our configuration, it would be better to work out which version of PHP is installed at runtime and reference that.
To do this, we can update these values as follows:
php_fpm_path: "/etc/php/{{ php_version }}/fpm/pool.d/www.conf"php_ini_path: "/etc/php/{{ php_version }}/fpm/php.ini"php_service_name: "php{{ php_version }}-fpm"This means we now must find a way to populate the php_version variable with the relevant version of PHP.
To do this, we can run the php -v command, which returns a lot of information on the version of PHP installed. We then use the head and a few cut commands on the Linux command line using the ansible.builtin.shell and not a built-in Ansible function:
- name: "Get the PHP version" ansible.builtin.shell: cmd: "php -v | head -n 1 | cut -d ' ' -f 2 | cut -c 1-3" register: php_version_outputHere is a detailed breakdown of the command we are getting Ansible to run:
php -v: This command, when run, outputs the version information of the PHP installed on the host the command is being executed on; this output is typically a multi-line text that includes the PHP version along with additional information on how the version of the PHP was compiled.|: This symbol is known as a pipe. It takes the command output on its left (in this case,php -v) and uses it as the input for the command on its right. It’s a way of passing data between programs.head -n 1: This command processes the input received from the previous command; the head command outputs the first part of the files or data it receives.-n 1is an option that tellsheadto output only the first line. So, in our case,head -n 1takes the multiple lines of output fromphp -vand returns just the very first line.|: Another pipe, which again passes the command output on its left,head -n 1, to the command on its right.cut -d ' ' -f 2: This command is used for cutting out sections of each input line.-d ' 'is an option where-dstands for the delimiter, and' '(a space) is the delimiter being used. This tells cut to divide each line into sections based on spaces.-f 2means field 2. This option tells thecutcommand to select the second field of the line in the standard format of the PHP version output; this field should be the version number.|: Again, we have another pipe, passing the output, now just the version number, to the following command.cut -c 1-3: This further processes the version number.-c 1-3tellscutto return only the characters in positions1through3of the string it receives. For a typical PHP version such as8.2.1, this would result in8.2, which is precisely what we need to proceed with the rest of our tasks.
We can then take the output and register it as php_version_output, and set the php_version variable as a fact:
- name: "Set the PHP version" ansible.builtin.set_fact: php_version: "{{ php_version_output.stdout }}"Now that we have the PHP version, we can proceed with the remainder of the PHP tasks, which copy the www.conf file to /etc/php/{{ php_version }}/fpm/pool.d/www.conf and also update the PHP.ini file at /etc/php/{{ php_version }}/fpm/php.ini.
With those files in place, we start the PHP-FPM and NGINX services, ensuring that they are set to start on boot.
The final task in the role is to create the ~/.my.cnf file and populate it with the information of our Amazon RDS instance. All of the other MariaDB tasks, which are there to start and configure our local MariaDB server, are commented out as we no longer install a local database server, so we don’t need to run the tasks to configure it.
The WordPress role
Section titled “The WordPress role”There are just two tasks commented out in this role. The tasks that create the database and the database user are not needed because when the Amazon RDS instance started, the database and user were made for us, meaning these two tasks are redundant.
All other tasks remain; for more details, see Chapter 5, Deploying WordPress.
The EC2 AMI role
Section titled “The EC2 AMI role”Now that our software stack is installed and configured and WordPress is sorted, it is time to create the AMI from our temporary instance.
The first thing we need to do is get the details on our temporary EC2 instance; as our host group contains the DNS name of the instance, we can use this:
- name: "Find out some facts about the instance we have been using" amazon.aws.ec2_instance_info: region: "{{ region }}" filters: dns-name: "{{ groups['vmgroup'] }}" register: our_instanceNow that we have the information on the instance we would like to create the AMI from registered as our_instance, we can proceed with the AMI creation:
- name: "Create the AMI" amazon.aws.ec2_ami: region: "{{ region }}" state: "{{ state }}" instance_id: "{{ our_instance.instances[0].instance_id }}" wait: "yes" name: "{{ ami_name }}-{{ ansible_date_time.date }}_{{ ansible_date_time.hour }}{{ ansible_date_time.minute }}" tags: "Name": "{{ ami_name }}-{{ ansible_date_time.date }}_{{ ansible_date_time.hour }}{{ ansible_date_time.minute }}" "buildDate": "{{ ansible_date_time.date }} {{ ansible_date_time.time }}" "projectName": "{{ app.name }}" "environment": "{{ app.env }}" "deployedBy": "{{ playbook_dict.deployedBy }}" "description": "{{ playbook_dict.ansible_warning }}" "role": "{{ playbook_dict.ami }}" register: ami_outputThere are just a few things to point out here. As you can see, we are using ansible_date_time to generate the date and get the current time as an hour and minute. We are using this both to give a unique name for the AMI and add a tag called buildDate.
The reason why we are using both the date and time is that it could be possible that we will need to create multiple AMIs on a single day, so it is important that we can easily identify them by name.
Once the AMI is created, we do not need the temporary instance, so we can terminate it:
- name: "Remove any temporary instances which are running" amazon.aws.ec2_instance: region: "{{ region }}" state: "absent" name: "{{ ec2_tmp_name }}" filters: instance-state-name: "running" "tag:Name": "{{ ec2_tmp_name }}" "tag:Role": "tmp" "tag:Project": "{{ app.name }}"Once the EC2 instance has been terminated, there is one more task in the role:
- name: "Wait for 2 minutes before continuing" ansible.builtin.pause: minutes: 2This does exactly what it says: it pauses the Playbook execution for 2 minutes.
I have included this because there was the odd occasion where the AMI was created and shown as available. Still, for some reason, it takes a short while for it to appear in the results when we query the Amazon API to find our AMIs, so rather than introduce a potential error when the next role starts, I have found it best to wait a minute or two.
The auto-scaling role
Section titled “The auto-scaling role”We have arrived at the final role of the Playbook; in this role, we will create all the resources needed to deploy EC2 instances using our newly created AMI and register them with the ELB to access our WordPress site.
The first thing we need to do is grab a list of all our AMIs from the API:
- name: "Search for all of our AMIs" amazon.aws.ec2_ami_info: region: "{{ region }}" filters: name: "{{ ami_name }}-*" register: ami_findNow that we have a list of AMIs, we need to filter out the most recent one. To do this, we use the same logic that we used when launching the temporary EC2 instance:
- name: "Find the last one we built" ansible.builtin.set_fact: ami_sort_filter: "{{ ami_find.images | sort(attribute='creation_date') | last }}"Now that we have filtered our list of AMIs down to the latest one, we need to set two facts, one for the name of the AMI and the other containing the ID of the AMI:
- name: "Grab AMI ID and name of the most recent result" ansible.builtin.set_fact: our_ami_id: "{{ ami_sort_filter.image_id }}" our_ami_name: "{{ ami_sort_filter.name }}"The final bit of information we need before we start creating/updating resources is the ID of the security group we are using for the EC2 instances.
As before, we use the ec2_seach_string variable to find the correct group ID and set a fact called ec2_group_id.
Next up, we need to create or update a launch template if one already exists.
A launch template contains the basic configuration for the instances we will be launching in the auto-scaling group:
- name: "Create the launch template" community.aws.ec2_launch_template: region: "{{ region }}" state: "{{ state }}" name: "{{ launch_template_name }}" version_description: "{{ our_ami_name }}" image_id: "{{ our_ami_id }}" security_group_ids: ["{{ ec2_group_id.security_groups[0].group_id }}"] instance_type: "{{ ec2.instance_type }}" disable_api_termination: "{{ ec2.asg.disable_api_termination }}" tags: "Name": "{{ ec2_name }}" "projectName": "{{ app.name }}" "environment": "{{ app.env }}" "deployedBy": "{{ playbook_dict.deployedBy }}" "description": "{{ playbook_dict.ansible_warning }}" "role": "launchTemplate"With this task, we create the launch template and then publish a version called after the name of our AMI so that we can quickly identify it; we then attach the corresponding AMI ID and security group ID and set the spec of the instances we want to launch.
With the launch template in place, we need to gather a few more bits of information from the AWS API before creating the auto-scaling group.
First, we need the ID of the target group that we created in the ELB role:
- name: "Find out the target group ARN" community.aws.elb_target_group_info: region: "{{ region }}" names: - "{{ elb_target_group_name }}" register: elb_target_group_outputWe then need the IDs of the subnets where we are going to be deploying the EC2 instances launched as part of auto-scaling group, the following task gathers information on the subnets:
- name: "Get information on the ec2 subnets" amazon.aws.ec2_vpc_subnet_info: region: "{{ region }}" filters: tag:role: "*{{ subnet_role_compute }}*" register: ec2_subnet_outputNow that we have the information on the subnets, we need to extract just the IDs of each of the subnets and create a list:
- name: "Create a list of subnet IDs" ansible.builtin.set_fact: subnet_ec2_ids: "{{ subnet_ec2_ids | default([]) + [item.subnet_id] }}" loop: "{{ ec2_subnet_output.subnets }}"This is the final bit of information we need, and we can now proceed with creating or updating the auto-scaling group:
- name: "Create/update the auto-scaling group using the launch template we just created" amazon.aws.autoscaling_group: region: "{{ region }}" state: "{{ state }}" name: "{{ asg_name }}" target_group_arns: ["{{ elb_target_group_output.target_groups[0].target_group_arn }}"] launch_template: launch_template_name: "{{ launch_template_name }}" min_size: "{{ ec2.asg.min_size }}" max_size: "{{ ec2.asg.max_size }}" desired_capacity: "{{ ec2.asg.desired_capacity }}" health_check_period: "{{ ec2.asg.health_check_period }}" health_check_type: "{{ ec2.asg.health_check_type }}" replace_all_instances: "{{ ec2.asg.replace_all_instances }}" replace_batch_size: "{{ ec2.asg.replace_batch_size }}" vpc_zone_identifier: "{{ subnet_ec2_ids }}" wait_for_instances: "{{ ec2.asg.wait_for_instances }}" wait_timeout: "{{ ec2.asg.wait_timeout }}" tags: - key: "Name" value: "{{ ec2_name }}" propagate_at_launch: true - key: "Project" value: "{{ app.name }}" propagate_at_launch: true - key: "Environment" value: "{{ app.env }}" propagate_at_launch: true - key: "Deployed_by" value: "Ansible" propagate_at_launch: true register: ec2_asg_outputThere is quite a lot happening in this, the final resource we will be launching, so let’s go into more detail.
First, we have the basic configuration standard across most of the AWS-related modules we have called throughout this Playbook; here, we are setting the name, region, and state of the resource, which will be present for this playbook.
Next up, we must provide the Target Group Amazon Resource Names (ARNs). The target_group_arns key specifies the ARNs of the target groups for the load balancer, which we set to the first target group ARN from elb_target_group_output and then the launch_template key references the launch template by its name, set to the value of launch_template_name.
Now we have the size and capacity settings; the min_size, max_size, and desired_capacity keys are set using ec2.asg.min_size, ec2.asg.max_size, and ec2.asg.desired_capacity variables, which define the auto-scaling group’s minimum, maximum, and desired number of instances.
We then have the health check configuration, setting the health_check_period and health_check_type keys to control how the health of the instances in the auto scaling group (ASG) is checked.
Now we have the Instance Replacement Settings. The replace_all_instances and replace_batch_size keys instruct whether all instances should be replaced and provide the batch size for replacing instances, respectively.
Then, we have the Network Configuration, setting vpc_zone_identifier to use the list of subnet IDs stored in subnet_ec2_ids to distribute the instances in the ASG across those subnets and availability zones.
Next up are the Wait Settings, which control whether the task should wait for the instances to have a status of running and the maximum time to wait for that condition to be met.
Finally, you will have noticed that we are tagging in a pretty different way than we have been doing throughout the rest of the Playbook; the task defines several tags (Name, Project, Environment, and Deployed_by) with respective values, all marked to propagate at launch, which means that the EC2 instances launched by the auto-scaling group will each inherit these tags when they are launched.
This concludes our walk-through of the Playbook. As you will have seen, we extended our original AWS networking Playbook from Chapter 10, Building Out a Cloud Network, to encompass more services as well as integrating our WordPress roles from the Playbook we covered in Chapter 5, Deploying WordPress – all that is left now is run the playbook.
Running the Playbook
Section titled “Running the Playbook”Now that we have all the roles needed to deploy our resources into AWS, we can run the playbook. To start with, we need to let Ansible know our access key and secret by running the following commands with your own credentials to set the environment variables:
$ export AWS_ACCESS_KEY=AKIAI5KECPOTNTTVM3EDA$ export AWS_SECRET_KEY=Y4B7FFiSWl0Am3VIFc07lgnc/TAtK5+RpxzIGTrWith environment variables set, you kick off the Ansible run by using the following command:
$ ansible-playbook -i hosts site.ymlUnlike previous chapters, where we just looked at the end of the playbook run, here we will look at some highlights of what happens when we deploy our resources.
Playbook run highlights
Section titled “Playbook run highlights”This is not the complete playbook output, and when running the playbook, I have not enabled debug, so all those tasks will be skipped.
We start with the VPC:
PLAY [Deploy and configure the AWS Environment] ***********TASK [Gathering Facts] ************************************ok: [localhost]TASK [roles/vpc : Create VPC] *****************************changed: [localhost]We now have somewhere to put the subnets once we have gathered some information on the availability zones in our chosen region:
TASK [roles/subnets : Get some information on the available zones] *************ok: [localhost]Once we have that information, it will loop through and include the create_subnet.yml tasks:
TASK [roles/subnets : Create all subnets] *****************included: create_subnet.yml for localhost => (item={'name': 'ec2', 'role': 'compute'})included: create_subnet.yml for localhost => (item={'name': 'rds', 'role': 'database'})included: create_subnet.yml for localhost => (item={'name': 'efs', 'role': 'storage'})included: create_subnet.yml for localhost => (item={'name': 'dmz', 'role': 'public'})We then get the results of each of the four included task runs, the first of which looks like the following:
TASK [roles/subnets : Create subnet in the availability zone] *****************************************************changed: [localhost] => (item={'state': 'available', 'opt_in_status': 'opt-in-not-required', 'messages': [], 'region_name': 'eu-west-1', 'zone_name': 'eu-west-1a', 'zone_id': 'euw1-az1', 'group_name': 'eu-west-1', 'network_border_group': 'eu-west-1', 'zone_type': 'availability-zone'})changed: [localhost] => (item={'state': 'available', 'opt_in_status': 'opt-in-not-required', 'messages': [], 'region_name': 'eu-west-1', 'zone_name': 'eu-west-1b', 'zone_id': 'euw1-az2', 'group_name': 'eu-west-1', 'network_border_group': 'eu-west-1', 'zone_type': 'availability-zone'})changed: [localhost] => (item={'state': 'available', 'opt_in_status': 'opt-in-not-required', 'messages': [], 'region_name': 'eu-west-1', 'zone_name': 'eu-west-1c', 'zone_id': 'euw1-az3', 'group_name': 'eu-west-1', 'network_border_group': 'eu-west-1', 'zone_type': 'availability-zone'})As you can see, a subnet is created for each of the zones in the eu-west-1 region – this is then repeated three more times. Once the subnets have all been added, we grab more information on what has been created.
Next, the Internet Gateway role is run:
TASK [roles/gateway : Create an Internet Gateway] *********changed: [localhost]TASK [roles/gateway : Create a route table so the internet gateway can be used by the public subnets] ****************changed: [localhost]As you may have remembered, there isn’t much happening in that role, unlike the next one, which adds the network security groups, where we start by getting your current public IP address:
TASK [roles/securitygroups : Find out your current public IP address using https://ipify.org/] **********************ok: [localhost]TASK [roles/securitygroups : Set your public ip as a fact]*ok: [localhost]As you may recall, we create the two groups in two parts – first, we create the base groups:
TASK [roles/securitygroups : Create the base security groups] ***************************************************changed: [localhost] => (item={'name': 'learnansible-elb-security-group', 'description': 'opens port 80 and 443 to the world', 'id_var_name': 'elb_group_id', 'rules': [{'proto': 'tcp', 'from_port': '80', 'to_port': '80', 'cidr_ip': '0.0.0.0/0', 'rule_desc': 'allow all on port 80'}, {'proto': 'tcp', 'from_port': '443', 'to_port': '443', 'cidr_ip': '0.0.0.0/0', 'rule_desc': 'allow all on port 443'}]})changed: [localhost] => (item={'name': 'learnansible-ec2-security-group', 'description': 'opens port 22 to a trusted IP and port 80 to the elb group', 'id_var_name': 'ec2_group_id', 'rules': [{'proto': 'tcp', 'from_port': '22', 'to_port': '22', 'cidr_ip': '86.177.22.88/32', 'rule_desc': 'allow 86.177.22.88/32 access to port 22'}, {'proto': 'tcp', 'from_port': '80', 'to_port': '80', 'group_id': '', 'rule_desc': 'allow access to port 80 from ELB'}]})changed: [localhost] => (item={'name': 'learnansible-rds-security-group', 'description': 'opens port 3306 to the ec2 instances', 'id_var_name': 'rds_group_id', 'rules': [{'proto': 'tcp', 'from_port': '3306', 'to_port': '3306', 'group_id': '', 'rule_desc': 'allow access to port 3306'}]})changed: [localhost] => (item={'name': 'learnansible-efs-security-group', 'description': 'opens port 2049 to the ec2 instances', 'id_var_name': 'efs_group_id', 'rules': [{'proto': 'tcp', 'from_port': '2049', 'to_port': '2049', 'group_id': '', 'rule_desc': 'allow access to port 2049'}]})Then we get information on the bases we have just launched and set them as facts:
TASK [roles/securitygroups : Set the fact for the security group ids] ************************************************ok: [localhost] => (item={'name': 'learnansible-elb-security-group', 'description': 'opens port 80 and 443 to the world', 'id_var_name': 'elb_group_id', 'rules': [{'proto': 'tcp', 'from_port': '80', 'to_port': '80', 'cidr_ip': '0.0.0.0/0', 'rule_desc': 'allow all on port 80'}, {'proto': 'tcp', 'from_port': '443', 'to_port': '443', 'cidr_ip': '0.0.0.0/0', 'rule_desc': 'allow all on port 443'}]})ok: [localhost] => (item={'name': 'learnansible-ec2-security-group', 'description': 'opens port 22 to a trusted IP and port 80 to the elb group', 'id_var_name': 'ec2_group_id', 'rules': [{'proto': 'tcp', 'from_port': '22', 'to_port': '22', 'cidr_ip': '86.177.22.88/32', 'rule_desc': 'allow 86.177.22.88/32 access to port 22'}, {'proto': 'tcp', 'from_port': '80', 'to_port': '80', 'group_id': '', 'rule_desc': 'allow access to port 80 from ELB'}]})ok: [localhost] => (item={'name': 'learnansible-rds-security-group', 'description': 'opens port 3306 to the ec2 instances', 'id_var_name': 'rds_group_id', 'rules': [{'proto': 'tcp', 'from_port': '3306', 'to_port': '3306', 'group_id': '', 'rule_desc': 'allow access to port 3306'}]})ok: [localhost] => (item={'name': 'learnansible-efs-security-group', 'description': 'opens port 2049 to the ec2 instances', 'id_var_name': 'efs_group_id', 'rules': [{'proto': 'tcp', 'from_port': '2049', 'to_port': '2049', 'group_id': '', 'rule_desc': 'allow access to port 2049'}]})Lastly, we then add the rules; you will notice from the output that we are passing in the IDs of the groups we have created so that we can use them as part of the rules:
TASK [roles/securitygroups : Provision security group rules] ****************************************************changed: [localhost] => (item={'name': 'learnansible-elb-security-group', 'description': 'opens port 80 and 443 to the world', 'id_var_name': 'elb_group_id', 'rules': [{'proto': 'tcp', 'from_port': '80', 'to_port': '80', 'cidr_ip': '0.0.0.0/0', 'rule_desc': 'allow all on port 80'}, {'proto': 'tcp', 'from_port': '443', 'to_port': '443', 'cidr_ip': '0.0.0.0/0', 'rule_desc': 'allow all on port 443'}]})changed: [localhost] => (item={'name': 'learnansible-ec2-security-group', 'description': 'opens port 22 to a trusted IP and port 80 to the elb group', 'id_var_name': 'ec2_group_id', 'rules': [{'proto': 'tcp', 'from_port': '22', 'to_port': '22', 'cidr_ip': '86.177.22.88/32', 'rule_desc': 'allow 86.177.22.88/32 access to port 22'}, {'proto': 'tcp', 'from_port': '80', 'to_port': '80', 'group_id': 'sg-04f31e782e30e1f0a', 'rule_desc': 'allow access to port 80 from ELB'}]})changed: [localhost] => (item={'name': 'learnansible-rds-security-group', 'description': 'opens port 3306 to the ec2 instances', 'id_var_name': 'rds_group_id', 'rules': [{'proto': 'tcp', 'from_port': '3306', 'to_port': '3306', 'group_id': 'sg-05bffd3eb96602519', 'rule_desc': 'allow sg-05bffd3eb96602519 access to port 3306'}]})changed: [localhost] => (item={'name': 'learnansible-efs-security-group', 'description': 'opens port 2049 to the ec2 instances', 'id_var_name': 'efs_group_id', 'rules': [{'proto': 'tcp', 'from_port': '2049', 'to_port': '2049', 'group_id': 'sg-05bffd3eb96602519', 'rule_desc': 'allow sg-05bffd3eb96602519 access to port 2049'}]})Now, with the rules configured, we can start deploying some resources that use them, starting with the Target Group and ELB:
TASK [roles/elb : Provision the target group] *************changed: [localhost]TASK [roles/elb : Provision an application elastic load balancer] *************************************************changed: [localhost]Then EFS:
TASK [roles/efs : Generate the efs targets vars file] *****changed: [localhost]TASK [roles/efs : Include the efs targets vars file] ******ok: [localhost]TASK [roles/efs : Create the EFS File System] *************changed: [localhost]Now RDS:
TASK [roles/rds : Add RDS subnet group] *******************changed: [localhost]TASK [roles/rds : Create the RDS instance] ****************changed: [localhost]Now it is time to create the temporary EC2 instance. First, we find the AMI to use:
TASK [roles/ec2tmp : Gather information about AMIs with the specified filters] ****************************************ok: [localhost]TASK [roles/ec2tmp : filter the list of AMIs to find the latest one] ***********************************************ok: [localhost]Then, we create the SSH key pair:
TASK [roles/ec2tmp : Create an SSH Key Pair] **************changed: [localhost]Then, we create the EC2 instance itself:
TASK [roles/ec2tmp : Create the temporary ec2 instance] ***changed: [localhost]With the instance configured, we need to wait for it to have a status of running:
TASK [roles/ec2tmp : Get information about the temporary EC2 instance to see if it is running] ***FAILED - RETRYING: [localhost]: Get information about the temporary EC2 instance to see if it is running (50 retries left).. . . .FAILED - RETRYING: [localhost]: Get information about the temporary EC2 instance to see if it is running (46 retries left).ok: [localhost]Now that the instance is running, we add the newly launching EC2 instance to our host group:
TASK [roles/ec2tmp : Add the temporary EC2 instance to the vmgroup] **************************************************changed: [localhost]TASK [roles/ec2tmp : Wait for the temporary EC2 instance to be ready to accept SSH connections] ***********************ok: [localhost]Before we move on to connecting to the EC2 host to install and configure the software stack and WordPress, we generate the endpoints variables file:
TASK [roles/endpoints : Generate the aws endpoints file] **changed: [localhost]That concludes the first section of the site.yml file, and we can now SSH into the temporary EC2 host and install everything:
PLAY [Install and configure Wordpress] ********************TASK [Gathering Facts] ************************************ok: [ec2-18-203-221-2.eu-west-1.compute.amazonaws.com]We then progress with the installation, which, as we have already discussed, is pretty much the same set of tasks that we covered in Chapter 5, Deploying WordPress, and Chapter 9, Moving to the Cloud – except for these tasks, which mount the EFS file system:
TASK [roles/stack_config : Check that the EFS volume is ready] ****************************************************ok: [ec2-18-203-221-2.eu-west-1.compute.amazonaws.com]TASK [roles/stack_config : ensure rpcbind service is running] **************************************************ok: [ec2-18-203-221-2.eu-west-1.compute.amazonaws.com]TASK [roles/stack_config : mount the EFS volume] **********changed: [ec2-18-203-221-2.eu-west-1.compute.amazonaws.com]These tasks get the PHP version and set it as a fact:
TASK [roles/stack_config : Get the PHP version] ***********changed: [ec2-18-203-221-2.eu-west-1.compute.amazonaws.com]TASK [roles/stack_config : Set the PHP version] ***********ok: [ec2-18-203-221-2.eu-west-1.compute.amazonaws.com]Once that is complete, NGINX and PHP-FPM are restarted:
RUNNING HANDLER [roles/stack_config : restart nginx] ******changed: [ec2-18-203-221-2.eu-west-1.compute.amazonaws.com]RUNNING HANDLER [roles/stack_config : restart php-fpm] ****changed: [ec2-18-203-221-2.eu-west-1.compute.amazonaws.com]This concludes the tasks that bootstrap our temporary EC2 instance. We can now move back to our local machine and run the final section of the sites.yml file.
First, we create the AMI and terminate the temporary EC2 instance:
TASK [roles/ec2ami : find out some facts about the instance we have been using] ***************************************ok: [localhost]TASK [roles/ec2ami : create the AMI] **********************changed: [localhost]TASK [roles/ec2ami : remove any temporary instances which are running] **********************************************changed: [localhost]Then, we wait for two minutes:
TASK [roles/ec2ami : wait for 2 minutes before continuing]Pausing for 120 seconds(ctrl+C then 'C' = continue early, ctrl+C then 'A' = abort)ok: [localhost]Now, we grab the details of the AMI we just created:
TASK [roles/autoscaling : Search for all of our AMIs] *****ok: [localhost]TASK [roles/autoscaling : Find the last one we built] *****ok: [localhost]TASK [roles/autoscaling : Grab AMI ID and name of the most recent result] ********************************************ok: [localhost]Once we have those details, we create (or if we have already run the playbook, update) the Launch Template:
TASK [roles/autoscaling : Create the launch template] *****changed: [localhost]Now, we gather the information needed for us to create/update the Auto Scaling Group:
TASK [roles/autoscaling : find out the target group ARN] **ok: [localhost]TASK [roles/autoscaling : get information on the ec2 subnets] **************************************************ok: [localhost]Then we create the list of subnets the Auto Scaling Group will use:
TASK [roles/autoscaling : create a list of subnet IDs] ****ok: [localhost] => (item={'availability_zone': 'eu-west-1c', 'availability_zone_id': 'euw1-az3', 'available_ip_address_count': 27, 'cidr_block': '10.0.0.64/27', 'default_for_az': False, 'map_public_ip_on_launch': False, 'map_customer_owned_ip_on_launch': False, 'state': 'available', 'subnet_id': 'subnet-091ea1834c5fc8e48', 'vpc_id': 'vpc-008808ff628883751', 'owner_id': '687011238589', 'assign_ipv6_address_on_creation': False, 'ipv6_cidr_block_association_set': [], 'tags': {'role': 'compute', 'deployedBy': 'Ansible', 'Name': 'ec2-subnet-euw1-az3', 'environment': 'prod', 'description': 'Resource managed by Ansible', 'projectName': 'learnansible'}, 'subnet_arn': 'arn:aws:ec2:eu-west-1:687011238589:subnet/subnet-091ea1834c5fc8e48', 'enable_dns64': False, 'ipv6_native': False, 'private_dns_name_options_on_launch': {'hostname_type': 'ip-name', 'enable_resource_name_dns_a_record': False, 'enable_resource_name_dns_aaaa_record': False}, 'id': 'subnet-091ea1834c5fc8e48'})The preceding output is repeated twice for the other two subnets we will be using; then, we finally create/update the Auto Scaling Group:
TASK [roles/autoscaling : Create/update the auto-scaling group using the launch template we just created] **********changed: [localhost]Now, we have come to the end of our Playbook run, and we get the recap:
PLAY RECAP ************************************************ec2-18-203-221-2.eu-west-1.compute.amazonaws.com :ok=37 changed=28 unreachable=0 failed=0 skipped=1 rescued=0 ignored=2localhost :ok=56 changed=23 unreachable=0 failed=0 skipped=30 rescued=0 ignored=0When I ran the playbook, it took just over 20 minutes to complete the first time, with subsequent runs taking around 10 minutes to finish.
So, from a single command and in 20ish minutes, we have a highly available vanilla WordPress installation. If you find out the public URL of your Elastic Load Balancer from the AWS console or by checking the value of the elb key in the group_vars/generated_aws_endpoints.yml file, you should be able to see your site.
Terminating all the resources
Section titled “Terminating all the resources”Before we complete this chapter, we need to look at terminating the resources; to do this, you can run the following:
$ ansible-playbook -i hosts destroy.ymlThis removes everything in the reverse order that we launched it, starting with the Auto Scaling Group:
PLAY [Destroy the AWS Environment created by the site.yml playbook] ************TASK [Gathering Facts] ************************************ok: [localhost]TASK [Delete the Auto Scaling Group] **********************changed: [localhost]TASK [Delete the Launch Template] *************************changed: [localhost]As there can be more than one AMI, we gather some facts and then loop through removing everything that is returned:
TASK [Get information about the AMIs] *********************ok: [localhost]TASK [Delete the AMI(s)] **********************************changed: [localhost] => (item={'architecture': 'x86_64', 'creation_date': '2024-01-12T09:44:07.000Z', 'image_id': 'ami-0ddfeb5a1fb64c23a', 'image_location': '687011238589/learnansible-prod-ami-2024-01-12_0944', 'image_type': 'machine', 'public': False, 'tags': {'Name': 'learnansible-prod-ami-2024-01-12_0944', 'deployedBy': 'Ansible', 'environment': 'prod', 'buildDate': '2024-01-12 09:44:06', 'description': 'Resource managed by Ansible', 'projectName': 'learnansible', 'role': 'ami'}, 'virtualization_type': 'hvm', 'source_instance_id': 'i-050689909fa289998'})We then remove more one-off resources:
TASK [Create a SSH Key Pair] ******************************changed: [localhost]TASK [Delete the group_vars/generated_aws_endpoints.yml file] *****************************************************changed: [localhost]TASK [Delete the RDS database] ****************************changed: [localhost]TASK [Delete RDS subnet group] ****************************changed: [localhost]TASK [Delete the group_vars/generated_rds_passwordfile file] *****************************************************changed: [localhost]TASK [Delete the EFS File System] *************************changed: [localhost]TASK [Delete the group_vars/generated_efs_targets.yml file]changed: [localhost]TASK [Delete the application elastic load balancer]********changed: [localhost]TASK [Delete the target group] *********************************************************************changed: [localhost]As the security groups reference each other, we need to create a list of them in reverse order so we can attempt to delete a group that is referenced by the next one we are going to delete:
TASK [Create a reversed list of the security group names] *ok: [localhost]TASK [Delete the security groups] *************************changed: [localhost] => (item=learnansible-efs-security-group)changed: [localhost] => (item=learnansible-rds-security-group)changed: [localhost] => (item=learnansible-ec2-security-group)FAILED - RETRYING: [localhost]: Delete the security groups (50 retries left).. . . . .FAILED - RETRYING: [localhost]: Delete the security groups (46 retries left).changed: [localhost] => (item=learnansible-elb-security-group)You may have noticed that it failed towards the end; that is because the AWS API is having a little trouble keeping up, and the playbook is running a little ahead of the results it is returning.
We check a few more tasks:
TASK [Get information about the VPC] **********************ok: [localhost]TASK [Get information about the Route Table] **************ok: [localhost]TASK [Delete the Route Table] *****************************changed: [localhost] => (item={'associations': [{'main': False, 'route_table_association_id': 'rtbassoc-0738bb9e5aaf44848', 'route_table_id': 'rtb-04bc7177949ad2c92', 'subnet_id': 'subnet-07c28d376283741f6', 'association_state'TASK [Delete the Internet Gateway]*************************changed: [localhost]Next, we have the subnets:
TASK [Get information on the subnets] **************************************************************ok: [localhost]TASK [Delete the subnets] *********************************changed: [localhost] => (item={'availability_zone': 'eu-west-1c', 'availability_zone_id': 'euw1-az3', 'available_ip_address_count': 27, 'cidr_block': '10.0.0.64/27', 'default_for_az': False, 'map_public_ip_on_launch': False, 'map_customer_owned_ip_on_launch': False, 'state': 'available', 'subnet_id': 'subnet-091ea1834c5fc8e48', 'vpc_id': 'vpc-008808ff628883751', 'id': 'subnet-091ea1834c5fc8e48'}). . . . .changed: [localhost] => (item={'availability_zone': 'eu-west-1b', 'availability_zone_id': 'euw1-az2', 'available_ip_address_count': 27, 'cidr_block': '10.0.0.128/27', 'default_for_az': False, 'map_public_ip_on_launch': False, 'map_customer_owned_ip_on_launch': False, 'state': 'available', 'subnet_id': 'subnet-0fd4610392872d442', 'vpc_id': 'vpc-008808ff628883751', 'id': 'subnet-0fd4610392872d442'})Finally, we get to the VPC and recap:
TASK [Delete the VPC] *************************************changed: [localhost]PLAY RECAP ************************************************localhost :ok=23 changed=17 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0Once the playbook has finished running, I recommend you log in to the AWS console and double-check that everything has been correctly removed, as you don’t want to incur any unexpected costs.
Summary
Section titled “Summary”In this chapter, we have taken our AWS deployment to the next level by creating and launching a highly available WordPress installation. By leveraging the various services offered by AWS, we engineered out any single points of failure regarding the availability of instances and our use of availability zones.
We also built logic into our playbook to use the same command to launch a new deployment or update the operating system on an existing one with a rolling deployment of new instance AMIs that contain our updated packages, leading to zero downtime during deployment.
While the WordPress deployment is as simple as possible, deploying the production-ready images would remain similar when using a more complicated application.
In our next chapter, we will look at moving from the public to the private cloud and how Ansible interacts with VMware.