Building Out a Cloud Network
local graph
Chapter 10 — Building Out a Cloud Network
Section titled “Chapter 10 — Building Out a Cloud Network”Now that we have launched servers in Microsoft Azure, we will start looking at launching services within Amazon Web Services (AWS).
Before we launch virtual machine instances, we must create a network to host them. This is called a virtual private cloud (VPC) and there are a few different elements we will need to bring together in a playbook to create one, which we will then be able to use for our instances.
In this chapter, we will do the following:
- Receive an introduction to AWS
- Cover what it is we are trying to achieve and why
- Create a VPC, subnets, and routes (networking and routing)
- Create security groups (firewall)
We will look at more advanced Ansible techniques as we launch and manage more dynamic resources with complex dependencies.
The chapter covers the following topics:
- An introduction to AWS
- Amazon VPC overview
- Creating an access key and secret
- Getting Ansible ready for targeting AWS
- The AWS playbook
- Running the playbook
Technical requirements
Section titled “Technical requirements”This chapter will use AWS; you will need administrator access to create the roles needed to allow Ansible to interact with your account. As with other chapters, you can find the complete playbooks in the Chapter10 folder in the accompanying GitHub repository at https://github.com/PacktPublishing/Learn-Ansible-Second-Edition/tree/main/Chapter10.
An introduction to AWS
Section titled “An introduction to AWS”AWS has been around since 2002; it started by offering a few services that were not linked in any way. It progressed in this form until early 2006 when it was relaunched. The relaunched AWS brought together three services:
- Amazon Elastic Compute Cloud (Amazon EC2): This is the AWS compute service
- Amazon Simple Storage Service (Amazon S3): Amazon’s scalable object storage service
- Amazon Simple Queue Service (Amazon SQS): This service provides a message queue, primarily for web applications
Since 2006, it has grown from three unique services to over 160, covering over 15 primary areas such as the following:
- Compute
- Storage
- Database
- Networking and content delivery
- Machine learning analytics security, identity, and compliance
- Internet of things
At its earnings call in October 2023, it was revealed that AWS had USD 23.06 billion in revenue in the third quarter of 2023, good for a service that initially offered to share idle compute time.
At the time of writing, AWS spans 32 geographic regions, which host a total of 102 availability zones (https://aws.amazon.com/about-aws/global-infrastructure/).
So, what makes AWS so successful? Not only its coverage but its approach to putting out its services. Andy Jassy, AWS CEO, has been quoted as saying:
“ Our mission is to enable any developer or any company to be able to build all their technology applications on top of our infrastructure technology platform.”
As an individual, you have access to the same APIs, services, regions, tools, and pricing models as large multi-national companies and Amazon themselves, as they consume their services. This gives you the freedom to start small and scale massively. For example, Amazon EC2 instances start from around USD 4.50 per month for a t2.nano (1 vCPU and 0.5G) all the way up to over USD 19,000 per month for an x1e.32xlarge (128 vCPU, 3,904 GB RAM, and two 1920 GB SSD storage); as you can see, there are instance types for every workload imaginable.
Both instances and most services are billed under pay-as-you-go, from per-second billing for EC2 instances to pay per GB per month for the storage you are using.
Amazon VPC overview
Section titled “Amazon VPC overview”In this chapter, we are going to be concentrating on launching an Amazon Virtual Private Cloud (Amazon VPC); this is the networking layer that will host the computing and other Amazon services that we will be launching in Chapter 11, Highly Available Cloud Deployments.
We are going to be launching our VPC into the EU-West #1 (Ireland) region; we will be spanning all three availability zones for our EC2 instances and also the Application Elastic Load Balancer. We will, again, be using the three availability zones for our Amazon Relational Database Service (RDS) instance and also two zones for the Amazon Elastic File System (Amazon EFS) volumes.
This all means our Ansible playbook needs to create/configure the following:
- One Amazon VPC
- Three subnets for EC2 instances
- Three subnets for Amazon RDS instances
- Three subnets for Amazon EFS volumes
- Three subnets for the Application Load Balancer
- One internet gateway
We will also need to configure the following:
- One route to allow access through the internet gateway
- One security group that allows everyone to access port
80(HTTP) and443(HTTPS) on the Application Load Balancer - One security group that allows trusted source access to port
22(SSH) on the EC2 instances - One security group that allows access to port
80(HTTP) from the Application Load Balancer to the EC2 instances - One security group that allows access to port
3306(MySQL) on the Amazon RDS instances from the EC2 instances - One security group that allows access to port
2049(NFS) on the Amazon EFS volumes from the EC2 instances
This will give us our primary network, allowing restrictive access to everything but the Application Load Balancer, which we want to be publicly available.
Before creating an Ansible playbook that deploys the network, we need to get an AWS API access key and secret.
Creating an access key and secret
Section titled “Creating an access key and secret”It is more than possible to create an access key and secret key for your AWS user to give Ansible full access to your AWS account.
Because of this, we are going to look at creating a user for Ansible, which only has permission to access the parts of AWS we know that Ansible will need to interact with for the tasks we are covering in this chapter. We will be giving Ansible full access to the following services:
- Amazon VPC
- Amazon EC2
- Amazon RDS
- Amazon EFS
To do this, follow these steps:
- Log in to the AWS console, which can be found at https://console.aws.amazon.com/.
- Once logged in, click on Services, which can be found in the menu at the top of the screen. In the open menu, enter
IAMinto the search box and then click on the IAM “Manage access to AWS resources” result. - On the IAM page, click User Groups in the left-hand side menu; we will create a group with the permissions assigned to it, and then we will create a user and add it to our group.
- Once on the User Groups page, click the Create Group button. This process has two steps, the first of which is setting the group’s name. In the space provided, enter the group name
Ansible. - Now, in the Attach permissions policies – Optional section, select AmazonEC2FullAccess, AmazonVPCFullAccess, AmazonRDSFullAccess, and AmazonElasticFileSystemFullAccess; once all four have been selected, click on the Create Group button at the bottom of the page.
- Now that we have our Ansible group, click Users in the left-hand side menu.
- Once on the Users page, click Create user, and this will take you to a page where you can configure your desired username and the type of user you want. Enter the following information:
- User name: Enter
LearnAnsiblein here- Leave the Provide user access to the AWS Management Console – optional option unchecked, as we will create a programmatic user
- User name: Enter
- Click on the Next button to take you to the Set Permissions page. Ensure that Add user to group is selected and that you have the
Ansiblegroup we created earlier ticked, and then click Next, which will take you to the Review and Create page. - Once you have reviewed the details, you need to click the Create user button, which will precisely do that: create our
LearnAnsibleuser. - The final step is to get an access key for our user. To get this, click on the
LearnAnsibleuser and select the Security credentials tab; from there, scroll down to Access Keys and click the Create access key button. - In the list of Access key best practices & alternatives select Other and then the Next button. Enter
For use with Learn Ansiblefor the description tag value and then click Create access key. - The Retrieve access keys page is the only time you get access to the Secret access key, so I recommend downloading the CSV file. Once downloaded, click on Done.
Important note
The CSV file you have just downloaded contains credentials allowing whoever has them to launch resources in your AWS account; please do not share them and keep them safe, as they could be misused, resulting in a huge and unexpected AWS bill should they fall into the wrong hands.
Now that we have an access key ID and secret access key for a user with the permissions, we need to launch our VPC using Ansible; we can start getting Ansible ready and reviewing the playbook.
Getting Ansible ready for targeting AWS
Section titled “Getting Ansible ready for targeting AWS”We first need to discuss how to pass our access key ID and secret access key to Ansible safely and securely. As I will share the final playbooks in a public repository on GitHub, I want to keep my AWS keys private from the world as that could get expensive! Typically, if it were a private repository, I would use Ansible Vault or some other secret management to encrypt the keys and include them with other potentially sensitive data, such as deployment keys.
In this case, I don’t want to include any encrypted information in the repository, as it would mean that people would need to unencrypt it, edit the values, and then re-encrypt it. Luckily, the AWS modules allow you to set two environment variables on your Ansible controller; those variables will then be read as part of the playbook execution.
To set the variables, run the following commands to make sure that you replace the content with your access key and secret after = (the information listed as follows is just placeholder values):
$ export AWS_ACCESS_KEY=AKIAI5KECPOTNTTVM3EDA$ export AWS_SECRET_KEY=Y4B7FFiSWl0Am3VIFc07lgnc/TAtK5+RpxzIGTrOnce set, you can view the contents by running the following:
$ echo $AWS_ACCESS_KEYNow that we can securely pass our credentials to Ansible, we can install the Python modules needed by the AWS Ansible modules to interact with the AWS API.
Important note
You must set the environment variables for each terminal session, as they will be lost each time you close your terminal.
To install the Python modules, run the following command:
$ pip3 install botocore boto3Now that we have the basics configured, we can review our playbook.
The AWS playbook
Section titled “The AWS playbook”As mentioned at the start of the chapter, we are going to be using some more advanced techniques when it comes to deploying resources in AWS where possible; I have tried to allow the resources to be deployed as dynamically as possible, a lot of which comes down to how we define our variables, which is where we are going to start our playbook review.
The playbook variables
Section titled “The playbook variables”Most of the variables we define can be found in group_vars/common.yml, and as you can see from the following, they start by looking a lot like the variables we described in Chapter 9, Moving to the Cloud:
debug_output: falseapp: name: "learnansible" region: "eu-west-1" env: "prod"As you can see, we have the same debug_output feature flag and selection of variables used to describe our app and the AWS region in which it will be launched.
Next up, we have the resource names:
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 }}"Nothing too out of the ordinary so far, but here we will find our first difference in approach:
vpc: cidr_block: "10.0.0.0/23" dns_hostnames: true dns_support: true subnet_size: "27" subnets: - name: "ec2" role: "{{ subnet_role_compute }}" - name: "rds" role: "{{ subnet_role_database }}" - name: "efs" role: "{{ subnet_role_storage }}" - name: "dmz" role: "{{ subnet_role_public }}"At first glance, that doesn’t look too dissimilar to what we did for Microsoft Azure.
However, you might have noticed that there are no IP address CIDR ranges listed for the subnets, just some details about the subnets, including a dictionary of roles:
subnet_role_compute: "compute"subnet_role_database: "database"subnet_role_storage: "storage"subnet_role_public: "public"We will look at why the subnet’s CIDR ranges are missing when we get to the tasks that create the subnet.
Next, we have the variables for creating the security groups; in total, we will be configuring four security groups, so in the interest of space, I will only be showing one of the small groups here:
security_groups: - name: "{{ app.name }}-rds-{{ playbook_dict.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: "{{ ec2_group_id | default('') }}" rule_desc: "allow {{ ec2_group_id | default('') }} access to port 3306"See the GitHub repo for the full configuration for the four security groups; there is only one thing at this point to highlight, and that is this: where we reference {{ ec2_group_id | default('') }}, we are setting a default value of nothing (which is the '' part). We will discuss why we are doing this when we cover the security role.
The final set of variables is the dictionary (playbook_dict) and a variable, which sets the value of region using app.region; again, see the GitHub if you want to see all the contents.
The VPC role
Section titled “The VPC role”Before we get to the exciting tasks, we need to create the VPC. The task in roles/vpc/tasks/main.yml looks like the following:
- name: "Create VPC" amazon.aws.ec2_vpc_net: name: "{{ vpc_name }}" region: "{{ region }}" cidr_block: "{{ vpc.cidr_block }}" dns_hostnames: "{{ vpc.dns_hostnames }}" dns_support: "{{ vpc.dns_support }}" state: "{{ state }}" tags: Name: "{{ vpc_name }}" projectName: "{{ app.name }}" environment: "{{ app.env }}" deployedBy: "{{ playbook_dict.deployedBy }}" description: "{{ playbook_dict.ansible_warning }}" register: vpc_outputThe task is pretty much as you would expect, apart from the tags being set a little more in line than those we defined in Chapter 9, Moving to the Cloud. There is also a debug statement that prints the results of creating the VPC if you set debug_output to true:
- name: "Debug - VPC result" ansible.builtin.debug: var: "vpc_output" when: debug_outputFrom now on, it is safe to assume that all registered output will be followed by an ansible.builtin.debug task. Now that we have our VPC launched, we can start putting things inside it, beginning with the subnets, where things get more interesting.
The subnets role
Section titled “The subnets role”As mentioned in the AWS overview, there are 32 geographic regions and, at the time of writing, 102 Availability Zones. AWS differs from Microsoft Azure in that you need a subnet per Availability Zone rather than a single subnet spanning all the availability zones.
The eu-west-1 region, which is the region we will target, is made up of three availability zones, and we have subnets for four different roles, meaning that we need 12 subnets in total, but our playbook could easily be targeting a region that only has two availability zones, or in some cases, even more.
So, our first task is to get information on the availability zones in our target region:
- name: "Get some information on the available zones" amazon.aws.aws_az_info: region: "{{ region }}" register: zones_outputNow that we know some information on the region, we can use that information and create our subnets:
- name: "Create all subnets" ansible.builtin.include_tasks: create_subnet.yml loop: "{{ vpc.subnets }}" loop_control: loop_var: subnet_item index_var: subnet_index vars: subnet_name: "{{ subnet_item.name }}" subnet_role: "{{ subnet_item.role }}" az_zones_from_main: "{{ zones_output }}" register: subnet_outputThis task is quite different from the ones we have been using so far in the book, so let’s take a deeper dive into what is happening.
Here, we are using a loop to automate the creation of multiple subnets. Each iteration of the loop processes one subnet from the vpc.subnets list, which, as we have already seen, contains the configuration details for each subnet.
As the loop runs, it assigns the current subnet’s details to the subnet_item variable and its index in the list to subnet_index. These variables are then utilized to customize the creation process for each subnet.
The task includes and executes the steps defined in create_subnet.yml (which we will cover next) for each subnet, using the specific details of that subnet (such as its name and role).
You may have noticed that we still haven’t passed in any CIDR ranges for the subnets; this is all handled within the create_subnet.yml task, which we loop over for each of our four subnet types; this is also where a second loop happens:
- name: "Create subnet in the availability zone" amazon.aws.ec2_vpc_subnet: region: "{{ region }}" state: "{{ state }}" vpc_id: "{{ vpc_output.vpc.id }}" cidr: "{{ vpc_output.vpc.cidr_block | ansible.utils.ipsubnet(vpc.subnet_size, az_loop_index + (subnet_index * az_zones_from_main.availability_zones|length)) }}" az: "{{ az_item.zone_name }}" tags: Name: "{{ subnet_name }}-{{ playbook_dict.subnet }}-{{ az_item.zone_id }}" projectName: "{{ app.name }}" environment: "{{ app.env }}" deployedBy: "{{ playbook_dict.deployedBy }}" description: "{{ playbook_dict.ansible_warning }}" role: "{{ subnet_role }}" loop: "{{ az_zones_from_main.availability_zones }}" loop_control: loop_var: az_item index_var: az_loop_indexPlease stick with me, as this is where it gets a little confusing; for each of the four loops we are enacting from our main loop, we are taking the information on the availability zones and then looping over them, creating a subnet per availability zone for the role we are currently looping over.
So, what about the CIDR range for the subnet?
You may have noticed something where you would expect to see the CIDR range; we have this expression:
vpc_output.vpc.cidr_block | ansible.utils.ipsubnet(vpc.subnet_size, az_loop_index + (subnet_index * az_zones_from_main.availability_zones|length))We have the following components in the expression:
vpc_output.vpc.cidr_block: This is the CIDR block of the VPC, within which the subnets will be created. For our example, it’s10.0.0.0/22.vpc.subnet_size: This specifies the size of each subnet. We are using/27, representing a subnet with 32 IP addresses.az_zones_from_main.availability_zones|length: This is the total number of availability zones available. The region we are targeting has3availability zones.az_loop_index: This is the current index in the loop over the availability zones.subnet_index: This is the index of the current subnet being processed.
This means that for our expression, we will get the following results. The first subnet, which is labeled ec2, in the availability zone (az1) will have the following:
az_loop_index = 0subnet_index = 0
So, the formula would be 0+(0*3)=0, meaning that we would get the following:
cidr = "{{ vpc_output.vpc.cidr_block | ansible.utils.ipsubnet(27, 0) }}"With vpc_output.vpc.cidr_block being 10.0.0.0/22, we could get the first /27, which would be 10.0.0.0/27.
For the second availability zone (az2), the loop would be the following:
az_loop_index = 1subnet_index = 0
1+(0*3)=1 means we would get 10.0.0.32/27 since the next subnet block starts immediately after the previous one at the next 32 IP address interval.
The third Availability Zone (az3) would be 2+(0*3)=2, and the CIDR block would be 10.0.0.64/27.
The next subnet role, which is the RDS role, would give the following for az1:
az_loop_index = 0subnet_index = 1
The formula would be 0+(1*3)=3, giving us a CIDR block 10.0.0.96/27.
This pattern would follow the sequence, where the next subnet for RDS az2 would be at 10.0.0.128/27, and for az3, it would be at 10.0.0.160/27, and so on.
This expression ensures that each subnet created within the VPC is assigned a unique and non-overlapping CIDR block, segmented adequately according to the defined subnet size, and distributed across different availability zones.
Taking this approach not only simplifies the management of subnet creation but also ensures efficiency when it comes to writing the role, as it means that we don’t have to hardcode tasks to consider changes between regions or the number of subnets we are defining in our variables.
The remaining tasks in the role build a list of the subnet IDs for each of the roles we have defined. An example of one of these tasks is as follows:
- name: "Gather information about the compute subnets" amazon.aws.ec2_vpc_subnet_info: region: "{{ region }}" filters: "tag:role": "{{ subnet_role_compute }}" "tag:environment": "{{ app.env }}" "tag:projectName": "{{ app.name }}" register: subnets_compute_outputThis gets information on the three subnets assigned the subnet_role_compute role. A few more of these data-gathering tasks can be found in the repo; these cover the subnet_role_database, subnet_role_storage, and subnet_role_public roles.
Finally, the final task in the role prints the subnet IDs that we have gathered using the previous set of tasks; this looks slightly different to the debug statements we have been using in the playbook so far, as we are using the msg function rather than the var one when calling the ansible.builtin.debug module.
The gateway role
Section titled “The gateway role”The gateway role is relatively simple compared to the previous one. In comparison, it deploys an internet gateway. Then, it creates a route to send all traffic destined for the internet (represented by using 0.0.0.0/0, the CIDR notation for all network traffic) to our newly launched internet gateway.
The task that creates the internet gateway looks like the following:
- name: "Create an Internet Gateway" amazon.aws.ec2_vpc_igw: region: "{{ region }}" state: "{{ state }}" vpc_id: "{{ vpc_output.vpc.id }}" tags: "Name": "{{ internet_gateway_name }}" "projectName": "{{ app.name }}" "environment": "{{ app.env }}" "deployedBy": "{{ playbook_dict.deployedBy }}" "description": "{{ playbook_dict.ansible_warning }}" "role": "igw" register: internet_gateway_outputAs per the rest of the tasks, a debug task follows this, and then the task that creates the route table, which is then associated with our newly created internet gateway and also the computing and public subnets that we defined and gathered the information for in the subnet’s role:
- name: "Create a route table so the internet gateway can be used by the public subnets" amazon.aws.ec2_vpc_route_table: region: "{{ region }}" state: "{{ state }}" vpc_id: "{{ vpc_output.vpc.id }}" subnets: "{{ subnet_compute_ids + subnet_public_ids }}" routes: - dest: "0.0.0.0/0" gateway_id: "{{ internet_gateway_output.gateway_id }}" resource_tags: "Name": "{{ internet_gateway_route_name }}" "projectName": "{{ app.name }}" "environment": "{{ app.env }}" "deployedBy": "{{ playbook_dict.deployedBy }}" "description": "{{ playbook_dict.ansible_warning }}" "role": "route" register: internet_gateway_route_outputWe then do a debug task that completes this role, and we then move on to the final role of the playbook: the security group’s role.
The security group’s role
Section titled “The security group’s role”While this role, in my opinion, is not as complicated as the subnet’s role, we have built a little more logic into the task than some of the more straightforward tasks in the book that we have run so far.
If you recall, earlier in the chapter, when we covered the variables being used by the playbook, we gave the following example of the security groups being deployed:
- proto: "tcp" from_port: "3306" to_port: "3306" group_id: "{{ ec2_group_id | default('') }}" rule_desc: "allow {{ ec2_group_id | default('') }} access to port 3306"The preceding rule, as per rule_desc, opens up port 3306 for any devices that have the EC2 security group attached to them, which, as we will see in Chapter 11, Highly Available Cloud Deployments, will be the EC2 instances that will be running our workload.
You may think to yourself, “Now that makes sense.” However, this is a little bit of a flaw in the logic we must work around. ec2_group_id is referencing a group ID, which, at the time we first run our playbook, doesn’t exist. So, how can we create the groups and populate them with rules that reference groups that don’t yet exist?
As we have already seen, looping over the resources defined in our variables is more efficient. It reduces the hard-coded logic at the role level, making the role more re-useable between projects and playbooks.
Before we look at the logic of creating the groups, we need to gather one bit of information: the public IP address of the resource running Ansible. To do this, we call the following task:
- name: "Find out your current public IP address using https://ipify.org/" community.general.ipify_facts: register: public_ip_outputThen we set a fact called your_public_ip, which we can reference in our rules where needed:
- name: "Set your public ip as a fact" ansible.builtin.set_fact: your_public_ip: "{{ public_ip_output.ansible_facts.ipify_public_ip }}/32"Now that we have that snippet of information, we can return to the question of how we can reference the IDs of resources that have yet to be launched.
To create the security groups, we will be using the amazon.aws.ec2_security_group module. The module has a flag called purge_rules, set to true by default; in this default state, when our playbook finds and needs to update an existing security group, it will drop all the rules in the group and then add just the ones defined in the playbook to maintain a consistent state.
While it is a valid use case, in our example, disabling this functionality by setting purge_rules to false will allow us to create some unpopulated security groups:
- name: "Create the base security groups" amazon.aws.ec2_security_group: region: "{{ region }}" state: "{{ state }}" vpc_id: "{{ vpc_output.vpc.id }}" name: "{{ item.name }}" description: "{{ item.description }}" purge_rules: false tags: "Name": "{{ item.name }}" "projectName": "{{ app.name }}" "environment": "{{ app.env }}" "deployedBy": "{{ playbook_dict.deployedBy }}" "role": "securitygroup" loop: "{{ security_groups }}" register: base_security_groups_outputThis will loop through and create the base, unpopulated security groups if they don’t exist, and if they do already exist, no changes will be made to them.
So, now that we have our groups created, or if they already exist, we have the information we need to dynamically define some facts based on the output of the previous tasks:
- name: "Set the fact for the security group ids" ansible.builtin.set_fact: "{{ item.id_var_name }}": "{{ base_security_groups_output.results | selectattr('item.name', 'equalto', item.name) | map(attribute='group_id') | first }}" loop: "{{ security_groups }}" when: base_security_groups_output.results | selectattr('item.name', 'equalto', item.name) | map(attribute='group_id') | list | length > 0This task uses the ansible.builtin.set_fact module, allowing the creation or update of new variables during runtime. This task aims to extract the unique ID of each security group created in the first task and assign it to a specific variable name.
There are two expressions we use to do this. The first is the following:
"{{ item.id_var_name }}": "{{ base_security_groups_output.results | selectattr('item.name', 'equalto', item.name) | map(attribute='group_id') | first }}"This is used to create the dynamic set of variables based on the loop created by the second expression. A breakdown of this first expression follows:
base_security_groups_output.results: This refers to the list of results from the previous task that created the security groups. Each result in this list contains data about one of the security groups.selectattr('item.name', 'equalto', item.name): Theselectattrfilter is used to search through the list of results. It looks for results where the name attribute of the item (each security group) is equal to the currentitem.namein the loop. In other words, it filters the results to find the specific security group we’re currently interested in.map(attribute='group_id'): Themapfilter is then used to transform the filtered list of results. It extracts only thegroup_idattribute from each result, which is the ID of the security group.first: Since the previous step can still return a list (albeit with a single element), thefirstfilter takes only the first element from this list, which should be the unique ID of the security group.
The result of this expression is the ID of the security group that matches the current item in the loop, and it’s assigned to a variable named according to item.id_var_name.
The second expression, which is in the when condition, runs as part of the loop:
when: base_security_groups_output.results | selectattr('item.name', 'equalto', item.name) | map(attribute='group_id') | list | length > 0This expression determines whether the task should be executed for a particular item in the loop. It follows a similar logic to the first expression:
- It starts with the same filtering process to find the security group that matches the current
item.name. - After extracting the
group_id, it ensures the output is treated as a list using thelistfilter. length > 0: This part checks whether the length of the list (the number of items in it) is greater than0. This means at least one security group with the specified name must exist. If the list is empty, no matching security group is found, and the task will be skipped for the current item.
In theory, we should have now populated the variables that contain the security group IDs, meaning that we can now add the rules:
- name: "Provision security group rules" amazon.aws.ec2_security_group: region: "{{ region }}" state: "{{ state }}" vpc_id: "{{ vpc_output.vpc.id }}" name: "{{ item.name }}" description: "{{ item.description }}" purge_rules: false rules: "{{ item.rules }}" loop: "{{ security_groups }}" register: security_groups_with_rules_outputThis will loop over the already created groups and populate the rules for each one, using the group IDs from the variables we dynamically defined in the previous task.
Running the playbook
Section titled “Running the playbook”As mentioned earlier, we worked our way through the playbook code; before you run the playbook, you must set the AWS_ACCESS_KEY and AWS_SECRET_KEY environment variables on your terminal session by running the following, making sure to update any values to those that you made a note of when you created the Ansible user in the AWS console:
$ export AWS_ACCESS_KEY=AKIAI5KECPOTNTTVM3EDA$ export AWS_SECRET_KEY=Y4B7FFiSWl0Am3VIFc07lgnc/TAtK5+RpxzIGTrWith the environment variables set, you can run the playbook running the now very familiar following code:
$ ansible-playbook -i hosts site.ymlOnce completed, you should see something like the following terminal output:

Figure 10.1 – Running the playbook in a terminal
Going to the VPC and viewing the resource map in http://console.aws.amazon.com/ should display something like the following resource map:

Figure 10.2 – Viewing the resource map
By going to Security Groups, you should also see the groups that we created listed:

Figure 10.3 – Reviewing the security groups
I have included a second playbook in the repo, which destroys all of the resources created by running the site.yml playbook called destroy.yml. You can run it using the following command:
$ ansible-playbook -i hosts destroy.ymlI am not going to cover the contents of the playbook here, but if you review the code, you will notice that, in essence, it runs the same tasks in the role we have covered in this chapter in reverse order, setting the state to absent rather than present.
Summary
Section titled “Summary”In this chapter, we have taken our next step in using Ansible to launch resources in a public cloud. We have laid the groundwork for automating quite a complex environment by creating a VPC, setting up the subnets we need for our application, provisioning an internet gateway, and setting our instances to route their outgoing traffic through it.
We have configured four security groups, with three containing dynamic content, to secure the services launching into our VPC.
In the next chapter, we will build on the foundations laid in this chapter and launch a more complex set of services alongside the VPC.
Further reading
Section titled “Further reading”- Details of the AWS Q3 2023 earnings call: https://www.cnbc.com/2023/10/26/aws-q3-earnings-report-2023.html