Until now, every Aurora Store machine has been born with vagrant up: someone had to create it before Ansible could configure it. In the cloud that changes: servers, networks and firewalls are created with API calls, and Ansible can make those calls just as it configures nginx. In this lesson, Aurora prepares its first environment outside the lab, a staging environment on AWS: with the amazon.aws collection you'll create the virtual private network, the subnet, the internet gateway, the security groups and the EC2 instances, all tagged and idempotent; you'll wait for them to respond over SSH, add them to the in-memory inventory with add_host and configure them in the same playbook. You'll also learn how to manage cloud credentials without them ever touching the repository, how to destroy what you've created and how to keep an eye on costs.
Cost warning. What you do in this lesson creates real, billable resources in an AWS account: instances, disks, public IPv4 addresses and traffic. With three small instances for an hour or two the cost is low, but forgetting them running for a month isn't. Use a test account with budget alerts, destroy everything when you finish (section 12) and check in the console that nothing is left. All identifiers, IPs and values in this lesson are fictitious.
Contents
- From the lab to the cloud: provisioning versus configuring
- Cloud provider collections
- The
amazon.awscollection and its requirements - Cloud credentials: never in the repository
- The design of the
stagingenvironment - Variables and structure of the
staging-aws.ymlplaybook - The network: VPC, subnet, gateway and routes
- Security groups
- SSH key and system image
- Idempotent EC2 instances: tags, filters and
exact_count - Waiting for SSH,
add_hostand configuring in the same playbook - Destroying the environment and keeping costs under control
- What's next: dynamic inventory
- From the lab to the cloud: provisioning versus configuring
| Phase | What's done | In the lab | In the cloud |
|---|---|---|---|
| Provision | Create the machine, its network, its disk, its IP | Vagrant (lab/Vagrantfile) |
The provider's API (Ansible with amazon.aws, Terraform…) |
| Configure | Packages, users, services, application | Ansible (site.yml) |
Ansible (the same roles) |
Cloud modules don't run on a server over SSH, but on the control node against the provider's API, like the Kubernetes ones in Lesson 8.2. That's why provisioning plays use hosts: localhost.
sequenceDiagram
participant A as ansible-playbook (your computer)
participant API as AWS API
participant I as EC2 instances
A->>API: Create VPC, subnet, routes, security groups, instances (play 1, localhost)
API-->>A: IDs and public IPs
A->>A: add_host (in-memory inventory)
A->>I: SSH: wait for the connection and apply the common role (play 2)
- Cloud provider collections
Each major provider has its own collection, usually maintained by the vendor itself or by the community:
| Provider | Collection | Example modules | Inventory plugin | Library on the control node |
|---|---|---|---|---|
| AWS | amazon.aws (+ community.aws for less common services) |
ec2_instance, ec2_vpc_net, s3_bucket |
amazon.aws.aws_ec2 |
boto3, botocore |
| Microsoft Azure | azure.azcollection |
azure_rm_virtualmachine, azure_rm_virtualnetwork |
azure.azcollection.azure_rm |
Azure SDK (list in the collection) |
| Google Cloud | google.cloud |
gcp_compute_instance, gcp_compute_network |
google.cloud.gcp_compute |
google-auth, requests |
| OpenStack | openstack.cloud |
server, network, security_group |
openstack.cloud.openstack |
openstacksdk |
| Hetzner Cloud | hetzner.hcloud |
server, network, firewall |
hetzner.hcloud.hcloud |
hcloud |
| DigitalOcean | community.digitalocean |
digital_ocean_droplet |
community.digitalocean.digitalocean |
requests |
| VMware vSphere | vmware.vmware, community.vmware |
vmware_guest |
vmware.vmware.vms |
vSphere SDK |
They all follow the same scheme you'll see with AWS: credentials outside the repository, resources identified by name or tags, idempotent modules with state: present/absent and *_info modules for queries. If your company uses another provider, what you learn here carries over almost directly.
Aurora uses AWS as the example, in the eu-south-2 region (Spain). Any other region (for example eu-west-1, Ireland) works by changing a variable.
- The
amazon.aws collection and its requirements
amazon.aws collection and its requirementsAdd it to collections/requirements.yml (the 10.x series asks for ansible-core >=2.17.0):
# AWS resources: network, security groups and EC2 instances (Lesson 8.4).
- name: amazon.aws
version: "10.1.1"ansible-galaxy collection install -r collections/requirements.yml
pipx inject ansible boto3 botocore
ansible-doc amazon.aws.ec2_instance | head -5boto3 and botocore are the official AWS SDK for Python; the modules use them to call the API. They go on your computer (the control node), not on the servers.
In the EE: when building,
ansible-builderwill addboto3andbotocoreautomatically, because the collection declares them. Remember the pipeline rule from Lesson 8.3: a change tocollections/requirements.ymlrebuildsaurora-ee, and since the1.1.0tag already exists, the job will fail until you bumpoptions.tagstoaurora-ee:1.2.0in the same pull request (andimage:inansible-navigator.yml). That's exactly what should happen.
- Cloud credentials: never in the repository
4.1. An identity for Ansible
Don't use the account's root user or your personal administrator credentials. In the AWS console (IAM), create an identity for Aurora's automation (for example, the aurora-ansible user) with a policy that allows only what's needed: managing VPCs, subnets, routes, gateways, security groups, key pairs and EC2 instances, ideally limited to the chosen region. The exact policy should be reviewed by whoever administers the account's security (Lesson 9.2).
4.2. How credentials reach the modules
The amazon.aws modules look for credentials in roughly this order: module parameters, environment variables, a profile in ~/.aws/ and, if Ansible runs inside AWS, the machine's role.
| Method | How | When to use it |
|---|---|---|
access_key / secret_key parameters on the task |
Variables (encrypted with Vault) | Avoid it: they easily end up in a log or in Git |
| Environment variables | AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY (and AWS_SESSION_TOKEN if they're temporary) |
CI and AWX (they inject them) |
| Named profile | ~/.aws/credentials + AWS_PROFILE=aurora-staging |
Your computer |
| IAM Identity Center (SSO) | aws sso login --profile aurora-staging (temporary credentials) |
Recommended for people |
| Instance or pod role | No explicit credentials | Ansible running inside AWS |
Aurora uses a named profile on your computer, outside the repository:
# ~/.aws/credentials (permissions 0600; NEVER in Git)
[aurora-staging]
aws_access_key_id = AKIAEXAMPLEFAKEKEY01
aws_secret_access_key = exampleFakeDoNotUse/abcdefghijklmnopqrstuvIf your organization uses IAM Identity Center, instead of permanent keys you'd configure the profile with aws configure sso and run aws sso login every day: the credentials expire on their own, which is much safer.
4.3. In AWX
AWX has an Amazon Web Services credential type (access key, secret key and, optionally, a session token). When you attach it to a template, AWX injects the AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables into the job, and the modules use them without the playbook mentioning them. It's the same injection pattern you saw in Lesson 7.5. For now, Aurora will launch staging from the terminal.
If a key leaks: deactivate it immediately in IAM, review the account activity (CloudTrail) and create another one. Bots that search public repositories for AWS keys find them and use them within minutes, usually to mine cryptocurrency at your expense.
- The design of the
staging environment
staging environmentflowchart TB
INET((Internet)) --- IGW[Internet gateway<br/>aurora-staging-igw]
subgraph VPC["VPC aurora-staging 10.40.0.0/16 (eu-south-2)"]
IGW --- RT[Route table<br/>0.0.0.0/0 → IGW]
RT --- SUB
subgraph SUB["Public subnet 10.40.1.0/24 (eu-south-2a)"]
W1[aurora-staging-web]
W2[aurora-staging-web]
D1[aurora-staging-db]
end
end
SGW[SG aurora-staging-web<br/>22 from your IP · 80 from the Internet] -.-> W1 & W2
SGD[SG aurora-staging-db<br/>22 from your IP · 5432 from web SG] -.-> D1
Decisions:
- A VPC of its own (
10.40.0.0/16), so staging isn't mixed with anything else. - One public subnet with automatic public IPs: simple and enough for learning. In production, the database would go in a private subnet with no public IP, and internet access would go out through a NAT gateway (which has a non-negligible fixed hourly cost) or access would be through a bastion host or AWS Systems Manager.
- Security groups as firewalls: SSH only from your IP, HTTP open on the web servers, PostgreSQL only from the web servers' group.
- Three small instances (
t3.micro): two web servers and one database, the same split as the lab (without a load balancer). - Tags on everything:
Project=aurora,Environment=staging,ManagedBy=ansibleand, on the instances,Role=weborRole=db. Tags are the basis of idempotency (section 10), of safe destruction (section 12) and of cost allocation.
- Variables and structure of the
staging-aws.yml playbook
staging-aws.yml playbookThe environment data goes in a new file, cloud/aws-staging.yml:
---
# Aurora Store staging environment on AWS (Lesson 8.4).
# Example values: adjust the region, the zone and YOUR public IP before running.
aurora_staging_region: eu-south-2
aurora_staging_az: eu-south-2a
aurora_staging_name: aurora-staging
aurora_staging_vpc_cidr: 10.40.0.0/16
aurora_staging_subnet_cidr: 10.40.1.0/24
# The only IP allowed to use SSH (yours; 203.0.113.0/24 is a documentation range).
aurora_staging_admin_cidr: 203.0.113.25/32
aurora_staging_instance_type: t3.micro
aurora_staging_web_count: 2
aurora_staging_db_count: 1
aurora_staging_key_name: aurora-staging
aurora_staging_ssh_key: "{{ lookup('ansible.builtin.env', 'HOME') }}/.ssh/aurora_staging_ed25519"
# Official Ubuntu 24.04 from Canonical (the most recent one is looked up, section 9).
aurora_staging_ami_owner: "099720109477"
aurora_staging_ami_name: ubuntu/images/hvm-ssd-gp3/ubuntu-noble-24.04-amd64-server-*
aurora_staging_tags:
Project: aurora
Environment: staging
ManagedBy: ansibleWhy not in inventory/? Because these variables belong to the provisioning play, which runs on localhost, and the instances don't exist yet when it starts. It's a legitimate case for vars_files (Lesson 3.5). In Lesson 9.1 you'll reorganize the repository with per-environment inventories and this file will find its final place.
Create an SSH key only for staging (don't reuse the lab one, which has no passphrase and is on every VM):
(For a shared environment, protect it with a passphrase and use ssh-agent.)
The skeleton of staging-aws.yml, at the project root:
---
# Creates (or maintains) the Aurora Store staging environment on AWS and applies the base configuration.
# Requirements: amazon.aws collection, boto3/botocore and credentials (AWS_PROFILE=aurora-staging).
# Creates billable resources! Destruction: staging-aws-destroy.yml
- name: Provision the Aurora Store staging environment on AWS
hosts: localhost
connection: local
gather_facts: false
vars_files:
- cloud/aws-staging.yml
module_defaults:
group/amazon.aws.aws:
region: "{{ aurora_staging_region }}"
tasks:
# Sections 7 to 10
- name: Configure the staging environment servers
hosts: staging_aws
gather_facts: false
become: true
# Section 11module_defaults with the group/amazon.aws.aws group sets the region for all the collection's modules, just as you did with the kubeconfig in Lesson 8.2.
- The network: VPC, subnet, gateway and routes
- name: Create the VPC
amazon.aws.ec2_vpc_net:
name: "{{ aurora_staging_name }}"
cidr_block: "{{ aurora_staging_vpc_cidr }}"
tags: "{{ aurora_staging_tags }}"
state: present
register: aurora_staging_vpc
- name: Create the public subnet
amazon.aws.ec2_vpc_subnet:
vpc_id: "{{ aurora_staging_vpc.vpc.id }}"
cidr: "{{ aurora_staging_subnet_cidr }}"
az: "{{ aurora_staging_az }}"
map_public: true
tags: "{{ aurora_staging_tags | combine({'Name': aurora_staging_name ~ '-public'}) }}"
state: present
register: aurora_staging_subnet
- name: Create the internet gateway
amazon.aws.ec2_vpc_igw:
vpc_id: "{{ aurora_staging_vpc.vpc.id }}"
tags: "{{ aurora_staging_tags | combine({'Name': aurora_staging_name ~ '-igw'}) }}"
state: present
register: aurora_staging_igw
- name: Route the public subnet to the internet
amazon.aws.ec2_vpc_route_table:
vpc_id: "{{ aurora_staging_vpc.vpc.id }}"
tags: "{{ aurora_staging_tags | combine({'Name': aurora_staging_name ~ '-public'}) }}"
subnets:
- "{{ aurora_staging_subnet.subnet.id }}"
routes:
- dest: 0.0.0.0/0
gateway_id: igw
state: presentHow idempotency is achieved for each resource:
| Resource | How the module recognizes it on the next run |
|---|---|
| VPC | By name (Name tag) + cidr_block |
| Subnet | By vpc_id + cidr |
| Internet gateway | By vpc_id (there can only be one per VPC) |
| Route table | By vpc_id + tags (lookup: tag search, the default option) |
Details:
- Each task registers its result and the next one uses the real identifier (
aurora_staging_vpc.vpc.id, for examplevpc-0a1b2c3d4e5f60718). You never write IDs by hand: they change in every account and on every creation. combine(Lesson 5.3) adds theNametag to the common tags.map_public: true: instances in the subnet get a public IP automatically.gateway_id: igwis a special value: "this VPC's internet gateway", without having to pass its ID.
If you needed to compute subnets from the VPC CIDR (for example, one per zone), the
ansible.utilsfilters (ipsubnet,ipaddr) do it:aurora_staging_vpc_cidr | ansible.utils.ipsubnet(24, 1)returns10.40.1.0/24. Aurora doesn't need them and doesn't add that collection.
- Security groups
- name: Create the web servers security group
amazon.aws.ec2_security_group:
name: "{{ aurora_staging_name }}-web"
description: Aurora Store web servers (staging)
vpc_id: "{{ aurora_staging_vpc.vpc.id }}"
rules:
- proto: tcp
ports: [22]
cidr_ip: "{{ aurora_staging_admin_cidr }}"
rule_desc: SSH from the admin IP
- proto: tcp
ports: [80]
cidr_ip: 0.0.0.0/0
rule_desc: Public HTTP
tags: "{{ aurora_staging_tags }}"
state: present
- name: Create the database security group
amazon.aws.ec2_security_group:
name: "{{ aurora_staging_name }}-db"
description: Aurora Store database (staging)
vpc_id: "{{ aurora_staging_vpc.vpc.id }}"
rules:
- proto: tcp
ports: [22]
cidr_ip: "{{ aurora_staging_admin_cidr }}"
rule_desc: SSH from the admin IP
- proto: tcp
ports: [5432]
group_name: "{{ aurora_staging_name }}-web"
rule_desc: PostgreSQL from the web servers
tags: "{{ aurora_staging_tags }}"
state: present- A security group is a stateful firewall attached to network interfaces. By default it allows all outbound traffic and no inbound traffic; the
rulesdefine the inbound traffic. group_nameas the source allows traffic from any instance in theaurora-staging-webgroup, whatever its IP: if you add a third web server tomorrow, it already has access. It's more robust than listing IPs (compare it with the lab'spostgresql_hba_clients).- The module synchronizes the rules: by default (
purge_rules: true) it removes those that aren't in the list. If someone opens a port from the console, the next run closes it (drift correction, likeufwon the servers).
Remember that these rules are an additional layer: inside the instances, Aurora's nginx role also enables ufw (Lesson 4.3). Defense in depth.
- SSH key and system image
- name: Register the staging SSH public key
amazon.aws.ec2_key:
name: "{{ aurora_staging_key_name }}"
key_material: "{{ lookup('ansible.builtin.file', aurora_staging_ssh_key ~ '.pub') }}"
tags: "{{ aurora_staging_tags }}"
state: present
- name: Find the official Ubuntu 24.04 images
amazon.aws.ec2_ami_info:
owners: ["{{ aurora_staging_ami_owner }}"]
filters:
name: "{{ aurora_staging_ami_name }}"
architecture: x86_64
state: available
register: aurora_staging_amis
- name: Choose the most recent image
ansible.builtin.set_fact:
aurora_staging_ami_id: "{{ (aurora_staging_amis.images | sort(attribute='creation_date') | last).image_id }}"ec2_keyimports your public key (read with thefilelookup on the control node) as an EC2 key pair. The private key never leaves your computer.- AMIs change per region and with every Ubuntu update. Instead of writing an ID (
ami-0123456789abcdef0) that will go stale, you search by owner (099720109477is Canonical's official account: filtering by owner avoids counterfeit images with the same name) and by name, and pick the most recent one by sorting oncreation_date.
A subtle consequence: when Canonical publishes a new image, aurora_staging_ami_id will change. You'll see it in the next section.
- Idempotent EC2 instances: tags, filters and
exact_count
exact_count10.1. The problem
A naive "create instance" module would create new instances on every run: three on Monday, six on Tuesday… In the cloud, idempotency is achieved by stating how many instances of each kind must exist and how to recognize them.
10.2. The tasks
- name: Maintain the instances for each role
amazon.aws.ec2_instance:
name: "{{ aurora_staging_name }}-{{ item.role }}"
image_id: "{{ aurora_staging_ami_id }}"
instance_type: "{{ aurora_staging_instance_type }}"
key_name: "{{ aurora_staging_key_name }}"
vpc_subnet_id: "{{ aurora_staging_subnet.subnet.id }}"
security_group: "{{ aurora_staging_name }}-{{ item.role }}"
volumes:
- device_name: /dev/sda1
ebs:
volume_size: 10
volume_type: gp3
delete_on_termination: true
tags: "{{ aurora_staging_tags | combine({'Role': item.role}) }}"
exact_count: "{{ item.count }}"
filters:
"tag:Project": aurora
"tag:Environment": staging
"tag:Role": "{{ item.role }}"
instance-state-name: [pending, running]
state: running
wait: true
loop:
- {role: web, count: "{{ aurora_staging_web_count }}"}
- {role: db, count: "{{ aurora_staging_db_count }}"}
loop_control:
label: "{{ item.role }} x {{ item.count }}"
- name: Query the running instances of the environment
amazon.aws.ec2_instance_info:
filters:
"tag:Project": aurora
"tag:Environment": staging
instance-state-name: running
register: aurora_staging_instancesThe key is exact_count + filters:
filtersdefines which instances count as "Aurora's staging web servers": those with these tags that are starting or running.exact_countsays how many there must be. If there are fewer, the missing ones are created (with the given image, type and tags); if there are more, the oldest ones are terminated; if there are exactly enough, nothing is done (changed=false).- Without
filters, the module would count using a default criterion that includes the image: whenaurora_staging_ami_idchanged (section 9), it wouldn't recognize the existing instances and would create new ones. By filtering on tags, the image is only used for new instances; existing ones keep theirs. (Renewing the image of existing instances means replacing them, a deliberate operation.) state: running+wait: true: the task doesn't finish until the instances are running and have a public IP.volumes: a 10 GBgp3root disk that's deleted when the instance is terminated (otherwise it would keep being billed).
The second task uses ec2_instance_info to query all the environment's running instances. It's the reliable way to get the complete list with their IPs, regardless of which ones were just created.
Scaling is changing a variable: with
aurora_staging_web_count: 3, the next run creates one more web instance; with1, it terminates two. This power demands care: a mistake in the filters or the count terminates instances. Always test with--checkfirst.
- Waiting for SSH,
add_host and configuring in the same playbook
add_host and configuring in the same playbook11.1. Adding the instances to the in-memory inventory
At the end of the first play:
- name: Add the instances to this run's inventory
ansible.builtin.add_host:
name: "{{ item.tags.Name }}-{{ item.instance_id[-4:] }}"
groups:
- staging_aws
- "staging_{{ item.tags.Role }}"
ansible_host: "{{ item.public_ip_address }}"
ansible_user: ubuntu
ansible_ssh_private_key_file: "{{ aurora_staging_ssh_key }}"
ansible_ssh_common_args: -o StrictHostKeyChecking=accept-new
aurora_env: staging
aurora_staging_private_ip: "{{ item.private_ip_address }}"
loop: "{{ aurora_staging_instances.instances }}"
loop_control:
label: "{{ item.tags.Name }} {{ item.public_ip_address }}"
changed_when: falseadd_hostadds a host to the in-memory inventory for thisansible-playbookrun (it doesn't write any file). The following plays can use it like any other host. It runs once per loop item even though the play runs onlocalhost.- Name:
aurora-staging-web-a1b2(Name + last 4 characters of the instance ID), unique and readable. - Groups:
staging_aws(all of them) andstaging_weborstaging_db. - Connection variables: the public IP, the user of the Ubuntu images on AWS (
ubuntu, notvagrant), the staging key. Since they're host variables, they take precedence overremote_userandprivate_key_fileinansible.cfg. StrictHostKeyChecking=accept-new: the instances are new and their fingerprint isn't inknown_hosts; withhost_key_checking = Truethe connection would fail.accept-newaccepts the fingerprint the first time and requires it to match on subsequent connections (trust on first use). It's a reasonable compromise for staging; the strict approach is to read the fingerprint from the instance's console output before connecting (Lesson 9.2).aurora_env: stagingas a host variable takes precedence over the one ininventory/group_vars/all/aurora.yml(lab), so themotdand the local facts will saystaging. The othergroup_vars/allvariables (team users, common packages, time zone) also apply to these hosts.
11.2. The second play
- name: Configure the staging environment servers
hosts: staging_aws
gather_facts: false
become: true
pre_tasks:
- name: Wait for the servers to accept SSH connections
ansible.builtin.wait_for_connection:
timeout: 300
- name: Wait for cloud-init to finish booting
ansible.builtin.command:
cmd: cloud-init status --wait
changed_when: false
- name: Gather the minimal facts
ansible.builtin.setup:
gather_subset: [min]
roles:
- commonwait_for_connectionkeeps retrying until Ansible manages to connect and run a module (SSH started, key installed, Python available).wait: trueinec2_instanceonly guarantees that the instance is "running" as far as AWS is concerned, not that the system has finished booting. That's why the play hasgather_facts: falseand the facts are gathered afterwards, by hand.cloud-init status --wait: on first boot, cloud images runcloud-init(it installs the SSH key, adjusts the system) and often a package update; if thecommonrole tried to useaptat the same time, it would fail because of the APT lock.roles: [common]: the same base configuration as in the lab. The instances end up with the common packages, the time zone, the team users, themotdshowingstagingand the local facts.
What about nginx, PostgreSQL and the website? The roles exist, but their data (group_vars/webservers.yml, dbservers/) is tied to the lab groups, and the staging database password shouldn't be the lab one. Configuring the full staging environment, with its own inventory and its own Vault identity, is exactly the goal of Lesson 9.1. Here the goal is the provisioning cycle.
11.3. Running it
export AWS_PROFILE=aurora-staging
ansible-playbook staging-aws.yml --syntax-check
ansible-playbook staging-aws.yml --check # what it would create (tasks that depend on real IDs may fail in --check)
ansible-playbook staging-aws.ymlTypical output at the end of the first play (fictitious values):
TASK [Add the instances to this run's inventory] ****
ok: [localhost] => (item=aurora-staging-web 198.51.100.21)
ok: [localhost] => (item=aurora-staging-web 198.51.100.37)
ok: [localhost] => (item=aurora-staging-db 198.51.100.52)And now the idempotency test, the most important one in the cloud:
The first play should finish with changed=0: no new instances, no rules changed. The second, also changed=0 in common. Check the result:
ssh -i ~/.ssh/aurora_staging_ed25519 [email protected] 'cat /etc/motd; groups laura'Commit cloud/aws-staging.yml, staging-aws.yml and collections/requirements.yml (with EE 1.2.0, as warned in section 3).
- Destroying the environment and keeping costs under control
12.1. The destruction playbook
In the cloud, destroying is as important as creating. staging-aws-destroy.yml:
---
# Destroys ALL the resources of the Aurora Store staging environment on AWS.
# Usage: ansible-playbook staging-aws-destroy.yml -e confirm=aurora-staging
- name: Destroy the Aurora Store staging environment on AWS
hosts: localhost
connection: local
gather_facts: false
vars_files:
- cloud/aws-staging.yml
module_defaults:
group/amazon.aws.aws:
region: "{{ aurora_staging_region }}"
tasks:
- name: Require explicit confirmation
ansible.builtin.assert:
that: confirm | default('') == aurora_staging_name
fail_msg: "To destroy the environment, add -e confirm={{ aurora_staging_name }}"
- name: Terminate the environment instances
amazon.aws.ec2_instance:
filters:
"tag:Project": aurora
"tag:Environment": staging
instance-state-name: [pending, running, stopping, stopped]
state: absent
wait: true
- name: Delete the key pair
amazon.aws.ec2_key:
name: "{{ aurora_staging_key_name }}"
state: absent
- name: Find the environment VPC
amazon.aws.ec2_vpc_net_info:
filters:
"tag:Name": "{{ aurora_staging_name }}"
"tag:Environment": staging
register: aurora_staging_vpcs
- name: Delete the environment network
when: aurora_staging_vpcs.vpcs | length > 0
vars:
aurora_staging_vpc_id: "{{ aurora_staging_vpcs.vpcs[0].id }}"
block:
- name: Delete the security groups (the one that references the other first)
amazon.aws.ec2_security_group:
name: "{{ aurora_staging_name }}-{{ item }}"
vpc_id: "{{ aurora_staging_vpc_id }}"
state: absent
loop: [db, web]
- name: Delete the route table
amazon.aws.ec2_vpc_route_table:
vpc_id: "{{ aurora_staging_vpc_id }}"
tags:
Name: "{{ aurora_staging_name }}-public"
state: absent
- name: Delete the internet gateway
amazon.aws.ec2_vpc_igw:
vpc_id: "{{ aurora_staging_vpc_id }}"
state: absent
- name: Delete the subnet
amazon.aws.ec2_vpc_subnet:
vpc_id: "{{ aurora_staging_vpc_id }}"
cidr: "{{ aurora_staging_subnet_cidr }}"
state: absent
- name: Delete the VPC
amazon.aws.ec2_vpc_net:
vpc_id: "{{ aurora_staging_vpc_id }}"
state: absent- Mandatory confirmation: the same pattern as Exercise 2 in Lesson 8.2. A playbook that destroys things mustn't be launchable by accident.
- Reverse order of creation, respecting dependencies: you can't delete a security group that's in use, or a VPC with subnets or gateways.
- Tags delimit what gets destroyed: only instances with
Project=auroraandEnvironment=staging. That's why tagging properly isn't optional. - Running it again when nothing is left finishes without errors and without changes: it's idempotent too.
12.2. Cost control
| Measure | How |
|---|---|
| Budget alerts | AWS Budgets: an email alert when you exceed, for example, €10 a month |
| Cost allocation tags | Activate Project and Environment as cost allocation tags: you'll see staging spending separately |
| Destroy what isn't used | staging-aws-destroy.yml when you finish; an environment can be recreated in minutes |
| Shut down outside working hours | A scheduled AWX template that stops the instances at night (state: stopped) and starts them in the morning |
| Watch for "forgotten" resources | Orphaned disks, unassociated Elastic IPs, snapshots, NAT gateways: they keep billing without instances |
| Choose small sizes | t3.micro / t4g.micro for testing |
Before closing the lesson, go into the AWS console (region eu-south-2) and check that there's no aurora-staging instance, volume or VPC left.
- What's next: dynamic inventory
add_host lets you configure what you've just created in the same run, but tomorrow, in another run, Aurora's inventory won't know those instances exist. The solution is dynamic inventory: a plugin (amazon.aws.aws_ec2) that, every time you run Ansible, asks the AWS API which instances there are and groups them by their tags (for example, an environment_staging group and a role_web group). AWX offers it as an inventory source of type Amazon EC2. You'll study it in depth in Lesson 10.2.
Common Mistakes and Tips
NoCredentialsError: Unable to locate credentials: you haven't exportedAWS_PROFILE(or the profile doesn't exist in~/.aws/credentials).UnauthorizedOperation: Ansible's identity doesn't have permission for that action; the message says which one. Extend the policy with the minimum needed.Failed to import the required Python library (botocore or boto3): you injected them into another Python environment;localhostuses Ansible's Python (pipx inject ansible boto3 botocore).- New instances are created on every run: the
filtersdon't match the tags set when they're created (one uppercase letter is enough), orfiltersis missing and the image has changed. wait_for_connectiontimes out: the security group doesn't allow SSH from your real IP (checkaurora_staging_admin_cidr; your public IP may change), or the subnet has no route to the internet.Could not get lock /var/lib/dpkg/lock-frontend:cloud-initorunattended-upgradeswas still using APT; that's why the play waits forcloud-init status --wait.DependencyViolationwhen destroying: some resource is still inside the VPC (an instance that's still terminating, a network interface). Wait and try again.- Tip: use
--checkbefore every change in the cloud and review the bill the day after your first tests.
Exercises
Exercise 1: scaling the web servers
The team wants to test with three web servers in staging. What do you change, what happens in the first play, how many hosts does the second one configure and what's the risk if someone mistakenly writes aurora_staging_web_count: 0?
Exercise 2: nightly shutdown
Write a staging-aws-power.yml playbook that stops or starts all the environment's instances according to a desired_state variable (stopped or running), designed for two AWX schedules (20:00 and 08:00, Monday to Friday).
Exercise 3: what's going wrong?
A colleague "fixes" the filter in the "Maintain the instances for each role" task by writing "tag:Project": Aurora (capitalized) and runs staging-aws.yml twice with the environment already created. Describe what happens on each run and how you undo it.
Solutions
Exercise 1. You change aurora_staging_web_count: 3 in cloud/aws-staging.yml. In the first play, the instances task creates one new web instance (the two existing ones match the filters) with the most recent AMI; ec2_instance_info returns four instances, and add_host adds all four. The second play configures all four: on the three existing ones common changes nothing, and on the new one it applies the whole configuration. With aurora_staging_web_count: 0, exact_count would terminate all the staging web servers: that's why it's worth validating the variables (an assert at the start, as in Lesson 5.5, requiring them to be greater than zero) and testing with --check, which would show changed on that task without running it.
Exercise 2.
---
- name: Start or stop the Aurora Store staging environment
hosts: localhost
connection: local
gather_facts: false
vars_files:
- cloud/aws-staging.yml
module_defaults:
group/amazon.aws.aws:
region: "{{ aurora_staging_region }}"
tasks:
- name: Check the requested state
ansible.builtin.assert:
that: desired_state | default('') in ['stopped', 'running']
fail_msg: "Pass -e desired_state=stopped or -e desired_state=running"
- name: Change the state of the environment instances
amazon.aws.ec2_instance:
filters:
"tag:Project": aurora
"tag:Environment": staging
instance-state-name: [pending, running, stopping, stopped]
state: "{{ desired_state }}"
wait: trueIn AWX: a template with this playbook, the Amazon Web Services credential and two schedules with different extra_vars. Bear in mind that, when started again, the instances get a different public IP (which is why the dynamic inventory from Lesson 10.2 is the definitive solution), and that the disks keep billing even while the instances are stopped.
Exercise 3. Tag values are case-sensitive. The existing instances have Project=aurora, so the filter with Aurora finds none: exact_count thinks there are zero web servers and zero databases and creates two and one new ones. But it creates them with the tags in aurora_staging_tags, which still say aurora… so on the second run the filter doesn't see them either and creates three more. After two runs there are nine instances being billed; ec2_instance_info (which filters correctly) returns them all and the second play configures all nine. To undo it: restore the filter and run staging-aws.yml: now the filter recognizes all nine, exact_count sees that there are six too many and terminates the oldest ones until two web servers and one database remain (another demonstration of why exact_count deserves respect). The lesson: the filters and the tags that are applied should come from the same variable (for example, building filters from aurora_staging_tags with dict2items and a tag: prefix), so they can't diverge.
Conclusion
You've provisioned cloud infrastructure with Ansible. You know which collection corresponds to each major provider and that they all share the same model: modules that run on the control node against the API, credentials outside the repository (profiles, environment variables, SSO or AWX credentials) and resources identified by name and tags. With amazon.aws you've created a staging environment for Aurora in eu-south-2: VPC, public subnet, internet gateway, route table, security groups that reference each other, key pair, an official Ubuntu AMI chosen by owner and date, and instances maintained with exact_count and tag filters; then you waited for SSH and cloud-init, added the instances to the inventory with add_host and configured them with the common role in the same playbook. And you've learned to destroy it all safely and to keep an eye on the bill. But staging-aws.yml already has more than a dozen tasks chained together by registered identifiers, plus a destruction playbook that has to be maintained by hand in reverse order; if tomorrow you add a managed database or a load balancer, both will grow and it will be easy for them to get out of sync. In the next lesson, Ansible and Terraform, you'll see how a tool specialized in provisioning, with its own state, and Ansible, specialized in configuration, split the work, and you'll rebuild Aurora's staging environment by combining the two.
Ansible Course: From Beginner to Advanced
Module 1: Introduction to Ansible
- What Is Ansible?
- Installing Ansible
- Setting Up the Practice Lab
- Ansible Architecture
- Basic Ansible Commands
Module 2: Ansible Fundamentals
- Inventory Files
- Inventory Variables: group_vars and host_vars
- Configuring Ansible (ansible.cfg)
- Ad Hoc Commands
- Ansible Modules
- Collections and Fully Qualified Names (FQCN)
Module 3: Playbooks
- Introduction to Playbooks
- Essential YAML for Ansible
- Writing Your First Playbook
- Playbook Structure
- Variables and Facts
- Conditionals and Loops
- Registering Results and Debugging Playbooks
Module 4: Roles
- Introduction to Roles
- Creating Roles
- Role Directory Structure
- Using Roles in Playbooks
- Reusing Tasks: include and import
- Role Dependencies and Argument Validation
Module 5: Advanced Playbook Techniques
- Handlers
- Jinja2 Templates
- Filters and Lookups
- Ansible Vault
- Error Handling
- Tags and Selective Execution
- Rolling Deployments and Delegation
- Optimizing Playbooks
Module 6: Ansible Galaxy
- What Is Ansible Galaxy?
- Using Ansible Galaxy
- Managing Dependencies with requirements.yml
- Creating and Sharing Roles
- Creating Your Own Collections
Module 7: Ansible Tower, AWX and Automation Platform
- Introduction to Ansible Tower and AWX
- Installing AWX
- Using AWX: Job Templates and Jobs
- Managing Projects and Inventories
- Credentials, Permissions (RBAC) and Workflows
- Execution Environments and ansible-navigator
Module 8: Ansible for DevOps
- Ansible and Docker
- Ansible and Kubernetes
- CI/CD with Ansible
- Ansible in Cloud Environments
- Ansible and Terraform
Module 9: Ansible Best Practices
- Code Organization
- Security Best Practices
- Performance Tuning
- Code Quality: ansible-lint and yamllint
- Testing Ansible Code with Molecule
Module 10: Advanced Ansible Topics
- Custom Modules
- Dynamic Inventory
- Ansible Plugins
- The Ansible API and ansible-runner
- Event-Driven Ansible
