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

  1. From the lab to the cloud: provisioning versus configuring
  2. Cloud provider collections
  3. The amazon.aws collection and its requirements
  4. Cloud credentials: never in the repository
  5. The design of the staging environment
  6. Variables and structure of the staging-aws.yml playbook
  7. The network: VPC, subnet, gateway and routes
  8. Security groups
  9. SSH key and system image
  10. Idempotent EC2 instances: tags, filters and exact_count
  11. Waiting for SSH, add_host and configuring in the same playbook
  12. Destroying the environment and keeping costs under control
  13. What's next: dynamic inventory

  1. 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)

  1. 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.

  1. The amazon.aws collection and its requirements

Add 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 -5

boto3 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-builder will add boto3 and botocore automatically, because the collection declares them. Remember the pipeline rule from Lesson 8.3: a change to collections/requirements.yml rebuilds aurora-ee, and since the 1.1.0 tag already exists, the job will fail until you bump options.tags to aurora-ee:1.2.0 in the same pull request (and image: in ansible-navigator.yml). That's exactly what should happen.

  1. 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/abcdefghijklmnopqrstuv
chmod 600 ~/.aws/credentials
export AWS_PROFILE=aurora-staging

If 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.

  1. The design of the staging environment

flowchart 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=ansible and, on the instances, Role=web or Role=db. Tags are the basis of idempotency (section 10), of safe destruction (section 12) and of cost allocation.

  1. Variables and structure of the staging-aws.yml playbook

The 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: ansible

Why 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):

ssh-keygen -t ed25519 -f ~/.ssh/aurora_staging_ed25519 -C "aurora-staging" -N ""

(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 11

module_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.

  1. 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: present

How 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 example vpc-0a1b2c3d4e5f60718). You never write IDs by hand: they change in every account and on every creation.
  • combine (Lesson 5.3) adds the Name tag to the common tags.
  • map_public: true: instances in the subnet get a public IP automatically.
  • gateway_id: igw is 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.utils filters (ipsubnet, ipaddr) do it: aurora_staging_vpc_cidr | ansible.utils.ipsubnet(24, 1) returns 10.40.1.0/24. Aurora doesn't need them and doesn't add that collection.

  1. 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 rules define the inbound traffic.
  • group_name as the source allows traffic from any instance in the aurora-staging-web group, 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's postgresql_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, like ufw on 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.

  1. 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_key imports your public key (read with the file lookup 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 (099720109477 is 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 on creation_date.

A subtle consequence: when Canonical publishes a new image, aurora_staging_ami_id will change. You'll see it in the next section.

  1. Idempotent EC2 instances: tags, filters and exact_count

10.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_instances

The key is exact_count + filters:

  • filters defines which instances count as "Aurora's staging web servers": those with these tags that are starting or running.
  • exact_count says 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: when aurora_staging_ami_id changed (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 GB gp3 root 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; with 1, it terminates two. This power demands care: a mistake in the filters or the count terminates instances. Always test with --check first.

  1. Waiting for SSH, add_host and configuring in the same playbook

11.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: false
  • add_host adds a host to the in-memory inventory for this ansible-playbook run (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 on localhost.
  • Name: aurora-staging-web-a1b2 (Name + last 4 characters of the instance ID), unique and readable.
  • Groups: staging_aws (all of them) and staging_web or staging_db.
  • Connection variables: the public IP, the user of the Ubuntu images on AWS (ubuntu, not vagrant), the staging key. Since they're host variables, they take precedence over remote_user and private_key_file in ansible.cfg.
  • StrictHostKeyChecking=accept-new: the instances are new and their fingerprint isn't in known_hosts; with host_key_checking = True the connection would fail. accept-new accepts 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: staging as a host variable takes precedence over the one in inventory/group_vars/all/aurora.yml (lab), so the motd and the local facts will say staging. The other group_vars/all variables (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:
    - common
  • wait_for_connection keeps retrying until Ansible manages to connect and run a module (SSH started, key installed, Python available). wait: true in ec2_instance only guarantees that the instance is "running" as far as AWS is concerned, not that the system has finished booting. That's why the play has gather_facts: false and the facts are gathered afterwards, by hand.
  • cloud-init status --wait: on first boot, cloud images run cloud-init (it installs the SSH key, adjusts the system) and often a package update; if the common role tried to use apt at 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, the motd showing staging and 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.yml

Typical 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:

ansible-playbook staging-aws.yml

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).

  1. 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=aurora and Environment=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.
ansible-playbook staging-aws-destroy.yml -e confirm=aurora-staging

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.

  1. 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 exported AWS_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; localhost uses Ansible's Python (pipx inject ansible boto3 botocore).
  • New instances are created on every run: the filters don't match the tags set when they're created (one uppercase letter is enough), or filters is missing and the image has changed.
  • wait_for_connection times out: the security group doesn't allow SSH from your real IP (check aurora_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-init or unattended-upgrades was still using APT; that's why the play waits for cloud-init status --wait.
  • DependencyViolation when destroying: some resource is still inside the VPC (an instance that's still terminating, a network interface). Wait and try again.
  • Tip: use --check before 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: true

In 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

Module 2: Ansible Fundamentals

Module 3: Playbooks

Module 4: Roles

Module 5: Advanced Playbook Techniques

Module 6: Ansible Galaxy

Module 7: Ansible Tower, AWX and Automation Platform

Module 8: Ansible for DevOps

Module 9: Ansible Best Practices

Module 10: Advanced Ansible Topics

Module 11: Final Project

© Copyright 2026. All rights reserved