Ansible Hour 4: Moving to the Cloud (AWS)

Use the amazon.aws collection to create a VPC and EC2 instances, discover hosts with the aws_ec2 dynamic inventory, and deploy myapp to EC2 using the SSM connection plugin, with “zero inbound ports, zero SSH keys”.
ansible-core 2.21Ansible 14.xamazon.aws 12.1.0community.aws 12.0.0boto3/botocore ≥ 1.38.23Verified against official docs · 2026-11
Overall learning objectives
  • Set up amazon.aws the collection and its Python dependencies (boto3/botocore), and explain boto3 credential chain lookup order, and use IAM Identity Center (SSO) profile and assume role obtain short-term credentials, without storing any access keys in the repository.
  • Write *.aws_ec2.yml dynamic inventory: use filters for precise selection, keyed_groups to group automatically by tag, hostnames to choose host names (must be instance IDs for SSM), compose to generate variables, and enable caching.
  • Use amazon.aws modules to create, idempotently, VPCs, subnets, internet gateways, route tables, security groups, IAM roles and instance profiles, and EC2 instances, and be able to clean everything up in one step.
  • Understand the SSM connection plugin amazon.aws.aws_ssm (moved from community.aws as of 10.0.0) and how it runs a task end to end: control node → S3 → SSM session → SSM Agent on the instance → curl downloads the module → Python executes → result returned. Know its prerequisites, pros and cons, and performance characteristics.
  • Use amazon.aws.secretsmanager_secret and amazon.aws.ssm_parameter lookup plugins to read secrets and configuration at runtime, rather than writing them into a Vault file or inventory.
  • Deploy myapp to an EC2 instance with no inbound rules, and quickly pinpoint cloud failures such as credential issues, boto3 version, empty inventory, SSM connection failures, AccessDenied, and throttling.

1-hour time allocation

#TimeModuleCore contentAnimation / interactionLab (AWS ca-central-1)
0Before classWarm-up and AWS setupAWS CLI v2, SSO login, Session Manager plugin, collection and boto3, project directory and variablesEnvironment self-check checklistaws sts get-caller-identity Success
100–06amazon.aws and authenticationCollection structure, boto3/botocore version requirements, credential chain, SSO profile, assume role,module_defaultsCredential chain lookup simulatorCalling with SSO profile and assume role aws_caller_info
206–13aws_ec2 dynamic inventoryFile naming rules, filters / include / exclude, keyed_groups, hostnames, compose, cachingEC2 instances → inventory group generatorWrite out lab.aws_ec2.yml and ansible-inventory --graph
313–22Creating AWS resources with AnsibleVPC, subnets, IGW, route tables, security groups, IAM roles and instance profiles, EC2 (IMDSv2), tags and idempotencyCreate resources step by step along the dependency chainprovision.yml Create 2 EC2 instances
422–30Managing without SSH: the SSM connection pluginPrerequisites (S3 bucket, SSM Agent, instance role, Session Manager plugin), connection variables, become, performance and limitsCore animation: The full run of one task through S3 + SSMansible -m ping Via SSM
530–37Secrets: Secrets Manager and SSM parametersTwo lookup plugins, running on the control node, on_missing/on_denied, KMS, comparison with Ansible Vault, no_logDemo: when lookup plugins are evaluatedCreate a secret and a parameter and read them in a play
637–44Configuring EC2 and deploying the appApplying the myapp role to EC2 via SSM, become and ssm-user, rolling deployment serial, health checksRolling deployment timelineDeploy myapp and verify it on the instance /healthz
744–53Cloud troubleshooting in practiceCredentials, boto3 version, empty inventory, SSM connection failures (S3 permissions, proxy), AccessDenied, throttlingInteractive troubleshooting treeDeliberately cause 3 faults and fix them
853–60Cost, cleanup and self-testBillable items (EC2, public IPv4, EBS, S3, Secrets Manager, KMS), cleanup by tag, cleanup order, self-testCost calculatordestroy.yml + leftover check
—After classCheat sheet · Capstone labDeploy myapp to EC2 without SSH, then clean upFinal quiz (12 questions)Capstone lab

Knowledge Coverage Matrix

Target skillsM1M2M3M4M5M6M7M8Key commandsLabs
Install amazon.aws and boto3, manage short-term credentials✓·····✓·ansible-galaxy collection install,aws sso loginM1 lab
Dynamic inventory and grouping by tag·✓·✓·✓✓·ansible-inventory -i lab.aws_ec2.yml --graphM2 lab
Idempotent creation of network and compute resources··✓····✓ansible-playbook provision.ymlprovision.yml
IAM roles, instance profiles and least privilege✓·✓✓✓·✓·iam_role,iam_instance_profileM3 / M4 labs
Manage instances without SSH via SSM·✓·✓·✓✓·ansible_connection: amazon.aws.aws_ssmM4 lab
Read cloud secrets at runtime····✓✓✓·lookup('amazon.aws.secretsmanager_secret', …)M5 lab
Deploy the role to cloud hosts and do a rolling release···✓✓✓··serial,uri,wait_for_connectionM6 lab
Cloud fault diagnosis✓✓·✓✓·✓·-vvvv,aws ssm describe-instance-informationM7 lab
Cost control and complete cleanup··✓····✓destroy.yml,resourcegroupstaggingapiM8 lab

Topics excluded from this lesson (and where to learn them)

TopicWhy not in this lessonWhere to learn
Azure VMs, azure.azcollection, azure_rm dynamic inventoryCovered in the previous lesson; this lesson mirrors its structure one-to-oneHour 3
Managing EKS / ECS and CloudFormation modules with AnsibleContainer orchestration and declarative IaC tools are a better fitK8s lesson · Terraform lesson(Lesson 4, AWS)
GitHub Actions OIDC, AWS credential types in AWX, EDA listening to SQS/CloudTrailBelongs to the automation operations topicHour 5
Multi-tier architecture (nginx + 2 app nodes + PostgreSQL)This lesson deploys only the single-tier myappHour 6
Windows EC2 (PowerShell via SSM)Time is limited, so it is mentioned only briefly in M4 ansible_shell_type: powershellOfficial aws_ssm examples
VPC interface endpoints (PrivateLink), fully offline SSM in private subnetsEach endpoint is billed hourly; this lesson uses public subnets with no inbound rules to keep costs downM4 “production case” gives the key configuration points;AWS docs

How to use these course materials

10 pages per module
Theory · diagrams · animations · commands · labs · production cases · troubleshooting · quizzes · audio · video. The “animation” in M4 is the core of this lesson; play it through fully before you start hands-on work.
Learning progress
A quiz score of ≥ 70% or clicking “Mark module complete” counts toward progress. Progress is saved in this browser (cleared on refresh if local storage is disabled).
Cloud cost reminder
This lesson creates hourly-billed resources in your AWS account (about 0.03–0.05 USD/hour; see M8). Be sure to run destroy.yml, then confirm with the leftover-check command in M8.
Version notes Lesson baseline (verified 2026-11-15): ansible-core 2.21 (control node Python 3.12–3.14), Ansible community package 14.x; on Galaxy, amazon.aws latest 12.1.0,community.aws latest 12.0.0. amazon.aws 12.x requires ansible-core ≥ 2.18,boto3/botocore ≥ 1.38.23, Python ≥ 3.9 (3.9 is deprecated; versions released after 2027-04-01 will require 3.10+). The SSM connection plugin has been in amazon.aws since amazon.aws 10.0.0 version, and is named amazon.aws.aws_ssm (old name community.aws.aws_ssm still common in older environments); the lookup plugins aws_secret/aws_ssm were renamed, as of 6.0.0, to secretsmanager_secret/ssm_parameter. The amazon.aws version bundled with the Ansible 14 package may be below 12.1.0, so this lesson uses requirements.yml to pin the collection in the project directory.

Module 0 · Warm-up and AWS setup (complete before class)

Switching from Azure in the previous lesson to AWS: same control node, same project directory, same myapp role, but a different set of credentials and connection method
Before class ≈ 15 minca-central-1Requires an AWS account
Prerequisites
  • CompletedHour 3 (Azure)or at least lessons 1–2: control node is Ubuntu 24.04 (Azure VM or local), using pipx install --include-deps ansible with Ansible 14.x installed; project directory ~/ansible-lab contains roles/myapp (written in lesson 2; if you don't have it, M6 provides a trimmed-down version).
  • An AWS account that you can sign in to through IAM Identity Center (SSO) sign-in, with the permissions the labs need (see “Required permissions” below). Personal accounts without SSO can also use an IAM user + aws configure, but delete the access key after class.
  • Use the region ca-central-1 (consistent with the Docker lesson). Tag all resources Project=ansible-lab, and look them up by tag when cleaning up.

Continuity from the previous lesson: what changed and what stayed the same

ItemLesson 3 (Azure)Lesson 4 (AWS)
Collectionazure.azcollectionamazon.aws (+ a few community.aws)
Python dependenciesCollection's bundled requirements (a long list of Azure SDK packages)Only needs boto3 + botocore
Authenticationaz login / service principal / managed identitySSO profile / assume role / instance profile
Dynamic inventory*.azure_rm.yml*.aws_ec2.yml
Connection methodSSH (or Azure Bastion)SSM Session Manager, zero inbound ports
SecretsKey Vault lookupSecrets Manager / SSM Parameter Store lookup
UnchangedControl node,ansible.cfg,roles/myapp, playbook syntax, idempotency concepts,--check --diff

Step 1: Install AWS CLI v2 and the Session Manager plugin

cd /tmp
curl -sSLo awscliv2.zip "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip"
unzip -q awscliv2.zip && sudo ./aws/install --update
aws --version

# Session Manager plugin (the aws_ssm connection plugin depends on it)
curl -sSLo session-manager-plugin.deb \
  "https://s3.amazonaws.com/session-manager-downloads/plugin/latest/ubuntu_64bit/session-manager-plugin.deb"
sudo dpkg -i session-manager-plugin.deb
session-manager-plugin --version
command -v session-manager-plugin
aws-cli/2.x.x Python/3.13.x Linux/6.8.0-1015-azure exe/x86_64.ubuntu.24
1.2.xxx.0
/usr/local/bin/session-manager-plugin
Why paths matteramazon.aws.aws_ssm It looks first in /usr/local/bin/session-manager-plugin, and searches elsewhere only if it is not found PATH; you can also set the variable ansible_aws_ssm_plugin or the environment variable AWS_SESSION_MANAGER_PLUGIN to specify it. On an ARM control node, download ubuntu_arm64 version.

Step 2: Configure the SSO profile and sign in

aws configure sso --profile lab
# Enter in turn: SSO session name: lab-sso; SSO start URL: https://<your-portal>.awsapps.com/start
# SSO region: ca-central-1 (use the region where your Identity Center is located); choose the account and permission set; default region ca-central-1
aws sso login --profile lab
aws sts get-caller-identity --profile lab
{
    "UserId": "AROAEXAMPLEID:andy",
    "Account": "111122223333",
    "Arn": "arn:aws:sts::111122223333:assumed-role/AWSReservedSSO_LabAdmin_0123456789abcdef/andy"
}

Step 3: Install the collection and boto3 in the project

cd ~/ansible-lab
pipx inject ansible boto3 botocore          # install boto3 into the pipx virtual environment where ansible lives
cat > requirements.yml <<'EOF'
---
collections:
  - name: amazon.aws
    version: ">=12.1.0,<13.0.0"
  - name: community.aws
    version: ">=12.0.0,<13.0.0"
EOF
ansible-galaxy collection install -r requirements.yml -p ./collections
ansible-galaxy collection list amazon.aws -p ./collections
"$(pipx environment --value PIPX_LOCAL_VENVS)/ansible/bin/python" -c "import boto3,botocore;print(boto3.__version__, botocore.__version__)"
# /home/azureuser/ansible-lab/collections/ansible_collections
Collection Version
---------- -------
amazon.aws 12.1.0
1.40.x 1.40.x
The easiest pitfall to hit boto3 must be installed in the same Python that runs Ansible. Ansible installed with pipx has its own virtual environment,pip install --user boto3 or apt install python3-boto3 are both installed in the wrong place. Use ansible --version the python version and executable location fields in the output to confirm the interpreter. Ubuntu 24.04's python3-boto3 package version is old and does not meet the minimum requirement of amazon.aws 12.x.

Step 4: Project directory and shared variables

mkdir -p ~/ansible-lab/{inventories/aws/group_vars/all,playbooks/aws,files}
cat > ~/ansible-lab/inventories/aws/group_vars/all/aws.yml <<'EOF'
---
aws_profile: lab
aws_region: ca-central-1
lab_prefix: ansible-lab
lab_tags:
  Project: ansible-lab
  Course: ansible-part4
  Owner: "{{ lookup('ansible.builtin.env', 'USER') }}"
EOF
tree -L 3 ~/ansible-lab -I collections
/home/azureuser/ansible-lab
├── ansible.cfg
├── inventories
│   └── aws
│       └── group_vars
├── playbooks
│   └── aws
├── requirements.yml
└── roles
    └── myapp

Required permissions and costs (read before you start)

CategoryDescription
IAM permissionsThe lab permission set needs at least: ec2:* (VPC/subnet/IGW/route table/security group/instance),iam:CreateRole/PassRole/CreateInstanceProfile/AddRoleToInstanceProfile/AttachRolePolicy and the matching delete permissions,s3:* (lab bucket),ssm:StartSession/TerminateSession/DescribeInstanceInformation/GetParameter*/PutParameter/DeleteParameter,secretsmanager:CreateSecret/GetSecretValue/DeleteSecret,sts:AssumeRole. The simplest approach is to use a sandbox account with the AdministratorAccess permission set. For production accounts, tighten permissions to the least-privilege policy given in M4.
Estimated cost2 × t3.micro + 2 public IPv4 addresses + 2 × 8 GiB gp3 + S3 + 1 secret, about 0.04 USD/hour; completing this whole lesson (about 2 hours) typically costs less than 0.2 USD. Secrets Manager bills per secret per month (prorated), so delete the secret as soon as you finish. For current unit prices, see the AWS pricing page and the M8 cost calculator.
Security risksLesson instances have no inbound rules, and no SSH keys are assigned. The main risks are credential leakage from the control node and leftover module files in the S3 bucket (which may contain secret parameters); M4 explains how to mitigate them.
CleanupUse the M8 destroy.yml; fallback commands are on the M8 “Commands” page.

Warm-up: answer from memory (30 seconds)

What must the file name of the Azure dynamic inventory from the previous lesson end with? Why?

azure_rm.yml/azure_rm.yaml. Inventory plugins' verify_file() file name suffix determines whether they “claim” the file. For this lesson's aws_ec2 plugin, likewise, the file name must end with aws_ec2.yml/aws_ec2.yaml .

What are the basic steps Ansible takes to execute a module?

The control node renders the module (packaged with AnsiballZ) → the connection plugin transfers the file to a temp directory on the managed node → it runs with the managed node's Python → the module prints JSON to stdout → the control node parses it as ok/changed/failed. The only change in this lesson is the “connection plugin” layer: SSH is replaced by SSM + S3.

Environment self-check checklist

Module 1 · amazon.aws and authentication

00:00 – 06:00 · Every AWS module ultimately is “boto3 on the control node calling the AWS API”, so get boto3 and credentials right first
6 minamazon.aws 12.1.0boto3/botocore ≥ 1.38.23★★★★★
Learning objectives
  • Distinguish amazon.aws (Red Hat supported, core services) from community.aws (community-maintained, long-tail services), and know the FQCN changes caused by module migration.
  • State the lookup order of the boto3 credential chain, and be able to tell “which credentials this call actually used”.
  • Configure an SSO profile and an assume role profile, and use module_defaults to pass profile/region uniformly, or use sts_assume_role to temporarily switch roles.
Prerequisite knowledge: Basic AWS IAM concepts (users, roles, policies, trust policies). Importance:★★★★★ (the primary source of cloud Ansible failures)

What: what amazon.aws is

amazon.aws is Ansible's official AWS collection (Red Hat certified, supported in AAP). It includes EC2, VPC, S3, IAM, RDS, Route 53, CloudWatch, Secrets Manager lookup, SSM parameter lookup,aws_ec2/aws_rds inventory plugin, and aws_ssm connection plugin. community.aws is a community collection that holds modules with narrower use or that have not yet “graduated” (such as ec2_launch_template,wafv2_*,ssm_inventory_info etc.). Once a module matures, it moves from community.aws to amazon.aws. For example, aws_ssm the connection plugin in amazon.aws 10.0.0 moved in, along with a batch of ec2_vpc_* modules (nacl, peering, vgw, vpn, etc.) in 9.0.0 amazon.aws moved in. After migration, the old FQCN usually keeps a redirect for a while, but new code should always use the amazon.aws FQCN.

Itemamazon.aws (12.1.0)community.aws (12.0.0)
MaintainerRed Hat + AWS community, AAP-certified contentCommunity
Typical contentec2_instance, ec2_vpc_net, ec2_security_group, iam_role, iam_instance_profile, s3_bucket, aws_ec2 inventory, aws_ssm connection, secretsmanager_secret / ssm_parameter lookupsec2_launch_template, elb_target_group, ecs_*, wafv2_* and other long-tail services
Dependenciesansible-core ≥ 2.18; Python ≥ 3.9 (3.9 is deprecated); boto3 ≥ 1.38.23, botocore ≥ 1.38.23 (12.x README)

SDK support policy: since 2.0.0, the collection aims to support “boto3/botocore releases from the 12 months before the latest major version”; the legacy boto (boto2) was fully removed in 4.0.0. So when the collection moves to a new major version, boto3 often needs upgrading too.

Why: why authentication is the first hurdle

Unlike SSH, AWS modules run locally on the control node (a playbook usually sets hosts: localhost,connection: local), and boto3 calls the AWS API directly. If boto3 picks up the wrong credentials, such as an expired SSO token or leftover AWS_ACCESS_KEY_ID, or the wrong profile, every module will fail, and the error is often just one line: Unable to locate credentials or ExpiredToken.

How: the boto3 credential chain (the first source found wins)

OrderSourceHow it appears in Ansible
1Explicit parametersModule parameters access_key/secret_key/session_token, or profile (when a profile is specified, credentials come from that profile's configuration)
2Environment variablesAWS_ACCESS_KEY_ID,AWS_SECRET_ACCESS_KEY,AWS_SESSION_TOKEN; AWS_PROFILE Selected profile
3role/SSO settings in configthe profile contains role_arn + source_profile (assume role),web_identity_token_file (OIDC, lesson 5),sso_session (IAM Identity Center)
4~/.aws/credentialsStatic access key (not recommended)
5~/.aws/configcredential_process etc.
6Container credentialsECS task role, EKS Pod Identity (when the control node runs in a container)
7Instance metadata (IMDS)The control node is itself an EC2 instance with an instance profile attached (a common setup for AAP/AWX running on EC2)

Region works the same way: module parameter region → environment variable AWS_REGION/AWS_DEFAULT_REGION → the profile's region. Without a region, most modules fail immediately with NoRegionError. For the full order, see the boto3 “Credentials” documentation.

When: which credential to choose

  • Running a playbook by hand in a terminal: an SSO profile (aws sso login; the token expires after a few hours by default and refreshes automatically).
  • Cross-account operations: add an assume role profile on top of the SSO profile (role_arn + source_profile), or use amazon.aws.sts_assume_role.
  • CI/CD: GitHub Actions OIDC → AssumeRoleWithWebIdentity (lesson 5).
  • AWX/AAP running on EC2/EKS: instance profile or Pod Identity, with zero static keys.
  • Always avoid: storing access keys long-term in group_vars, inventory or Vault files.

Comparison with similar technology

Ansible + amazon.awsTerraform AWS providerAnsible + azure.azcollection (previous lesson)
Where API calls are madeControl node boto3Provider plugin (Go SDK)Control node Azure SDK
Credential chainboto3 standard chainAWS SDK for Go standard chain (same config files)az CLI / environment variables / MSI
StateStateless; queries the current state by tag/name on each runstate fileStateless
Common misconceptions① “The SSM Agent on EC2 uses the instance role, so Ansible modules also use the instance role” is wrong; modules run on the control node and use the control node's credentials. ② “If you have set profile: lab , environment variables will not be read”. Explicit parameters have the highest priority, which is correct; but if in the module you did not set any profile, but the shell still has leftover AWS_ACCESS_KEY_ID, and it will override AWS_PROFILE. ③ “Having awscli installed means you have boto3”—AWS CLI v2 is a standalone program with its own bundled runtime and has nothing to do with the boto3 in the Python that Ansible uses.

Architecture diagram: an AWS module from playbook to AWS API

playbook hosts: localhostamazon.aws.ec2_vpc_netmodule_defaults: profile/region Module process (local) AnsibleAWSModuleCheck boto3/botocore versionboto3.Session(profile, region) Credential chain Parameters → environment variables→ SSO / assume role→ file → container → IMDS AWS APISigV4-signed HTTPSec2.ca-central-1.amazonaws.com ~/.aws/config [profile lab] sso_session = lab-sso · sso_account_id · sso_role_name · region [profile lab-deployer] role_arn = arn:aws:iam::…:role/ansible-deployer · source_profile = lab [sso-session lab-sso] sso_start_url · sso_region · sso_registration_scopes
Figure 1-1: AWS modules run on the control node; boto3 obtains credentials from the credential chain, then calls the regional endpoint with SigV4 signing

Flowchart: getting short-term credentials via SSO + assume role

aws sso loginBrowser device authorization SSO token cache~/.aws/sso/cache/*.json sso:GetRoleCredentialsof the permission-set roletemporary credentials (profile lab) sts:AssumeRoleTrust policy check(profile lab-deployer) Short-term credentials1 hour by default botocore automatically completes steps 3–5 and refreshes before expiry; once the SSO token itself expires, you need to run aws sso login again If any step fails, the Ansible module only sees the exception text thrown by botocore (see the “Troubleshooting” page)
Figure 1-2: From SSO sign-in to assume role: no long-term access keys are used at any point

Interactive simulator: which credentials did boto3 actually use this time?

Check the credential sources that “exist on the control node”, then click “Play”. The simulator checks them one by one in botocore's actual order, stops at the first usable source, and the terminal below shows the corresponding aws sts get-caller-identity result and common pitfalls.

Core commands and parameters

Command / modulePurposeKey parameters / notes
ansible-galaxy collection install -r requirements.yml -p ./collectionsInstall the collection into the project directoryUse together with ansible.cfg the collections_path; pin the major version
pipx inject ansible boto3 botocoreInstall the SDK into Ansible's virtual environmentUse for upgrades pipx inject --force ansible boto3 botocore
aws configure sso / aws sso loginConfigure and sign in to IAM Identity Center--profile lab; sign in again when the token expires
amazon.aws.aws_caller_infoReturns the current identity (account, arn, user_id)“whoami” in a playbook; suitable as the first task
amazon.aws.sts_assume_roleSwitch roles within a playrole_arn,role_session_name,duration_seconds; returns sts_creds
module_defaults: group/amazon.aws.awsSet default profile/region for all modules in the collectionAvoid repeating it in every task
[defaults]
collections_path = ./collections
inventory = inventories/aws
interpreter_python = auto_silent
---
- name: Check AWS identity
  hosts: localhost
  connection: local
  gather_facts: false
  module_defaults:
    group/amazon.aws.aws:
      profile: "{{ aws_profile }}"
      region: "{{ aws_region }}"
  tasks:
    - name: Current caller
      amazon.aws.aws_caller_info:
      register: me

    - name: Show identity
      ansible.builtin.debug:
        msg: "account={{ me.account }} arn={{ me.arn }}"
cd ~/ansible-lab
ansible-playbook -i inventories/aws playbooks/aws/whoami.yml
PLAY [Check AWS identity] ***********************************************************
TASK [Current caller] ****************************************************************
ok: [localhost]
TASK [Show identity] ******************************************************************
ok: [localhost] => {
    "msg": "account=111122223333 arn=arn:aws:sts::111122223333:assumed-role/AWSReservedSSO_LabAdmin_0123456789abcdef/andy"
}

How to verify: The role name in the arn should match the permission set/role you expect. Common error: If inventories/aws has no inventory file yet, Ansible warns “No inventory was parsed, only implicit localhost is available”; this has no effect on this playbook. Production use: Make this task the first step in every cloud playbook, and add assert an account check to prevent “running a test playbook in the production account”.

Two ways to write assume role

[profile lab-deployer]
role_arn = arn:aws:iam::111122223333:role/ansible-deployer
source_profile = lab
role_session_name = ansible
region = ca-central-1
duration_seconds = 3600
- name: Switch to the deployment role
  amazon.aws.sts_assume_role:
    profile: "{{ aws_profile }}"
    role_arn: "arn:aws:iam::{{ target_account }}:role/ansible-deployer"
    role_session_name: "ansible-{{ lookup('ansible.builtin.env', 'USER') }}"
    duration_seconds: 3600
  register: assumed
  no_log: true

- name: Operate on the target account with temporary credentials
  amazon.aws.ec2_vpc_net_info:
    access_key: "{{ assumed.sts_creds.access_key }}"
    secret_key: "{{ assumed.sts_creds.secret_key }}"
    session_token: "{{ assumed.sts_creds.session_token }}"
    region: "{{ aws_region }}"

Method A is refreshed automatically by botocore, which is the least hassle; method B suits “querying in account A, then making changes in account B within the same play”, but once the temporary credentials expire (1 hour by default), you need to obtain them again. Note Do not pass profile and access_key to one module at the same time.

Lab 1: Confirm the SDK version, identity and credential priority (about 5 min)

Confirm the Python and boto3 that Ansible uses
ansible --version | grep -E "core|python version|executable"
"$(pipx environment --value PIPX_LOCAL_VENVS)/ansible/bin/python" -m pip list 2>/dev/null | grep -Ei "^(boto3|botocore) "
ansible [core 2.21.5]
  python version = 3.13.x (main, …) [GCC 13.3.0] (/home/azureuser/.local/share/pipx/venvs/ansible/bin/python)
  executable location = /home/azureuser/.local/bin/ansible
boto3    1.40.x
botocore 1.40.x
Run whoami.yml (see the “Commands” page) and confirm the account and arn.
Experience credential priority: set a fake access key in the shell, do not set a profile in the module, and see what happens.
export AWS_ACCESS_KEY_ID=AKIAFAKEFAKEFAKE AWS_SECRET_ACCESS_KEY=fake
export AWS_PROFILE=lab
ansible localhost -m amazon.aws.aws_caller_info -a "region=ca-central-1"
ansible localhost -m amazon.aws.aws_caller_info -a "region=ca-central-1 profile=lab"
unset AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY
localhost | FAILED! => {
    "msg": "Failed to retrieve caller identity: An error occurred (InvalidClientTokenId) when calling the GetCallerIdentity operation: The security token included in the request is invalid."
}
localhost | SUCCESS => {
    "account": "111122223333", ...
}

First run: the static key in environment variables takes precedence over AWS_PROFILE; second run: module parameters profile are explicit parameters with the highest priority. Conclusion: When troubleshooting authentication on CI or shared machines, first env | grep ^AWS_.

(optional) assume role: if you have a role that a permission-set role can assume ansible-deployer role, configure a profile with method A on the “Commands” page, then run:
aws sts get-caller-identity --profile lab-deployer
ansible localhost -m amazon.aws.aws_caller_info -a "region=ca-central-1 profile=lab-deployer"

The arn should change to assumed-role/ansible-deployer/ansible. If you do not have this role, skip this step; later labs use lab the profile.

Cleanup: this lab creates no resources. Confirm that env | grep ^AWS_ only AWS_PROFILE remains (or is empty).

Case 1: CI machine “occasionally” operates on the wrong account

Problem: On a shared Jenkins node, a job exported another account's access key and never cleaned it up; a later Ansible task in the playbook only specified AWS_PROFILE, so resources were created in the wrong account. Approach: Make the first step of every cloud playbook call aws_caller_info and assert assert that the account is on the allow list; CI switches to short-term OIDC credentials, and jobs are isolated in containers. Configuration:that: me.account == expected_account. Limitations: assert can only detect the problem; the real fix is to remove the static key.

Case 2: batch audit across multiple accounts (Organizations)

Problem: Security groups need to be audited across 30 member accounts. Approach: SSO permission set in the central account → loop sts_assume_role assume the read-only role in each member account OrganizationAccountAccessRole (or a custom ansible-audit) → call ec2_security_group_info. Configuration:loop: "{{ accounts }}" + include_tasks. Limitations: Watch for STS and EC2 API throttling; add throttle or reduce concurrency (M7).

Case 3: zero-key approach for AAP running on EC2

Problem: The security team prohibits any long-term access keys. Approach: Attach an instance profile to the EC2 instance that runs the AAP execution node, granting only sts:AssumeRole; in the job template, assume the specific business role. Limitations: The IMDSv2 hop limit defaults to 1; to access IMDS from the execution environment (a container), you need to set http_put_response_hop_limit to 2.

Common errors and fixes

Failed to import the required Python library (botocore and boto3) on controller's Python /usr/bin/python3

Cause: boto3/botocore is not installed in the Python that runs the module. For hosts: localhost plays, modules use by default ansible_python_interpreter (with implicit localhost this is the Python that runs Ansible; if localhost is explicitly defined in the inventory, it may become /usr/bin/python3).

ansible --version | grep "python version"
ansible localhost -m ansible.builtin.setup -a "filter=ansible_python" | grep executable

Fix:pipx inject ansible boto3 botocore; if localhost is explicitly defined in the inventory, set ansible_python_interpreter: "{{ ansible_playbook_python }}".

amazon.aws.ec2_vpc_net requires boto3 >= 1.38.23 and botocore >= 1.38.23 (or a similar version-too-old message)

Cause: After the collection was upgraded to 12.x, the minimum SDK version was raised.

pipx inject --force ansible "boto3>=1.38.23" "botocore>=1.38.23"

Prevention: In requirements.txt the file, pin boto3 along with the collection version, and install consistently in CI (lesson 5).

Unable to locate credentials. You can configure credentials by running "aws configure".

Cause: No source in the credential chain was found: no profile was passed, no variable was exported AWS_PROFILE, and not on EC2.

env | grep ^AWS_
aws configure list --profile lab

Fix: In module_defaults pass profile, or export AWS_PROFILE=lab.

Error when retrieving token from sso: Token has expired and refresh failed

Cause: The SSO access token has expired (session duration is set by Identity Center).

aws sso login --profile lab

Prevention: Sign in again before starting long-running playbooks (for example, large rolling updates); CI should use OIDC instead of SSO.

An error occurred (AccessDenied) when calling the AssumeRole operation: User: arn:aws:sts::…:assumed-role/AWSReservedSSO_… is not authorized to perform: sts:AssumeRole on resource: arn:aws:iam::…:role/ansible-deployer

Cause: the target role's trust policy does not trust the caller, or the caller lacks sts:AssumeRole permission.

aws iam get-role --role-name ansible-deployer --query Role.AssumeRolePolicyDocument --profile lab

Fix: Add the permission-set role ARN to the Principal in the trust policy (note that SSO role names carry a random suffix, so you can use aws:PrincipalArn a condition with a wildcard).

botocore.exceptions.NoRegionError: You must specify a region.

Cause: No region is set in module parameters, environment variables, or the profile.

Fix:module_defaults Set it in region, or write it in the profile region = ca-central-1.

Command-line exercises
1. Run one ad-hoc command that uses the lab profile to print the current AWS account ID.
ansible localhost -m amazon.aws.aws_caller_info -a "profile=lab region=ca-central-1" | grep '"account"'
2. Upgrade boto3/botocore to a version that meets amazon.aws 12.x, and verify it.
pipx inject --force ansible "boto3>=1.38.23" "botocore>=1.38.23"
"$(pipx environment --value PIPX_LOCAL_VENVS)/ansible/bin/python" -c "import boto3;print(boto3.__version__)"
Scenario analysis
On the same control node,aws sts get-caller-identity --profile lab succeeds, but the ec2_instance_info task in the playbook fails with InvalidClientTokenId. What are the likely causes, and in what order should you investigate them?

The AWS CLI explicitly uses --profile lab, but the module in the playbook does not pass a profile, so boto3 falls back to the default credential chain and hits the expired static key in environment variables (or ~/.aws/credentials the default section). Investigation: env | grep ^AWS_ → aws configure list (without profile) → add aws_caller_info to the playbook, print the arn → use module_defaults to pass the profile uniformly.

Verified teaching videos

▶
Ansible in 100 Seconds — Fireship
English · about 2 min · quick review of Ansible's push model and idempotency (does not cover AWS)
▶
What is Ansible | Ansible Playbook explained | Ansible Tutorial for Beginners — TechWorld with Nana
English · concept review; for how cloud modules “run locally on the control node”, this lesson is the reference

No verified video on “amazon.aws authentication / SSO profile” was found; please use the storyboard script below.

Official documentation

Video storyboard script (about 90 seconds)

This courseware cannot directly generate video or MP3; a storyboard and narration script are provided, which can be handed to a video tool to generate.

Shot 1 · 0–15s
Visual: in the playbook, hosts: localhost highlighted; an arrow points from a laptop to a cloud icon, not to EC2.
Narration: AWS modules do not run on EC2; they run locally on the control node and call the AWS API directly with boto3.
Shot 2 · 15–45s
Visual: seven steps light up in turn: parameters, environment variables, SSO and role, credentials file, config, container, instance metadata. On the second step there is a red old key.
Narration: boto3 looks for credentials in a fixed order, and the first one found takes effect. An old key left in environment variables will quietly override the profile you set.
Shot 3 · 45–70s
Visual: browser device authorization → token cache → permission-set role → assume role → 1-hour temporary credentials.
Narration: we recommend signing in with IAM Identity Center and then assuming the deployment role. No long-term keys are involved at any point, and credentials refresh automatically when they expire.
Shot 4 · 70–90s
Visual: terminal output aws_caller_info showing the account and arn, next to a green-check assert.
Narration: the first step of every cloud playbook is to confirm who you are and which account you are in.
or score ≥ 70% on the quiz

Module 2 · aws_ec2 dynamic inventory

06:00 – 13:00 · The inventory is no longer a hand-written IP list; it is one DescribeInstances call plus a set of tag rules
7 minamazon.aws.aws_ec2The file name must end with aws_ec2.yml★★★★★
Learning objectives
  • Write a working lab.aws_ec2.yml: regions, filters, include_filters/exclude_filters, hostnames, compose, keyed_groups, groups.
  • Understand In SSM scenarios, the host name must be the instance ID (ansible_host also must be the instance ID), while SSH scenarios usually use a private IP or DNS name.
  • Enable inventory caching and know when to --flush-cache; use ansible-inventory --graph/--host to check the results.
Prerequisites: Static inventory and group_vars from lesson 1; the previous lesson's azure_rm inventory. Importance:★★★★★

What: the aws_ec2 inventory plugin

amazon.aws.aws_ec2 is an inventory plugin: when Ansible parses an inventory source, if the file name ends with aws_ec2.yml/aws_ec2.yaml and its content contains plugin: amazon.aws.aws_ec2, the plugin uses boto3 to call ec2:DescribeInstances (per regions region, with automatic pagination), turns each instance into a host, turns instance attributes into host variables (instance_id,private_ip_address,tags,placement,instance_type…), and puts all hosts into aws_ec2 a group. The plugin implements the Constructable interface, so it supports compose,keyed_groups,groups these three kinds of “post-processing”.

Why: why dynamic inventory is required in the cloud

EC2 private IPs change when instances are replaced, and Auto Scaling adds and removes instances at any time. A hand-written inventory will inevitably go stale; by contrast, describing tags to describe “which hosts belong to which role” keeps the inventory always in sync with the real state. This is also the standard division of labor: “infrastructure is created and tagged by Terraform/Ansible → configuration is grouped by tag with Ansible”.

How: key options (12.x)

OptionPurposeDefault / notes
regionsWhich regions to queryDefault [] = all available regions (slow! always set this explicitly)
filtersEC2 API filters (server-side filtering)Default {},does not automatically exclude stopped instances; it is recommended to write instance-state-name: running
include_filters / exclude_filtersadditional OR conditions / exclusion conditionsExclusions take priority
hostnamesList host name sources in priority order; use the first non-empty valueCan be instance-id,tag:Name,private-ip-address,dns-name etc.; the dictionary form supports name/prefix/separator
composeGenerate host variables with Jinja2SSM: ansible_host: instance_id
keyed_groupsAutomatically create groups based on variable valuesIllegal characters in group names (such as -) are replaced with _
groupsPut hosts into a group based on a Jinja2 conditionAdded when the condition is true
cache familyCache API resultscache_plugin Default memory; cache_timeout default 3600 seconds
use_ssm_inventoryMerge SSM Inventory data into host variablesDefault false
iam_role_arn (alias assume_role_arn)Query after assuming a role (cross-account)—
hostvars_prefixPrefix variables sourced from AWSavoid name clashes with your own variables
strictRaise an error instead of skipping when compose/keyed_groups failsDefault false; enable when debugging

When: which host name to choose

  • SSM connection (this lesson): hostnames: [instance-id] + compose: {ansible_host: instance_id}. The aws_ssm plugin uses ansible_host (or ansible_aws_ssm_instance_id) as the session target.
  • SSH via a bastion host: private-ip-address, combined with ansible_ssh_common_args: -J bastion.
  • Readability: you can use tag:Name as the host name, but you must then compose ansible_host, and make sure the Name tag is unique (otherwise instances with the same name keep only one, unless allow_duplicated_hosts).

Comparison with similar technology

aws_ec2 pluginlegacy ec2.py scriptazure_rm plugin (previous lesson)
FormatYAML config + in-collection pluginPython script + ini (deprecated)YAML config
Groupingkeyed_groups/groups/composeFixed tag_xxx groupsSame Constructable mechanism
CachingAnsible cache pluginScript's own file cacheAnsible cache plugin
Common misconceptions① “The file name can be anything”—if the name does not end with aws_ec2.yml , the plugin's file check verify_file() simply rejects it; the inventory is empty and only one warning appears. ② “By default it only returns running instances”—by default the filters is empty, and stopped instances also show up and connections time out. ③ “If you write tags.Role in keyed_groups and the tag is absent, it raises an error”. By default strict: false it is silently skipped, so when a group is empty, first check the tag's spelling and case.

Architecture diagram: from DescribeInstances to the inventory graph

lab.aws_ec2.ymlregions / filtershostnames / composekeyed_groups / cache Cache hit?jsonfile: ~/.cache/…Miss / expired / --flush-cache→ call API ec2:DescribeInstancesFilters=[state=running,tag:Project=ansible-lab]Paginate per region Hosts + hostvarsi-0a1b… → tags,private_ip_address,placement … Constructable post-processing (order: compose → groups → keyed_groups) compose: ansible_host = instance_id; app_env = tags.Env keyed_groups: role_web, env_lab, az_ca_central_1a, type_t3_micro groups: ssm_managed (condition expression is true) IAM permissionsec2:DescribeInstancesec2:DescribeRegions (when regions is empty)ssm:* (use_ssm_inventory)
Figure 2-1: inventory plugin = cache + one filtered DescribeInstances call + Constructable rules

How tags become groups

Instance i-0a1b2c3d4e5f60001 tags.Name = myapp-1tags.Role = webtags.Env = labplacement.availability_zone = ca-central-1ainstance_type = t3.micro key: tags.Role, prefix: role → role_web key: tags.Env, prefix: env → env_lab key: placement.availability_zone → az_ca_central_1a playbookhosts: role_web:&env_labgroup_vars/role_web.yml takes effect automatically
Figure 2-2: keyed_groups makes “tagging” directly equal “grouping”; group_vars files take effect by group name

Interactive simulator: adjust the inventory config and watch it in real time ansible-inventory --graph

On the left are the 5 instances in ca-central-1 in the account (including one that is stopped, one that belongs to another project, and one without a Role tag). Check / switch the configuration on the right, click “Generate inventory”, and the simulator runs in the plugin's real processing order: (1) server-side filters → (2) exclude_filters → (3) hostnames → (4) compose → (5) groups → (6) keyed_groups, and shows the corresponding API requests and results in the terminal.

Instances in the account
lab.aws_ec2.yml config
hostnames:

Core commands and parameters

CommandPurposeKey parameters
ansible-inventory -i FILE --graphShow groups and hosts as a tree--vars Also show variables
ansible-inventory -i FILE --host HOSTAll variables for a given hostCheck compose results
ansible-inventory -i FILE --list --yamlFull output--output file
ansible-inventory … --flush-cacheClear the inventory cache and query againUse after creating/deleting instances
ansible-doc -t inventory amazon.aws.aws_ec2View all options offlineBased on the version you have installed
---
plugin: amazon.aws.aws_ec2
profile: lab
regions:
  - ca-central-1
filters:
  instance-state-name: running
  tag:Project: ansible-lab
hostnames:
  - instance-id
compose:
  ansible_host: instance_id
  private_ip: private_ip_address
  app_env: tags.Env | default('lab')
keyed_groups:
  - key: tags.Role
    prefix: role
  - key: tags.Env
    prefix: env
  - key: placement.availability_zone
    prefix: az
  - key: instance_type
    prefix: type
groups:
  ssm_managed: "tags.Access | default('') == 'ssm'"
cache: true
cache_plugin: ansible.builtin.jsonfile
cache_connection: ~/.cache/ansible/aws_ec2
cache_timeout: 300
cd ~/ansible-lab
ansible-inventory -i inventories/aws/lab.aws_ec2.yml --graph
ansible-inventory -i inventories/aws/lab.aws_ec2.yml --host i-0a1b2c3d4e5f60001 | head -30
@all:
  |--@ungrouped:
  |--@aws_ec2:
  |  |--i-0a1b2c3d4e5f60001
  |  |--i-0a1b2c3d4e5f60002
  |--@role_web:
  |  |--i-0a1b2c3d4e5f60001
  |  |--i-0a1b2c3d4e5f60002
  |--@env_lab:
  |  |--i-0a1b2c3d4e5f60001
  |  |--i-0a1b2c3d4e5f60002
  |--@az_ca_central_1a:
  |  |--i-0a1b2c3d4e5f60001
  |  |--i-0a1b2c3d4e5f60002
  |--@type_t3_micro:
  |  |--i-0a1b2c3d4e5f60001
  |  |--i-0a1b2c3d4e5f60002
  |--@ssm_managed:
  |  |--i-0a1b2c3d4e5f60001
  |  |--i-0a1b2c3d4e5f60002
{
    "ansible_host": "i-0a1b2c3d4e5f60001",
    "app_env": "lab",
    "instance_id": "i-0a1b2c3d4e5f60001",
    "instance_type": "t3.micro",
    "placement": { "availability_zone": "ca-central-1a", ... },
    "private_ip": "10.40.1.23",
    "tags": { "Access": "ssm", "Env": "lab", "Name": "myapp-1", "Project": "ansible-lab", "Role": "web" },
    ...

How to verify:--graph in the output, each group's members are as expected, and in --host the output of ansible_host is an instance ID. Common error: Running this before creating instances in M3 gives an inventory with only @ungrouped — an empty inventory. This is normal. With caching enabled, new instances may not appear for 5 minutes; add --flush-cache. Production use: Replace profile with iam_role_arn to work across accounts. For multiple regions, in regions list the regions and add key: placement.region groups.

Put the SSM connection variables in group variables (used in M4)

---
ansible_connection: amazon.aws.aws_ssm
ansible_aws_ssm_region: "{{ aws_region }}"
ansible_aws_ssm_profile: "{{ aws_profile }}"
ansible_aws_ssm_bucket_name: "{{ lab_prefix }}-ssm-{{ aws_account_id }}-{{ aws_region }}"

aws_account_id In M3, write group_vars/all/aws.yml. Note that the group_vars directory must match the inventory file at the same level (inventories/aws/), so that it is loaded automatically.

Lab 2: write and verify the dynamic inventory (about 5 min)

Create the inventory file: copy the configuration from the “Commands” page lab.aws_ec2.yml save it to inventories/aws/.
Verify that the plugin “claims” the file (there are no instances yet, so an empty inventory is normal):
ansible-inventory -i inventories/aws/lab.aws_ec2.yml --graph -vvv 2>&1 | grep -E "Parsed|declined|aws_ec2" | head
Parsed /home/azureuser/ansible-lab/inventories/aws/lab.aws_ec2.yml inventory source with amazon.aws.aws_ec2 plugin
Try the file name rule:
cp inventories/aws/lab.aws_ec2.yml /tmp/lab-inventory.yml
ansible-inventory -i /tmp/lab-inventory.yml --graph -vvv 2>&1 | grep -iE "declined|did not pass|Unable to parse" | head -3
rm /tmp/lab-inventory.yml
amazon.aws.aws_ec2 declined parsing /tmp/lab-inventory.yml as it did not pass its verify_file() method
[WARNING]: Unable to parse /tmp/lab-inventory.yml as an inventory source
(come back after M3) check groups and variables:
ansible-inventory -i inventories/aws --graph --flush-cache
ansible-inventory -i inventories/aws --host "$(ansible-inventory -i inventories/aws --list | jq -r '.role_web.hosts[0]')" | jq '{ansible_host, private_ip, tags}'
ansible role_web -i inventories/aws --list-hosts
{
  "ansible_host": "i-0a1b2c3d4e5f60001",
  "private_ip": "10.40.1.23",
  "tags": { "Access": "ssm", "Env": "lab", "Name": "myapp-1", "Project": "ansible-lab", "Role": "web" }
}
  hosts (2):
    i-0a1b2c3d4e5f60001
    i-0a1b2c3d4e5f60002
Observe caching:
ls -l ~/.cache/ansible/aws_ec2/
time ansible-inventory -i inventories/aws --graph >/dev/null      # cache hit, noticeably faster
time ansible-inventory -i inventories/aws --graph --flush-cache >/dev/null
Cleanup: this lab does not create cloud resources; to clear the cache if needed: rm -rf ~/.cache/ansible/aws_ec2.

Case 1: unified inventory across multiple accounts and regions

Problem: 3 accounts × 2 regions; the ops team wants one command to show all web hosts. Approach: One per account *.aws_ec2.yml (each configured with iam_role_arn), placed in the same inventory directory; keyed_groups add key: owner_id (account) and placement.region. Configuration:ansible-inventory -i inventories/prod/ --graph All sources in the directory are merged automatically. Limitations: Each run must assume 3 roles and make 6 API calls, so enable caching and set an appropriate cache_timeout.

Case 2: rolling configuration for Auto Scaling groups

Problem: ASG instances are constantly replaced, and only instances that “passed health checks” should be configured. Approach:filters Add tag:aws:autoscaling:groupName,keyed_groups group by ASG name; then use serial to batch. Limitations: The first-time configuration of new instances is best placed in user_data / AMI (or use EDA to listen for ASG lifecycle events, lesson 5); Ansible handles subsequent changes.

Case 3: inventory sync in AWX/AAP

Problem: Syncing the inventory before every AWX job is too slow. Approach: Use the “Amazon EC2” inventory source in AWX (it is also backed by the aws_ec2 plugin), write filters/keyed_groups in the source variables, and set “Update on launch” plus a cache timeout. Limitations: AWX inventory syncs run in an execution-environment container, and credentials come from AWX credential types rather than a local profile (lesson 5).

Common errors and fixes

[WARNING]: Unable to parse …/inventory.yml as an inventory source / aws_ec2 declined parsing … did not pass its verify_file() method

Cause: The file name does not end with aws_ec2.yml/aws_ec2.yaml , or plugin: is misspelled.

ansible-inventory -i FILE --graph -vvv 2>&1 | grep -i aws_ec2

Fix: Rename it to xxx.aws_ec2.yml; make sure ansible.cfg 's [inventory] enable_plugins (if set) includes amazon.aws.aws_ec2.

The inventory has only @all and @ungrouped, with no hosts

Cause: The region is wrong, or the filters are too strict (tag case mismatch, e.g. project vs Project), instances are not in the running state, the credentials point to another account, or the cache is stale.

aws ec2 describe-instances --profile lab --region ca-central-1 \
  --filters Name=tag:Project,Values=ansible-lab Name=instance-state-name,Values=running \
  --query 'Reservations[].Instances[].[InstanceId,State.Name,Tags]'
ansible-inventory -i inventories/aws --graph --flush-cache

Fix: If the CLI finds the instances but the inventory does not, it is most likely a profile/region or cache problem; if the CLI also finds nothing, it is a filter or tag problem. For the full procedure, see the M7 troubleshooting tree.

An error occurred (UnauthorizedOperation) when calling the DescribeInstances operation: You are not authorized to perform this operation.

Cause: The identity used by the inventory plugin lacks ec2:DescribeInstances. Note that the inventory plugin does not read the playbook's module_defaults, so the profile must be set in the inventory file or supplied through environment variables.

Fix: In lab.aws_ec2.yml write profile:; grant the role read-only permissions (such as AmazonEC2ReadOnlyAccess).

keyed_groups defines a role group, but the role_web group does not exist

Cause: Instances have no Role tag, or the value differs; strict: false in that case the error is silently ignored.

ansible-inventory -i inventories/aws --host i-xxxx | jq .tags

Fix: Temporarily set strict: true to see the real error; standardize tag conventions (case, values).

Only one of two instances with the same Name appears

Cause:hostnames: [tag:Name] When that setting is used, duplicate host names overwrite one another, and the later host replaces the earlier one.

Fix: Use instance-id; or use the dictionary form {name: tag:Name, prefix: instance-id, separator: "_"} to compose a unique name; or enable allow_duplicated_hosts.

Command-line exercises
1. After clearing the cache, list the hosts that belong to both the env_lab and role_web groups.
ansible-inventory -i inventories/aws --graph --flush-cache >/dev/null
ansible 'role_web:&env_lab' -i inventories/aws --list-hosts
2. View all options supported by the aws_ec2 plugin installed on this machine.
ansible-doc -t inventory amazon.aws.aws_ec2 | less
Scenario analysis
The team set hostnames to private-ip-address, and enabled the aws_ssm connection in group_vars, but all hosts report “target not connected”. Why, and how should it be fixed?

The aws_ssm plugin treats ansible_host as the SSM session target, but the SSM StartSession target must be an instance ID (or managed node ID); a private IP is not a valid target. Fix: hostnames: [instance-id], or keep a readable host name but compose: {ansible_host: instance_id}.

Verified teaching videos

▶

Official documentation

Video storyboard script (about 80 seconds)

This courseware cannot directly generate video/MP3; a storyboard and narration script are provided.

Shot 1 · 0–15s
Visual: IP addresses in a hand-written hosts file are crossed out one by one.
Narration: cloud IPs change and instances come and go, so a hand-written inventory is bound to go stale.
Shot 2 · 15–40s
Visual: lab.aws_ec2.yml → DescribeInstances with filters → only two of the five instances light up.
Narration: the aws_ec2 plugin calls DescribeInstances each time, filtering server-side by state and tags. Remember to explicitly request only running instances.
Shot 3 · 40–65s
Visual: instance tag cards fly into the role_web, env_lab and az groups.
Narration: keyed_groups turns tags directly into groups, and group_vars takes effect automatically.
Shot 4 · 65–80s
Visual: the hostnames dropdown selects instance-id, with SSM written beside it.
Narration: when connecting via SSM, the host address must be the instance ID.
or score ≥ 70% on the quiz

Module 3 · creating AWS resources with Ansible

13:00 – 22:00 · One provision.yml: VPC → IGW → subnet → route table → security group → IAM role/instance profile → S3 bucket → 2 EC2 instances
9 minamazon.aws modulesIncurs charges★★★★☆
Learning objectives
  • Use amazon.aws.ec2_vpc_net,ec2_vpc_igw,ec2_vpc_subnet,ec2_vpc_route_table,ec2_security_group,iam_role,iam_instance_profile,s3_bucket,ec2_instance to build a minimal yet secure environment.
  • Understand what makes cloud modules idempotent: name/tag lookup + comparing differences, so tags and names are the “primary keys” of these resources.
  • Know the trade-offs between Ansible resource orchestration and Terraform, plus cloud details such as IAM eventual consistency, IMDSv2, and public IPv4 billing.
Prerequisites: Basic VPC knowledge (CIDR, route tables, IGW, security groups). Importance:★★★★☆

What: the resources this lesson creates

ResourceModule (FQCN)“Primary key” (basis for idempotency)Notes
VPC 10.40.0.0/16amazon.aws.ec2_vpc_netname + cidr_blockSame name and same CIDR are treated as the same VPC
Internet gatewayamazon.aws.ec2_vpc_igwvpc_idAt most one per VPC
Public subnet 10.40.1.0/24amazon.aws.ec2_vpc_subnetvpc_id + cidrmap_public: true
Route tableamazon.aws.ec2_vpc_route_tablevpc_id + tags (lookup: tag, default)0.0.0.0/0 → IGW
Security groupamazon.aws.ec2_security_groupname + vpc_idNo inbound rules, outbound allows only 80/443
IAM roleamazon.aws.iam_rolenameTrust ec2.amazonaws.com, attach AmazonSSMManagedInstanceCore
Instance profileamazon.aws.iam_instance_profilenameEC2 can only use a role through an instance profile
S3 bucket (for SSM transfers)amazon.aws.s3_bucket + community.aws.s3_lifecyclename (globally unique)Block public access, SSE, no versioning, 1-day expiration
EC2 × 2amazon.aws.ec2_instancefilters (this lesson uses the Name + Project tags)Ubuntu 24.04, t3.micro, IMDSv2, no key pair

Why: why use Ansible to create resources (and when not to)

For lab environments, throwaway environments, or pipelines that “create a resource and configure it right away,” a single playbook that both creates and configures is very direct and needs no extra state file. But Ansible has no state: it does not know which resources were created earlier and later removed, so deletion must be written explicitly state: absent (the destroy.yml in M8). For long-lived, multi-person infrastructure, use Terraform (see the Terraform course), while Ansible handles configuration; this is the division of labor between the two courses.

How: idempotency mechanics of cloud modules

  1. The module first uses Describe/List APIs to look up existing resources by their “primary key” (name, CIDR, tags, filters).
  2. Not found → Create; found → compare desired and actual attributes (for example security group rules and tags), call Modify/Authorize/Revoke/Tag only when they differ, and return changed: true.
  3. Most modules support --check check mode (Describe only, no changes),--diff and support for diff varies by module.
  4. Tags default to purge_tags: true: tags not in tags will be removed —tags that others added manually get wiped, set this to false when you need to keep them.

When: a few cloud details you must know

  • IAM eventual consistency: a newly created instance profile can take a few to a dozen-plus seconds to be recognized by EC2, so a launch may RunInstances report Invalid IAM Instance Profile name. Use retries/until to retry.
  • IMDSv2: metadata_options.http_tokens: required Enforces session tokens to prevent SSRF from stealing instance credentials; the SSM Agent supports IMDSv2.
  • Do not hardcode AMI IDs: use the public SSM parameter /aws/service/canonical/ubuntu/server/24.04/stable/current/amd64/hvm/ebs-gp3/ami-id to resolve the latest Ubuntu 24.04 AMI (the official Ubuntu AMI ships with the SSM Agent snap preinstalled).
  • Public IPv4 billing: since February 2024 AWS charges hourly for all public IPv4 addresses. To avoid NAT gateway and VPC endpoint costs, this lesson gives instances a public IP but opens no inbound ports; for production, a private subnet with VPC endpoints is recommended (see the M4 production case).
  • ec2_instance 's network parameter is deprecated (to be removed in releases after 2026-12-01); use network_interfaces (added in 8.2.0).

Comparison with similar tools

Ansible amazon.awsTerraform AWS providerCloudFormation
StateNone (looked up on each run)state fileStack (AWS-managed)
Delete resourcesexplicit state: absentRemoving it from the code is enough for plan to show a deletionRemoving it from the template is enough
Dependency ordertask order (manual)dependency graph (automatic parallelism)dependency graph
Best forcreate-then-configure, temporary environmentslong-lived infrastructureAWS-only, needs stack-level rollback
Common misconceptions① “Deleting a task from the playbook removes the resource”: Ansible has no state, so the resource keeps running and billing. ② “Setting a name on ec2_instance guarantees idempotency”: the name is just a tag; if filters do not match an existing instance (for example after changing the subnet), another instance is created. This lesson writes it explicitly filters. ③ “A security group without rules_egress has no outbound”: when omitted, the default allow-all outbound is kept; when specified, the default becomes purge_rules_egress: true, so only the rules you write are kept.

Architecture diagram: this lesson’s AWS lab environment

Region ca-central-1 · VPC ansible-lab-vpc 10.40.0.0/16 Public subnet 10.40.1.0/24 (ca-central-1a) myapp-1t3.micro · IMDSv2SSM Agent myapp-2t3.micro · IMDSv2SSM Agent Security group ansible-lab-sgInbound: none · Outbound: TCP 443, 80 Route table10.40.0.0/16 local0.0.0.0/0 → igw Internet Gatewayansible-lab-igw IAM role ansible-lab-ssm-role → instance profile ansible-lab-ssm-profileManaged policy AmazonSSMManagedInstanceCore (SSM Agent registration, session channel) SSM servicessm / ssmmessagesec2messages S3 bucketansible-lab-ssm-<account>-ca-central-1 Control nodeansible + boto3Outbound HTTPS only Control node → AWS API / SSM / S3 (all outbound HTTPS 443)
Figure 3-1: instances have no inbound ports; all traffic is outbound HTTPS initiated by the instances and the control node toward AWS services

Dependency order: why tasks must be written in this sequence

VPC IGW Subnet Route table Security group IAM role Instance profile S3 bucket ec2_instance × 2Needs subnet, security group, and instance profile The S3 bucket is not a dependency of EC2, but the SSM connection in M4 needs it; deletion runs in the exact reverse order (M8)
Figure 3-2: Ansible runs tasks in order and you guarantee dependencies yourself; Terraform derives the dependency graph automatically

Animation: which AWS APIs provision.yml calls, task by task

Click “Play” to watch the first run (create); check “Second run” and play again to see idempotency: the modules only call Describe-type APIs, all of which return ok.

Core modules and parameters

ModuleKey parametersCommon keys in return values
ec2_vpc_netname,cidr_block,tags,dns_hostnamesvpc.id
ec2_vpc_igwvpc_id,tagsgateway_id
ec2_vpc_subnetvpc_id,cidr,az,map_publicsubnet.id
ec2_vpc_route_tablevpc_id,subnets,routes,tagsroute_table.id
ec2_security_groupname,description,vpc_id,rules,rules_egressgroup_id
iam_roleassume_role_policy_document,managed_policies,create_instance_profileiam_role.arn
iam_instance_profilename,roleiam_instance_profile.arn
s3_bucketname,public_access,encryption,versioningname
ec2_instancename,image_id,instance_type,vpc_subnet_id,security_group,network_interfaces,iam_instance_profile,metadata_options,filters,waitinstance_ids,instances[].private_ip_address
{
  "Version": "2012-10-17",
  "Statement": [
    { "Effect": "Allow", "Principal": { "Service": "ec2.amazonaws.com" }, "Action": "sts:AssumeRole" }
  ]
}
---
- name: Create AWS lab environment
  hosts: localhost
  connection: local
  gather_facts: false
  module_defaults:
    group/amazon.aws.aws:
      profile: "{{ aws_profile }}"
      region: "{{ aws_region }}"
  vars:
    vpc_cidr: 10.40.0.0/16
    subnet_cidr: 10.40.1.0/24
    lab_az: "{{ aws_region }}a"
    instance_names: [myapp-1, myapp-2]
    instance_type: t3.micro
    ami_param: /aws/service/canonical/ubuntu/server/24.04/stable/current/amd64/hvm/ebs-gp3/ami-id
  tasks:
    - name: Confirm identity
      amazon.aws.aws_caller_info:
      register: me

    - name: Record account ID for inventory and SSM use
      ansible.builtin.lineinfile:
        path: "{{ playbook_dir }}/../../inventories/aws/group_vars/all/aws.yml"
        regexp: '^aws_account_id:'
        line: 'aws_account_id: "{{ me.account }}"'

    - name: VPC
      amazon.aws.ec2_vpc_net:
        name: "{{ lab_prefix }}-vpc"
        cidr_block: "{{ vpc_cidr }}"
        dns_hostnames: true
        dns_support: true
        tags: "{{ lab_tags }}"
      register: vpc

    - name: Internet gateway
      amazon.aws.ec2_vpc_igw:
        vpc_id: "{{ vpc.vpc.id }}"
        tags: "{{ lab_tags | combine({'Name': lab_prefix ~ '-igw'}) }}"
      register: igw

    - name: Public subnet
      amazon.aws.ec2_vpc_subnet:
        vpc_id: "{{ vpc.vpc.id }}"
        cidr: "{{ subnet_cidr }}"
        az: "{{ lab_az }}"
        map_public: true
        tags: "{{ lab_tags | combine({'Name': lab_prefix ~ '-public-a'}) }}"
      register: subnet

    - name: Route table
      amazon.aws.ec2_vpc_route_table:
        vpc_id: "{{ vpc.vpc.id }}"
        subnets: ["{{ subnet.subnet.id }}"]
        routes:
          - dest: 0.0.0.0/0
            gateway_id: "{{ igw.gateway_id }}"
        tags: "{{ lab_tags | combine({'Name': lab_prefix ~ '-public-rt'}) }}"

    - name: Security group (no inbound, outbound 80/443 only)
      amazon.aws.ec2_security_group:
        name: "{{ lab_prefix }}-sg"
        description: "ansible-lab: no inbound, SSM via outbound 443"
        vpc_id: "{{ vpc.vpc.id }}"
        rules: []
        rules_egress:
          - { proto: tcp, ports: [443], cidr_ip: 0.0.0.0/0, rule_desc: "SSM, S3, HTTPS" }
          - { proto: tcp, ports: [80], cidr_ip: 0.0.0.0/0, rule_desc: "apt mirrors" }
        tags: "{{ lab_tags }}"
      register: sg

    - name: Instance IAM role
      amazon.aws.iam_role:
        name: "{{ lab_prefix }}-ssm-role"
        assume_role_policy_document: "{{ lookup('ansible.builtin.file', playbook_dir ~ '/../../files/ec2-trust.json') }}"
        managed_policies:
          - arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore
        create_instance_profile: false
        tags: "{{ lab_tags }}"

    - name: Instance profile
      amazon.aws.iam_instance_profile:
        name: "{{ lab_prefix }}-ssm-profile"
        role: "{{ lab_prefix }}-ssm-role"

    - name: S3 bucket for SSM file transfer
      amazon.aws.s3_bucket:
        name: "{{ lab_prefix }}-ssm-{{ me.account }}-{{ aws_region }}"
        versioning: false
        encryption: AES256
        public_access:
          block_public_acls: true
          ignore_public_acls: true
          block_public_policy: true
          restrict_public_buckets: true
        tags: "{{ lab_tags }}"

    - name: Automatically delete leftover module files after 1 day
      community.aws.s3_lifecycle:
        profile: "{{ aws_profile }}"
        region: "{{ aws_region }}"
        name: "{{ lab_prefix }}-ssm-{{ me.account }}-{{ aws_region }}"
        rule_id: expire-ansible-staging
        expiration_days: 1
        status: enabled

    - name: EC2 instance
      amazon.aws.ec2_instance:
        name: "{{ item }}"
        image_id: "{{ lookup('amazon.aws.ssm_parameter', ami_param, profile=aws_profile, region=aws_region) }}"
        instance_type: "{{ instance_type }}"
        vpc_subnet_id: "{{ subnet.subnet.id }}"
        security_group: "{{ sg.group_id }}"
        network_interfaces:
          - assign_public_ip: true
        iam_instance_profile: "{{ lab_prefix }}-ssm-profile"
        metadata_options:
          http_endpoint: enabled
          http_tokens: required
        filters:
          "tag:Name": "{{ item }}"
          "tag:Project": "{{ lab_tags.Project }}"
          instance-state-name: [pending, running, stopping, stopped]
        tags: "{{ lab_tags | combine({'Role': 'web', 'Env': 'lab', 'Access': 'ssm'}) }}"
        state: running
        wait: true
      loop: "{{ instance_names }}"
      register: ec2
      retries: 6
      delay: 10
      until: ec2 is succeeded

    - name: Summary
      ansible.builtin.debug:
        msg: "{{ ec2.results | map(attribute='instances') | flatten | map(attribute='instance_id') | list }}"
cd ~/ansible-lab
ansible-playbook -i inventories/aws playbooks/aws/provision.yml --check     # Dry run first (some modules depend on return values from earlier tasks; in check mode they may be skipped or report missing values, which is normal)
ansible-playbook -i inventories/aws playbooks/aws/provision.yml
TASK [VPC] *********************************************************************
changed: [localhost]
TASK [Security group (no inbound, outbound 80/443 only)] *****************************************
changed: [localhost]
TASK [Instance profile] **************************************************************
changed: [localhost]
TASK [EC2 instance] ******************************************************************
FAILED - RETRYING: [localhost]: EC2 instance (6 retries left).
changed: [localhost] => (item=myapp-1)
changed: [localhost] => (item=myapp-2)
TASK [Summary] **********************************************************************
ok: [localhost] => { "msg": ["i-0a1b2c3d4e5f60001", "i-0a1b2c3d4e5f60002"] }
PLAY RECAP *********************************************************************
localhost : ok=14  changed=12  unreachable=0  failed=0  skipped=0  rescued=0  ignored=0

How to verify: Running it again should show changed=0 (lineinfile also unchanged); aws ec2 describe-instances --filters Name=tag:Project,Values=ansible-lab You should see 2 instances running. Common error: Seeing FAILED - RETRYING once usually means the IAM instance profile has not propagated yet; success on retry is normal. Production use: Move vars to group_vars, use --extra-vars env=staging to reuse the same playbook to create multiple environments.

Lab 3: Create the lab environment and verify idempotency (about 8 minutes; billing starts)

Save the file: files/ec2-trust.json with playbooks/aws/provision.yml (see the “Commands” tab).Cost: billing starts at this step, about 0.04 USD per hour. For the required permissions, see Module 0.
Run it and record the time:
cd ~/ansible-lab
time ansible-playbook -i inventories/aws playbooks/aws/provision.yml
grep aws_account_id inventories/aws/group_vars/all/aws.yml
localhost : ok=14  changed=12 …
real    2m31.4s
aws_account_id: "111122223333"
Cross-check with the CLI:
aws ec2 describe-instances --profile lab --region ca-central-1 \
  --filters Name=tag:Project,Values=ansible-lab Name=instance-state-name,Values=running \
  --query 'Reservations[].Instances[].[InstanceId,PrivateIpAddress,MetadataOptions.HttpTokens,IamInstanceProfile.Arn]' --output table
aws ec2 describe-security-groups --profile lab --region ca-central-1 \
  --filters Name=group-name,Values=ansible-lab-sg --query 'SecurityGroups[0].[IpPermissions,IpPermissionsEgress[].FromPort]'
---------------------------------------------------------------------------------------------------
|                                        DescribeInstances                                        |
+----------------------+------------+-----------+-------------------------------------------------+
|  i-0a1b2c3d4e5f60001 | 10.40.1.23 | required  | arn:aws:iam::111122223333:instance-profile/ansible-lab-ssm-profile |
|  i-0a1b2c3d4e5f60002 | 10.40.1.57 | required  | arn:aws:iam::111122223333:instance-profile/ansible-lab-ssm-profile |
+----------------------+------------+-----------+-------------------------------------------------+
[
    [],
    [ 443, 80 ]
]

Inbound rules are empty [], and IMDSv2 is required.

Verify idempotency:
ansible-playbook -i inventories/aws playbooks/aws/provision.yml | tail -2
PLAY RECAP *********************************************************************
localhost : ok=14  changed=0  unreachable=0  failed=0  skipped=0  rescued=0  ignored=0
Back to step 4 of the M2 lab, use --flush-cache to view the dynamic inventory groups.
Cleanup: keep the resources for use in M4–M6. If you are not continuing today, run the M8 destroy.yml.

Case 1: temporary test environments “created on demand, destroyed on schedule”

Problem: Each feature branch needs its own environment, and they are often forgotten after use. Approach: provision.yml uses env_name as the prefix and apply the ExpiresAt tag; a nightly job uses ec2_instance_info to find expired tags and call destroy. Limitation: IAM resources are global, so names must carry an environment prefix to avoid conflicts between branches.

Case 2: Terraform builds the network; Ansible builds and configures the hosts

Problem: The network team manages VPCs with Terraform, and the application team wants to start and stop instances with Ansible. Approach: Ansible uses ec2_vpc_subnet_info to look up the Terraform-created subnets by tag (read-only), then create the instances. Configuration:filters: {"tag:Tier": "app"}. Limitation: Do not use Ansible to modify Terraform-managed resources, or the next terraform plan will show drift.

Case 3: purge_tags removed the cost allocation tags

Problem: Finance added the CostCenter tag in the console; it disappeared after the next playbook run. Cause:purge_tags purge_tags defaults to true. Approach: Put company-wide tags into lab_tags, or set purge_tags: false; better still, manage them centrally with AWS Organizations tag policies.

Common errors and fixes

An error occurred (InvalidParameterValue) when calling the RunInstances operation: Value (ansible-lab-ssm-profile) for parameter iamInstanceProfile.name is invalid. Invalid IAM Instance Profile name

Cause: IAM eventual consistency: the instance profile was just created and EC2 cannot see it yet.

Fix: Keep retries/until; or after creating the profile, add ansible.builtin.pause: seconds=10.

An error occurred (UnauthorizedOperation) when calling the RunInstances operation: You are not authorized to perform this operation. User: … is not authorized to perform: iam:PassRole on resource: …ansible-lab-ssm-role

Cause: Passing the role to EC2 requires the iam:PassRole permission. The error may include an encoded Encoded authorization failure message message.

aws sts decode-authorization-message --encoded-message "<encoded-string>" --profile lab --query DecodedMessage --output text | jq .

Fix: Add iam:PassRole (scoped to the role via Resource, with condition iam:PassedToService = ec2.amazonaws.com).

BucketAlreadyExists: The requested bucket name is not available.

Cause: S3 bucket names are globally unique. This lesson includes the account ID and region in the name, so collisions are very unlikely; changing the naming scheme could cause a clash.

Fix: Keep the ansible-lab-ssm-<account>-<region> format.

The second run of ec2_instance created 2 new instances

Cause: Didn’t set filters, or changed a parameter that affects default matching; or the first-run instance was in the shutting-down/terminated state.

aws ec2 describe-instances --filters Name=tag:Project,Values=ansible-lab --query 'Reservations[].Instances[].[InstanceId,State.Name,Tags[?Key==`Name`].Value|[0]]' --output table --profile lab --region ca-central-1

Fix: Set filters explicitly (as in this lesson); terminate the extra instances: amazon.aws.ec2_instance: instance_ids=[…] state=absent.

VpcLimitExceeded: The maximum number of VPCs has been reached.

Cause: The default VPC quota is 5 per region, and earlier labs were not cleaned up.

Fix: Delete the leftover VPCs or request a quota increase (Service Quotas).

CLI exercises
1. Use an ad-hoc command to list the IDs of running instances tagged Project=ansible-lab.
ansible localhost -m amazon.aws.ec2_instance_info -a "profile=lab region=ca-central-1 filters={'tag:Project':'ansible-lab','instance-state-name':'running'}" | grep '"instance_id"'
2. Resolve the latest Ubuntu 24.04 AMI ID.
aws ssm get-parameter --profile lab --region ca-central-1 \
  --name /aws/service/canonical/ubuntu/server/24.04/stable/current/amd64/hvm/ebs-gp3/ami-id --query Parameter.Value --output text
Scenario analysis
A colleague deleted the “EC2 instance” task from provision.yml and reran it, thinking that would “delete” the instance. What happens, and what is the correct approach?

Nothing happens: the instance keeps running and billing, because Ansible has no state and does not know what was created before. The correct approach is to write a state: absent task (matching by filters or instance_ids), or run a dedicated destroy.yml; for long-lived infrastructure, consider a stateful tool such as Terraform.

Verified teaching videos

▶
you need to learn Ansible RIGHT NOW!! (Linux Automation) — NetworkChuck
English · motivation and basics; for cloud resource creation, follow this lesson

No verified video titled “Creating VPC/EC2 with amazon.aws” was found (module names have changed several times in recent years; the ec2,community.aws.ec2_vpc_* syntax used in older videos is outdated), so please use the storyboard below.

Official documentation

Video storyboard script (about 90 seconds)

This courseware cannot directly generate a video or MP3, so a storyboard and narration script are provided.

Shot 1 · 0–20s
Visual: blank region boxes; VPC, gateway, subnet, route table, and security group appear in turn.
Narration: one playbook builds the network in dependency order. Each module looks up first, then compares, and only changes things last.
Shot 2 · 20–45s
Visual: the security group’s inbound list is empty, outbound has only 443 and 80; a lock icon.
Narration: this lesson’s instances have no inbound ports and no SSH keys.
Shot 3 · 45–70s
Visual: the IAM role goes into an “instance profile” box, and the box plugs into EC2; the first attempt flashes red, and turns green after a retry.
Narration: instances get their role through an instance profile. IAM is eventually consistent, so retry right after creation.
Shot 4 · 70–90s
Visual: second run; all tasks show green ok, with changed at zero.
Narration: run it again and nothing changes; that is idempotency. Deleting resources, however, must be written out explicitly.
or score ≥ 70% on the Quiz

Module 4 · SSH-free management: the SSM connection plugin

22:00 – 30:00 · no port 22, no keys, no bastion host: Ansible sends commands through SSM sessions and relays module files through S3
8 minutesamazon.aws.aws_ssm (since 10.0.0)Requires an S3 bucket + Session Manager plugin★★★★★
Learning objectives
  • Explain amazon.aws.aws_ssm the full path of executing one task: StartSession → session-manager-plugin WebSocket → SSM Agent starts a shell → module file PutObject to S3 → presigned URL → curl download on the instance → Python execution → JSON returned through the session → cleanup.
  • List the four prerequisites: S3 bucket,SSM Agent online (instance role or DHMC),the Session Manager plugin on the control node,both sides can reach S3 (the instance also needs curl).
  • Configure the connection variables (bucket, region, profile, timeouts, SSE), understand become and ssm-user, evaluate trade-offs and performance, and know when to switch to “SSH over SSM”.
Prerequisites: The M2 inventory (hostname = instance ID), and the instance role and S3 bucket created in M3. Importance:★★★★★ (core of this lesson)

What: what the SSM connection plugin is

Ansible’s connection plugin is responsible for three things: exec_command (run commands),put_file (upload files),fetch_file (download files). The default ssh plugin uses OpenSSH; amazon.aws.aws_ssm uses AWS Systems Manager Session Manager to open an interactive session for running commands, and S3 for file transfer. The plugin was first added in community.aws 1.0.0,amazon.aws 10.0.0 moved it into amazon.aws; 11.3.0/11.4.0 unified the option names (old names kept as aliases).

Why: why use it

  • Zero inbound ports: the security group can have no inbound rules at all, and instances can even have no public IP (with VPC endpoints).
  • Zero SSH keys: authentication and authorization are handled entirely by IAM (who can start a session to which instance ssm:StartSession), so offboarding and key rotation no longer require distributing keys.
  • Auditing: every session has a StartSession record in CloudTrail; session output can optionally be written to S3/CloudWatch Logs, and sessions can be encrypted with KMS.

How: the real path of one task

  1. The control node packages the module as AnsiballZ_xxx.py (the same as with SSH).
  2. The plugin calls ssm:StartSession (target = ansible_host the instance ID from the inventory, optionally a custom ssm_document) to get SessionId, StreamUrl, and TokenValue.
  3. The plugin starts a local session-manager-plugin process, which connects via WebSocket to ssmmessages endpoint for the data channel.
  4. On the instance, the SSM Agent (which keeps an outbound HTTPS connection to ssm, ssmmessages, and ec2messages) receives the session request and starts a shell as the session user (Linux default: ssm-user), launching the shell.
  5. The plugin writes the command to the session’s stdin and uses start and end markers to split the output and exit code out of stdout (exec_command).
  6. put_file: the control node s3:PutObject uploads the module file to the bucket (keys prefixed with the instance ID) and generates a presigned URL, then has the instance run curl to download it. The instance needs no S3 IAM permissions, but it must be able to reach S3 over the network.
  7. Execute through the session python3 AnsiballZ_xxx.py (become first if needed), the module prints JSON to stdout, which returns through the session and is parsed as ok/changed/failed.
  8. Delete the remote temp directory and the S3 object (even if keep_remote_files is set, the S3 files are still deleted).

When: prerequisites checklist

LocationRequirementHow this lesson meets it
InstanceSSM Agent running and registered as a managed node; on Linux, curl and PythonThe official Ubuntu 24.04 AMI preinstalls SSM Agent (snap), curl, and python3
Instance permissionsPermissions for Agent registration and sessions: attach to the instance role AmazonSSMManagedInstanceCore, or enable Default Host Management Configuration (DHMC)M3’s instance profile
NetworkInstance outbound 443 to ssm, ssmmessages, ec2messages, and S3 (or the corresponding VPC endpoints); control node outbound 443 to SSM and S3Public subnet + outbound 443
Control nodeboto3/botocore,Session Manager pluginModule 0
Control node permissionsssm:StartSession/TerminateSession (plus ResumeSession), and on the bucket s3:GetObject,PutObject,ListBucket,DeleteObject,GetBucketLocationthe sandbox administrator permission set; for the minimal policy, see the “Commands” tab
S3 bucketMust be configured ansible_aws_ssm_bucket_name, even if only using command/shell (module files still need to be transferred)M3’s ansible-lab-ssm-<account>-ca-central-1

Pros, cons, and performance

aws_ssm pluginSSH (direct / bastion)SSH over SSM (ProxyCommand)
Inbound portsNone22None
KeysNone (IAM)RequiredRequired (or pushed temporarily via EC2 Instance Connect)
File transferVia S3 (PutObject + curl)SFTP/SCP or pipeliningSFTP/SCP or pipelining
pipeliningNot applicable (every module goes through S3)Supported, significantly fasterSupported
Per-task overheadHigh: session round trips + S3 upload + curl download, typically secondsLow (ControlPersist reuses connections)Low (reused after the session is first established)
remote_userNot supported; use become_userSupportedSupported
AuditingCloudTrail + session logsMust be built yourselfCloudTrail (session level)

Performance tips: reduce the number of tasks (for example, use one apt to install multiple packages),gather_facts fetch only the subset you need, and raise forks, bake heavyweight one-time installs into the AMI; at large scale (hundreds of hosts), evaluate “SSH over SSM” or the AWS-native AWS-ApplyAnsiblePlaybooks document (where instances pull and run the playbook themselves).

Risk of secrets left behind The official docs warn that secrets passed in tasks may appear in plaintext in S3 transfer files; files can be left behind if a play is interrupted, and with versioning enabled they also persist in version history. Therefore, the bucket should not have versioning enabled, enable SSE (ansible_aws_ssm_bucket_sse_mode: aws:kms + KMS keys is better), set a lifecycle expiration (M3 already sets 1 day), and allow access to the bucket only by the deployment identity.
Common misconceptions① “The instance downloads the module from S3, so the instance role needs s3:GetObject”: the current implementation uses a presigned URL generated by the control node, so the instance only needs network reachability. (Older plugin versions and many older blogs require S3 permissions on the instance role; follow the docs for the version you have installed.) ② “Setting ansible_user: ubuntu makes it run as ubuntu” — aws_ssm does not support remote_user/ansible_user, the session user is determined by Session Manager (default ssm-user, configurable in the session document via runAsEnabled/runAsDefaultUser), and for another identity use become/become_user. ③ “Using SSM means no outbound access is needed”: the instance must reach SSM and S3; private subnets need VPC endpoints (the S3 gateway endpoint is free, interface endpoints are billed hourly).

Architecture diagram: control node, SSM, S3, and instances

Control node ansible-playbook aws_ssm connection plugin (boto3) session-manager-plugin Credentials: SSO profilePermissions: ssm:StartSession + S3 bucket AWS Systems Managerssm: StartSession APIssmmessages: session data channelec2messages: Agent messages S3 bucketi-0a1b…/…/AnsiballZ_apt.pySSE · no versioning · 1-day expiration EC2 instance (no inbound) SSM Agent shell (ssm-user) curl → python3 module Instance role: SSMManagedInstanceCoreNo S3 permissions needed (presigned URL) ①StartSession ②WebSocket ③ Agent outbound long-lived connection ④PutObject ⑤ curl presigned GET
Figure 4-1: all connections are outbound HTTPS: control node → SSM/S3, instance → SSM/S3; the instance listens on no ports

Sequence diagram: round trip of one apt task

Control nodeSSMS3Instance StartSession(i-0a1b…) Session request → Agent starts a shell exec: mkdir ~/.ansible/tmp/ansible-tmp-… (via session) PutObject AnsiballZ_apt.py exec: curl -o …/AnsiballZ_apt.py 'presigned URL' HTTPS GET exec: sudo -u root python3 AnsiballZ_apt.py stdout: {"changed": true, …} + end marker and exit code exec: rm -rf temp directory DeleteObject
Figure 4-2: each task makes at least 4 command round trips through the session plus 1 S3 upload/download; this is why SSM is slower than SSH (with pipelining)

Core animation: how the SSM connection plugin executes one task

Using ansible i-0a1b2c3d4e5f60001 -m ansible.builtin.ping --become as the example, step through it. You can check “Inject fault” to see at which step the chain breaks and the real error you would see. Command text in the terminal is illustrative (the plugin actually uses wrapper commands with random markers); API names and order match the plugin implementation.

Control nodeAnsible + aws_ssmboto3session-manager-plugin SSM servicessm · ssmmessagesec2messages S3 bucketansible-lab-ssm-… EC2 instanceSSM Agentshell (ssm-user)curl · python3

Connection variables and commands

VariablePurposeNotes / default
ansible_connection: amazon.aws.aws_ssmEnable pluginOlder environments may use community.aws.aws_ssm
ansible_host / ansible_aws_ssm_instance_idSession targetInstance ID
ansible_aws_ssm_bucket_nameFile transfer bucketRequired
ansible_aws_ssm_regionSSM regionDefault us-east-1; always set it
ansible_aws_ssm_profileProfile to usecan also use AWS_PROFILE
ansible_aws_ssm_bucket_endpoint_url / ansible_aws_ssm_s3_addressing_styleS3 endpoint and addressing styleOften needed when the bucket and instance are in different regions virtual
ansible_aws_ssm_bucket_sse_mode / …_sse_kms_key_idTransfer file encryptionAES256 or aws:kms
ansible_aws_ssm_documentCustom session documentfor example, set runAsDefaultUser, shell configuration
ansible_aws_ssm_timeout / ansible_aws_ssm_retriesTimeout / reconnect countDefault 60 seconds / 3 attempts
ansible_aws_ssm_pluginSession Manager plugin pathLooks first for /usr/local/bin/session-manager-plugin
---
ansible_connection: amazon.aws.aws_ssm
ansible_aws_ssm_region: "{{ aws_region }}"
ansible_aws_ssm_profile: "{{ aws_profile }}"
ansible_aws_ssm_bucket_name: "{{ lab_prefix }}-ssm-{{ aws_account_id }}-{{ aws_region }}"
ansible_aws_ssm_bucket_sse_mode: AES256
ansible_aws_ssm_timeout: 120
ansible_python_interpreter: /usr/bin/python3
cd ~/ansible-lab
# 1) Check whether the instance is registered as a managed node
aws ssm describe-instance-information --profile lab --region ca-central-1 \
  --query 'InstanceInformationList[].[InstanceId,PingStatus,AgentVersion,PlatformName]' --output table
# 2) Open a session manually (verify IAM + plugin + Agent)
aws ssm start-session --target i-0a1b2c3d4e5f60001 --profile lab --region ca-central-1
# 3) Via Ansible
ansible role_web -i inventories/aws -m ansible.builtin.ping
ansible role_web -i inventories/aws -m ansible.builtin.command -a "id"
ansible role_web -i inventories/aws -b -m ansible.builtin.command -a "id"
-----------------------------------------------------------------
|                  DescribeInstanceInformation                  |
+----------------------+---------+-------------+----------------+
|  i-0a1b2c3d4e5f60001 |  Online |  3.3.xxxx.0 |  Ubuntu        |
|  i-0a1b2c3d4e5f60002 |  Online |  3.3.xxxx.0 |  Ubuntu        |
+----------------------+---------+-------------+----------------+
Starting session with SessionId: andy-0a1b2c3d4e5f6a7b8
$ exit
Exiting session with sessionId: andy-0a1b2c3d4e5f6a7b8.

i-0a1b2c3d4e5f60001 | SUCCESS => { "changed": false, "ping": "pong" }
i-0a1b2c3d4e5f60002 | SUCCESS => { "changed": false, "ping": "pong" }
i-0a1b2c3d4e5f60001 | CHANGED | rc=0 >>
uid=1001(ssm-user) gid=1001(ssm-user) groups=1001(ssm-user)
i-0a1b2c3d4e5f60001 | CHANGED | rc=0 >>
uid=0(root) gid=0(root) groups=0(root)

How to verify: Without become, id shows ssm-user; after become, it is root. Common error: PingStatus is ConnectionLost or the list is empty, Ansible will definitely fail to connect; resolve Agent registration first (M7). Production use: Put the connection variables in inventory group variables; the playbook itself is identical to the SSH setup, which makes it easy to switch between the two connection methods.

Control node minimal permission policy (example)

{
  "Version": "2012-10-17",
  "Statement": [
    { "Sid": "StartSessionOnLabInstances", "Effect": "Allow", "Action": "ssm:StartSession",
      "Resource": "arn:aws:ec2:ca-central-1:111122223333:instance/*",
      "Condition": { "StringEquals": { "ssm:resourceTag/Project": "ansible-lab" } } },
    { "Sid": "SessionDocument", "Effect": "Allow", "Action": "ssm:StartSession",
      "Resource": "arn:aws:ssm:ca-central-1::document/SSM-SessionManagerRunShell" },
    { "Sid": "OwnSessions", "Effect": "Allow", "Action": ["ssm:TerminateSession", "ssm:ResumeSession"],
      "Resource": "arn:aws:ssm:*:*:session/${aws:userid}-*" },
    { "Sid": "Describe", "Effect": "Allow", "Action": ["ssm:DescribeInstanceInformation", "ec2:DescribeInstances"], "Resource": "*" },
    { "Sid": "StagingBucket", "Effect": "Allow",
      "Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject", "s3:ListBucket", "s3:GetBucketLocation"],
      "Resource": ["arn:aws:s3:::ansible-lab-ssm-111122223333-ca-central-1",
                   "arn:aws:s3:::ansible-lab-ssm-111122223333-ca-central-1/*"] }
  ]
}

Session IDs begin with the caller’s user ID, so ${aws:userid} the policy restricts ending sessions to the caller’s own. With SSO, the session ID prefix may relate to the role session name; adjust based on the actual SessionId in CloudTrail.

Windows and “SSH over SSM”

ansible_connection: amazon.aws.aws_ssm
ansible_shell_type: powershell
Host i-* mi-*
  User ubuntu
  ProxyCommand sh -c "aws ssm start-session --target %h --document-name AWS-StartSSHSession --parameters 'portNumber=%p' --profile lab --region ca-central-1"

SSH over SSM keeps SSH’s pipelining and ControlPersist (performance close to direct), but requires placing a public key on the instance (this lesson’s instances have no key pair, so it is not used).

Lab 4: run the first task with zero inbound ports (about 6 minutes)

Wait for Agent registration (usually 1–3 minutes after the instance starts):
watch -n 10 "aws ssm describe-instance-information --profile lab --region ca-central-1 --query 'InstanceInformationList[].[InstanceId,PingStatus]' --output text"
i-0a1b2c3d4e5f60001	Online
i-0a1b2c3d4e5f60002	Online
Write the group variables: save the inventories/aws/group_vars/aws_ec2.yml, and confirm aws_account_id was already written by M3.
ansible-inventory -i inventories/aws --host i-0a1b2c3d4e5f60001 | jq '{ansible_connection, ansible_aws_ssm_bucket_name, ansible_aws_ssm_region}'
{
  "ansible_connection": "amazon.aws.aws_ssm",
  "ansible_aws_ssm_bucket_name": "ansible-lab-ssm-111122223333-ca-central-1",
  "ansible_aws_ssm_region": "ca-central-1"
}
ping and become: run the 3 ansible commands from the “Commands” tab.
Observe the S3 relay: open two terminals, run a slow task in one, and inspect the bucket in the other:
# Terminal A
ansible i-0a1b2c3d4e5f60001 -i inventories/aws -b -m ansible.builtin.apt -a "update_cache=true" -vvv 2>&1 | grep -iE "s3|put|curl|ESTABLISH" | head
# Terminal B (while the task is running)
aws s3 ls "s3://ansible-lab-ssm-$(aws sts get-caller-identity --profile lab --query Account --output text)-ca-central-1/" --recursive --profile lab
ESTABLISH SSM CONNECTION TO: i-0a1b2c3d4e5f60001
… PUT …/AnsiballZ_apt.py TO …
2026-11-15 10:21:07      150432 i-0a1b2c3d4e5f60001/home/ssm-user/.ansible/tmp/ansible-tmp-1763201967.12-…/AnsiballZ_apt.py

After the task finishes, run aws s3 ls again; the file should have been deleted. -vvv The exact wording of the output varies with the plugin version.

Compare timing:
time ansible role_web -i inventories/aws -m ansible.builtin.ping
time ansible role_web -i inventories/aws -m ansible.builtin.setup -a "gather_subset=min" >/dev/null

Record the result; M6 will use gather_subset and task merging to optimize deployment time.

Cleanup: this lab adds no new resources. Confirm aws ssm describe-sessions --state Active --profile lab --region ca-central-1 there are no leftover active sessions (if any, terminate them with aws ssm terminate-session --session-id …).

Case 1: SSM management in a private subnet with no public internet access

Problem: Compliance requires that instances have no public IP and the VPC has no NAT. Approach: Create interface endpoints com.amazonaws.ca-central-1.ssm,ssmmessages,ec2messages (with private DNS enabled and a security group allowing 443 from the VPC), plus an S3 gateway endpoint (associated with the route table). The control node (AAP) is also placed in the same VPC or reached via Direct Connect. Limitation: Each interface endpoint is billed hourly per Availability Zone; the S3 gateway endpoint is free. If the Agent needs to reach KMS (session encryption) or CloudWatch Logs (session logs), add the corresponding endpoints too.

Case 2: a corporate proxy makes SSM intermittently fail

Problem: The control node is on the corporate network and must reach the internet through an HTTP proxy; StartSession succeeds but the WebSocket disconnects, and module file uploads time out. Approach: Set HTTPS_PROXY on the control node; the proxy must allow WebSocket upgrades (ssmmessages.*.amazonaws.com); on the instance side, configure the proxy for the SSM Agent in its service environment (the snap-based Agent requires setting the proxy for the snap service per the AWS docs). Limitation: Proxies that perform TLS inspection usually break the session channel and need to bypass the SSM endpoints.

Case 3: auditing requires recording all operational commands

Problem: The security team requires that all operations on production instances be replayable. Approach: Enable session logging to S3/CloudWatch Logs in the Session Manager preferences with KMS encryption; CloudTrail records the caller and target of each StartSession. Limitation: Ansible module parameters (which may contain secrets) also appear in session logs, so use no_log on sensitive tasks, and restrict access to the logs.

Common errors and fixes

An error occurred (TargetNotConnected) when calling the StartSession operation: i-0a1b2c3d4e5f60001 is not connected.

Cause: The SSM Agent is not registered or is offline: the instance role is missing AmazonSSMManagedInstanceCore, the instance cannot reach the SSM endpoints, the Agent is not running, or the instance was just launched.

aws ssm describe-instance-information --filters Key=InstanceIds,Values=i-0a1b2c3d4e5f60001 --profile lab --region ca-central-1
aws ec2 describe-iam-instance-profile-associations --filters Name=instance-id,Values=i-0a1b2c3d4e5f60001 --profile lab --region ca-central-1
aws ec2 get-console-output --instance-id i-0a1b2c3d4e5f60001 --latest --output text --profile lab --region ca-central-1 | grep -i amazon-ssm-agent

Fix: After attaching the instance profile, the Agent retries registration within a few minutes; restart the instance if necessary. For private subnets, check the VPC endpoints and their security groups.

SessionManagerPlugin is not found. Please refer to SessionManager Documentation …

Cause: The control node does not have the Session Manager plugin installed, or it is not in the default path or PATH (especially common in AWX execution environment images).

Fix: Install it per Module 0, or set ansible_aws_ssm_plugin: /path/to/session-manager-plugin.

The task hangs for a long time and then reports a timeout or a missing remote file (curl download failure, 403, or SignatureDoesNotMatch)

Cause: The instance cannot reach S3 (outbound blocked, no S3 endpoint in the private subnet, or a proxy), or the presigned URL’s region or addressing style does not match the bucket (cross-region bucket).

aws ssm start-session --target i-0a1b2c3d4e5f60001 --profile lab --region ca-central-1
# Run in the session:
curl -sI https://s3.ca-central-1.amazonaws.com | head -1

Fix: Allow outbound 443 or add an S3 gateway endpoint; keep the bucket and instance in the same region where possible, and for cross-region buckets set ansible_aws_ssm_s3_addressing_style: virtual and ansible_aws_ssm_bucket_endpoint_url.

An error occurred (AccessDenied) when calling the PutObject operation: Access Denied

Cause: The control node identity lacks bucket permissions, or the bucket policy or KMS key policy denies access (when using aws:kms , you also need kms:GenerateDataKey/kms:Decrypt).

Fix: Grant access using the minimal policy on the “Commands” tab; check the bucket policy for explicit Deny statements.

An error occurred (AccessDeniedException) when calling the StartSession operation: User: … is not authorized to perform: ssm:StartSession on resource: arn:aws:ec2:…:instance/i-…

Cause: The control node identity lacks StartSession permission for that instance (or session document); a tag-based condition does not match.

Fix: Check the instance tags and policy conditions ssm:resourceTag/Project; also grant access to the document resource SSM-SessionManagerRunShell.

CLI exercises
1. Without using Ansible, verify with one command that IAM, the plugin, and the Agent are all working.
aws ssm start-session --target i-0a1b2c3d4e5f60001 --profile lab --region ca-central-1
2. As root, check the SSM Agent service status on the role_web group (Ubuntu snap version).
ansible role_web -i inventories/aws -b -m ansible.builtin.command -a "snap services amazon-ssm-agent"
Scenario analysis
aws ssm start-session You can open an interactive shell on the instance, but every Ansible task (including ping) hangs at the “transferring module” stage and fails after about 60 seconds. The instance is in a private subnet with a NAT gateway, but the route table was changed recently. How would you troubleshoot?

Being able to open a session shows that IAM, the Session Manager plugin, the Agent, and the SSM endpoints are working; since every module (including ping) relays through S3, being stuck at the transfer stage indicates that the instance cannot access S3 (or the control node’s upload is failing; in that case it usually reports AccessDenied directly rather than timing out). Run curl -sI https://s3.ca-central-1.amazonaws.com in the session to verify; check the subnet route table routes to the NAT gateway or S3 gateway endpoint, the NACL outbound and return rules, and the endpoint policy; if aws:kms encryption is used, also confirm KMS is reachable. Use -vvvv to see which command the plugin is stuck on.

Verified teaching videos

▶
Ansible 101 - Episode 9 - First 5 min server security with Ansible — Jeff Geerling
English · 2020 · covers SSH hardening; compare with this module to understand the “no SSH at all” approach

No verified video on the “Ansible aws_ssm connection plugin” was found (search results are all written tutorials); please use the storyboard script below.

Official documentation

Video storyboard script (about 120 seconds)

This courseware cannot directly generate a video or MP3, so a storyboard and narration script are provided.

Shot 1 · 0–15s
Visual: the security group’s inbound rule table is empty, with port 22 crossed out.
Narration: with no SSH, how does Ansible manage this machine? The answer is Systems Manager.
Shot 2 · 15–40s
Visual: the control node calls StartSession, starts session-manager-plugin locally, and a WebSocket connects to ssmmessages; the Agent on the instance has long since held an outbound long-lived connection.
Narration: both the control node and the instance initiate only outbound connections, and Session Manager connects them in the middle.
Shot 3 · 40–75s
Visual: the module file flies to the S3 bucket; the control node generates a time-limited key (presigned URL) and hands it to the instance, which retrieves the file with curl.
Narration: commands go through the session, files go through S3. The instance itself needs no S3 permissions, only network access to S3.
Shot 4 · 75–100s
Visual: python3 runs the module, JSON returns through the session, the terminal shows a green SUCCESS, and the file in S3 is deleted.
Narration: results return from standard output, and temporary files are cleaned up afterward.
Shot 5 · 100–120s
Visual: side-by-side timers: SSH 0.6 seconds, SSM 3 seconds.
Narration: the cost is speed. Reduce the number of tasks, or bake the installs into the image.
or score ≥ 70% on the Quiz

Module 5 · Secrets: Secrets Manager and SSM parameters

30:00 – 37:00 · secrets stay in the cloud, and the playbook only says where to fetch them from; lookup plugins run on the control node and are re-evaluated on every reference
7 minutessecretsmanager_secret · ssm_parameter lookupRenamed since 6.0.0★★★★☆
Learning objectives
  • Use amazon.aws.secretsmanager_secret (old name aws_secret) and amazon.aws.ssm_parameter (old lookup name aws_ssm) lookup plugins to read secrets and configuration, and understand nested,bypath/recursive/shortnames,on_missing/on_denied.
  • Understand that lookup plugins run on the control node, calling APIs with the control node’s credentials, and the consequences of “lookups in vars being evaluated lazily and calling the API on every reference”.
  • Choose among Secrets Manager, Parameter Store, and Ansible Vault, and use no_log to keep secrets out of logs.
Prerequisites: Lesson 2’s Ansible Vault and variable precedence. Importance:★★★★☆

What: the two lookup plugins

amazon.aws.secretsmanager_secretamazon.aws.ssm_parameter
BackendAWS Secrets Manager (GetSecretValue)SSM Parameter Store (GetParameter/GetParametersByPath)
Old name (alias)amazon.aws.aws_secretamazon.aws.aws_ssm (note: same name as the aws_ssm connection plugin but a different type, so they do not conflict)
Common optionsnested (get the key from JSON),bypath,join,version_stage/version_id,on_missing/on_denied/on_deleted (error/skip/warn)bypath,recursive,shortnames,droppath (8.2.0+),decrypt (default true),on_missing/on_denied
Authenticationthe control node’s boto3 credential chain; you can pass profile,region (lookup plugins do not read module_defaults)
Pricing (see official pricing)Billed per secret per month, plus per API callStandard parameters are free (standard throughput); advanced parameters and high throughput are billed separately; SecureString decryption involves KMS requests
HighlightsAutomatic rotation (Lambda / managed rotation, RDS, etc.), cross-account sharing, version stages AWSCURRENT/AWSPREVIOUShierarchical paths, public parameters (such as the M3 AMI ID), inexpensive

Why: why not keep secrets in Ansible Vault

Vault suits secrets that are few, change rarely, and are used only by Ansible. But once a secret needs rotation, needs to be read by the application itself or other systems, needs fine-grained IAM authorization and auditing, it should live in a cloud secrets service, with the playbook keeping only the name. This way Git no longer holds ciphertext, and the Vault password does not need to be distributed in CI.

How: evaluation timing and location

  1. Location: all lookup plugins run on the control node, regardless of how the target hosts are connected (SSH/SSM); they use the control node’s credentials, not the instance role.
  2. Timing: Ansible variables are lazy. Written in vars:/group_vars the "{{ lookup(...) }}" it runs again each time it is referenced in a template— 3 tasks × 50 hosts = 150 API calls, which easily triggers throttling and raises costs.
  3. Fix: use set_fact (with run_once: true, then pass via hostvars or delegate_facts to share it) so the value is evaluated once; or at the entry point of the role, set_fact.
  4. Passing to instances: secrets are passed as module parameters (for example to a template task that renders an environment file), relayed via S3 and the session to the instance. Add no_log: true, and remember the M4 note on S3 relay files.

Another pattern is to have the instance read it itself: grant the instance role secretsmanager:GetSecretValue (scoped to that secret); the application reads it at startup with the SDK/CLI, and Ansible only distributes the “secret name”. This keeps secrets out of the control node and S3, and is better suited to scenarios that need rotation.

When: choosing an option

ScenarioRecommended
Database passwords, API keys; rotation neededSecrets Manager (or have the application read it directly)
Feature flags, version numbers, ports, and other non-sensitive configurationParameter Store String (free)
A few sensitive settings; budget-sensitiveParameter Store SecureString (KMS encrypted)
Offline environments and cloud-independent secrets (such as switch passwords)Ansible Vault or an external Vault (HashiCorp)
Common misconceptions① “The instance can read the secret, so the lookup can read it”: the lookup runs on the control node and uses the control node’s credentials. ② “debug: var=db_password It is not leaked because it came from Secrets Manager”: once retrieved it is a plain string, and it can appear in output,-v logs, and callback plugins. ③ “on_missing: skip returns an empty string”: it returns an “empty” result, so templates should pair it with default() and confirm this fallback is intended (failing is better when a password is missing).

Architecture diagram: where secrets come from, the path they take, and where they go

Secrets Manageransible-lab/myapp{"secret_key": "…"} Parameter Store/ansible-lab/myapp/version/ansible-lab/myapp/greeting Control nodelookup() → boto3 (SSO credentials)set_fact run_once (evaluated once)template renders /etc/myapp/envno_log: true GetSecretValue GetParametersByPath S3 relaySSE · 1-day expiration EC2/etc/myapp/env0640 root:myappsystemd EnvironmentFile Commands via SSM session Alternative: grant GetSecretValue to the instance role, and the application reads it at startup → secrets never pass through the control node or S3
Figure 5-1: lookup plugins fetch values on the control node; the rendered file is written to the instance via S3 relay and the SSM session

Lazy evaluation: why API call counts explode

vars: db_pw: "{{ lookup(...) }}" task A references → API calls × hoststask B references → API calls × hoststask C references → API calls × hosts3 × 50 hosts = 150 calls set_fact + run_once The first host runs the lookup → 1 API callWith run_once, the result applies to all hostsLater references just read the existing variable1 call
Figure 5-2: a lookup in vars is re-evaluated on every reference; set_fact “freezes” the result

Interactive demo: how many times lookup plugins are evaluated

Choose a pattern, host count, and reference count, click “Run play”, and observe the control node’s actual Secrets Manager API calls (simulating the events in CloudTrail GetSecretValue events).

Host count: 2
Number of tasks referencing the variable: 3

Core commands

Command / pluginPurposeKey parameters
community.aws.secretsmanager_secret (module)Create/update/delete a secretjson_secret,recovery_window (0 = delete immediately)
community.aws.ssm_parameter (module)Create/update a parameterstring_type,value,overwrite_value
lookup('amazon.aws.secretsmanager_secret', NAME)Read a secretnested=true,on_missing
lookup('amazon.aws.ssm_parameter', PATH, bypath=true)Read parameters by pathrecursive,shortnames
aws secretsmanager get-secret-valueCLI cross-check--query SecretString
---
- name: Create myapp secrets and parameters
  hosts: localhost
  connection: local
  gather_facts: false
  tasks:
    - name: Secrets Manager: application key
      community.aws.secretsmanager_secret:
        profile: "{{ aws_profile }}"
        region: "{{ aws_region }}"
        name: "{{ lab_prefix }}/myapp"
        description: "myapp secret key (ansible-lab)"
        json_secret:
          secret_key: "{{ lookup('ansible.builtin.password', '/dev/null', length=40, chars=['ascii_letters', 'digits']) }}"
        overwrite: false
        tags: "{{ lab_tags }}"
      no_log: true

    - name: Parameter Store: non-sensitive configuration
      community.aws.ssm_parameter:
        profile: "{{ aws_profile }}"
        region: "{{ aws_region }}"
        name: "/{{ lab_prefix }}/myapp/{{ item.key }}"
        value: "{{ item.value }}"
        string_type: String
        tags: "{{ lab_tags }}"
      loop: "{{ {'version': 'v1', 'greeting': 'Hello from EC2 via SSM', 'port': '8000'} | dict2items }}"
- name: Read secrets and config once (control node, only one API call)
  ansible.builtin.set_fact:
    myapp_secret_key: "{{ lookup('amazon.aws.secretsmanager_secret', lab_prefix ~ '/myapp.secret_key',
                          nested=true, profile=aws_profile, region=aws_region) }}"
    myapp_params: "{{ lookup('amazon.aws.ssm_parameter', '/' ~ lab_prefix ~ '/myapp/',
                      bypath=true, recursive=true, shortnames=true, profile=aws_profile, region=aws_region) }}"
  run_once: true
  no_log: true

- name: Show only the non-sensitive parts
  ansible.builtin.debug:
    msg: "version={{ myapp_params.version }} port={{ myapp_params.port }} key_len={{ myapp_secret_key | length }}"
cd ~/ansible-lab
ansible-playbook -i inventories/aws playbooks/aws/secrets.yml
aws ssm get-parameters-by-path --path /ansible-lab/myapp/ --profile lab --region ca-central-1 --query 'Parameters[].[Name,Value]' --output text
aws secretsmanager describe-secret --secret-id ansible-lab/myapp --profile lab --region ca-central-1 --query '[Name,ARN]'
/ansible-lab/myapp/greeting	Hello from EC2 via SSM
/ansible-lab/myapp/port	8000
/ansible-lab/myapp/version	v1
[
    "ansible-lab/myapp",
    "arn:aws:secretsmanager:ca-central-1:111122223333:secret:ansible-lab/myapp-AbCdEf"
]

How to verify: The debug output shows only the length, not the secret itself. Common errors:nested=true with a JSON key, a secret name cannot contain dots (dots separate JSON keys); forgetting to pass region causes NoRegionError or hits the wrong region. Production use: A secret’s ARN ends with a 6-character random suffix; in IAM policies, use ansible-lab/myapp-* to match it. overwrite: false Ensures that repeated runs do not overwrite an existing key.

Lab 5: create and read secrets (about 5 minutes; Secrets Manager incurs a small charge)

Create: save and run the playbook from the “Commands” tab: secrets.yml.
Read and verify no_log:
---
- name: Read secret (demo)
  hosts: role_web
  gather_facts: false
  tasks:
    - name: Read
      ansible.builtin.set_fact:
        myapp_secret_key: "{{ lookup('amazon.aws.secretsmanager_secret', lab_prefix ~ '/myapp.secret_key', nested=true, profile=aws_profile, region=aws_region) }}"
        myapp_params: "{{ lookup('amazon.aws.ssm_parameter', '/' ~ lab_prefix ~ '/myapp/', bypath=true, recursive=true, shortnames=true, profile=aws_profile, region=aws_region) }}"
      run_once: true
      no_log: true
    - name: Visible on every host (the run_once set_fact applies to all hosts)
      ansible.builtin.debug:
        msg: "{{ inventory_hostname }} version={{ myapp_params.version }} key_len={{ myapp_secret_key | length }}"
ansible-playbook -i inventories/aws playbooks/aws/read-secrets.yml
TASK [Read] ****************************************************************
ok: [i-0a1b2c3d4e5f60001]
TASK [Visible on every host (the run_once set_fact applies to all hosts)] ***********
ok: [i-0a1b2c3d4e5f60001] => { "msg": "i-0a1b2c3d4e5f60001 version=v1 key_len=40" }
ok: [i-0a1b2c3d4e5f60002] => { "msg": "i-0a1b2c3d4e5f60002 version=v1 key_len=40" }

Note: the tasks in this play do not need to connect to the instance (set_fact and debug are control-node-local actions), so it runs even if SSM has problems; this shows that lookups are independent of the connection method.

Try on_missing:
ansible localhost -m ansible.builtin.debug -a "msg={{ lookup('amazon.aws.ssm_parameter', '/ansible-lab/myapp/nope', region='ca-central-1', profile='lab', on_missing='skip') | default('fallback', true) }}"
ansible localhost -m ansible.builtin.debug -a "msg={{ lookup('amazon.aws.ssm_parameter', '/ansible-lab/myapp/nope', region='ca-central-1', profile='lab') }}"
localhost | SUCCESS => { "msg": "fallback" }
localhost | FAILED! => { "msg": "… Failed to find SSM parameter /ansible-lab/myapp/nope (ResourceNotFound) …" }

The error text varies slightly by version; the key point is that the default behavior is error.

(Optional) Observe the calls in CloudTrail:
aws cloudtrail lookup-events --lookup-attributes AttributeKey=EventName,AttributeValue=GetSecretValue \
  --max-results 5 --profile lab --region ca-central-1 --query 'Events[].[EventTime,Username]' --output table

CloudTrail events are usually delayed by a few minutes.

Cleanup: keep the secret and parameters for M6; M8’s destroy.yml will use recovery_window: 0 to delete the secret immediately and remove the parameters.

Case 1: application disconnects after automatic database password rotation

Problem: Secrets Manager rotates the RDS password every 30 days. Ansible wrote the password into the application config at deploy time, so after rotation the application cannot connect. Approach: Instead, Ansible distributes only the secret ARN, and the application reads AWSCURRENT with the SDK at startup (or when a connection fails); the instance role is granted GetSecretValue on that secret. Limitation: The application must support dynamic reads; during the transition, you can use “trigger an Ansible redeploy after rotation” (EventBridge → EDA, lesson 5).

Case 2: a large-scale play triggers Secrets Manager throttling

Problem: A role run against 300 hosts had 3 lookups in defaults, referenced in several places in templates; CloudTrail showed thousands of GetSecretValue calls per run, with occasional ThrottlingException. Approach: At the start of the play, fetch the values once with set_fact + run_once; keep only the secret names in the role’s defaults. Limitation: When run_once is combined with serial , it runs once per batch.

Case 3: one playbook shared across environments

Problem: dev, staging, and prod have different configurations. Approach: Organize parameters hierarchically by /myapp/{{ env }}/… , and read them with bypath=true, shortnames=true once as a dictionary; IAM policies grant access by path prefix, so developers can only read the dev path. Limitation: Standard parameters have a per-value size limit (see official quotas); put large files in S3.

Common errors and fixes

An error occurred (AccessDeniedException) when calling the GetSecretValue operation: User: … is not authorized to perform: secretsmanager:GetSecretValue on resource: ansible-lab/myapp

Cause: The control node identity lacks permission, or the secret uses a customer-managed KMS key and is missing kms:Decrypt, or the resource policy denies it.

Fix: Grant secretsmanager:GetSecretValue (Resource arn:…:secret:ansible-lab/myapp-*); when tolerance is needed, use on_denied='warn', but in production it should usually fail.

Failed to find secret ansible-lab/myapp (ResourceNotFoundException)

Cause: Wrong region (lookup plugins do not read module_defaults), a typo in the name, or the secret is in a “scheduled for deletion” state (on_deleted governs this behavior).

aws secretsmanager list-secrets --include-planned-deletion --filters Key=name,Values=ansible-lab --profile lab --region ca-central-1 --query 'SecretList[].[Name,DeletedDate]'

Fix: Explicitly pass region; if it is scheduled for deletion, use aws secretsmanager restore-secret to restore it.

You can't create this secret because a secret with this name is already scheduled for deletion.

Cause: A secret with the same name was previously deleted with the default recovery window (30 days).

Fix: Restore it before use, or aws secretsmanager delete-secret --secret-id … --force-delete-without-recovery; this lesson’s destroy.yml uses recovery_window: 0 to avoid this problem.

Plaintext secret appears in output (debug, -v, failure messages)

Cause: The tasks using the secret do not have no_log: true; on failure, the module echoes its parameters back.

Fix: For tasks that use secrets, such as set_fact, template, and uri, add no_log: true; rotate any leaked secrets; restrict access to CI logs.

CLI exercises
1. Use an ad-hoc command to read all parameters under /ansible-lab/myapp/ as a dictionary (short names).
ansible localhost -m ansible.builtin.debug -a "msg={{ lookup('amazon.aws.ssm_parameter', '/ansible-lab/myapp/', bypath=true, recursive=true, shortnames=true, region='ca-central-1', profile='lab') }}"
2. Delete the secret ansible-lab/myapp immediately (without a recovery window).
aws secretsmanager delete-secret --secret-id ansible-lab/myapp --force-delete-without-recovery --profile lab --region ca-central-1
Scenario analysis
The instance role has already been granted GetSecretValue, but the lookup in the playbook still returns AccessDenied; a colleague suggests “give the control node the instance role’s permissions too.” What do you think?

The lookup runs on the control node and uses the control node’s credentials, which have nothing to do with the instance role, so the error is expected. Choose one of two correct approaches: ① grant the control node identity (the deployment role) the minimum read permission on that secret, and use set_fact + no_log; ② do not read the secret in Ansible at all, only distribute the secret name and let the application read it with the instance role. The latter is more secure and naturally supports rotation. Do not simply copy the same set of permissions to every identity.

Verified teaching videos

▶
Ansible 101 - Episode 6 - Ansible Vault and Roles — Jeff Geerling
English · 2020 · covers Ansible Vault; compare with this module’s cloud secrets approach

No verified video on the Secrets Manager / Parameter Store lookup plugins was found; please use the storyboard script below.

Official documentation

Video storyboard script (about 80 seconds)

This courseware cannot directly generate a video or MP3, so a storyboard and narration script are provided.

Shot 1 · 0–20s
Visual: the vault file in the Git repository is replaced with a single line containing the secret name.
Narration: secrets stay in the cloud; the code only says where to fetch them.
Shot 2 · 20–45s
Visual: the lookup arrow starts from the control node, not from EC2.
Narration: lookup plugins run on the control node and use the control node’s credentials.
Shot 3 · 45–65s
Visual: the counter goes up by one on every reference, soaring to 150; after switching to set_fact, it drops to one.
Narration: a lookup in vars calls the API again on every reference. Use set_fact to fetch only once.
Shot 4 · 65–80s
Visual: terminal output is blurred, and the task is tagged no_log.
Narration: a retrieved secret is just a plain string, so remember to add no_log.
or score ≥ 70% on the Quiz

Module 6 · Configuring EC2 and deploying the application

37:00 – 44:00 · the same myapp role, now with a dynamic inventory + SSM connection, rolled out to EC2 in batches, and verified under the premise of “no inbound ports”
7 minutesroles/myappRolling serial★★★★☆
Learning objectives
  • Apply the lesson 2 myapp role (Flask + gunicorn + Redis + systemd) to EC2 without modification: all differences are expressed in the inventory and group variables.
  • Handle the SSM-specific details: wait_for_connection,become and ssm-user,gather_subset speed-ups and secrets no_log.
  • Use serial + max_fail_percentage for rolling deployment, and verify through uri (on the instance) or via SSM port forwarding /healthz.
Prerequisites: Lesson 2’s role structure and handlers; M4 and M5. Importance:★★★★☆

What: what this module deploys

myapp is the same as in the Docker lesson: a Flask app, with gunicorn listening 0.0.0.0:8000, Redis counter,/healthz health check. Lesson 2 deploys it natively with systemd on the container node; this lesson deploys to 2 EC2 instances. The role itself needs no changes—this is the value of “decoupling the connection method from the business logic”:

LayerLesson 2 (container node)Lesson 4 (EC2)
InventoryStatic hosts.yml (node1–3)lab.aws_ec2.yml (role_web group)
Connectionsshamazon.aws.aws_ssm (group_vars/aws_ec2.yml)
SecretsAnsible VaultSecrets Manager + Parameter Store (M5)
Roleroles/myapp (identical)

Why: why use rolling updates

Even with only 2 hosts, update them one at a time: verify the health check on one host first, stop if it fails, and let the other keep serving. In production, combine this with a load balancer (ALB target group) to deregister and re-register each host (multi-tier architecture, Lesson 6).

How: play structure

  1. hosts: role_web,become: true,serial: 1,max_fail_percentage: 0.
  2. gather_facts: true + gather_subset: [min]: the setup module is slow over SSM, so gather only the minimum facts.
  3. pre_tasks: wait_for_connection (the agent on a new instance may not be ready yet),set_fact + run_once read secrets (M5).
  4. roles: [myapp]: apt install → user and directories → venv + pip → app code → env file (no_log) → systemd unit → handlers restart.
  5. post_tasks: inside the instance, use uri http://127.0.0.1:8000/healthz retry until 200.

When: become and users

  • SSM sessions run by default as ssm-user , and the agent configures passwordless sudo for it, so become: true works directly.
  • To run a task as the application user: become_user: myapp. Note that when becoming from one unprivileged user to another, Ansible needs the target user to be able to read the temporary module files (ACL/setfacl or allow_world_readable_tmpfiles), so on Ubuntu, install acl package is the simplest option.
  • Do not set ansible_user: aws_ssm does not support it.

Compared with similar approaches

Ansible push (this lesson)user_data / cloud-initBake an AMI (Packer + Ansible)SSM State Manager + AWS-ApplyAnsiblePlaybooks
TimingAny time, repeatableFirst boot onlyAt build timePeriodically / on association, the instance pulls its own config
Best forOngoing configuration and change releasesBootstrapping (installing agent, registration)Large-scale, fast scale-outMassive fleets, no central control node
Common misconceptions① “You can’t verify an app without an inbound port”—you can use uri check, or use SSM port forwarding AWS-StartPortForwardingSession to map port 8000 to localhost. ② “serial: 1 will make run_once’s set_fact run only once”—run_once is applied per batch; with serial: 1 every batch runs it once (2 hosts means 2 API calls). For a single global run, move it to an earlier play that is not batched.

Internal structure of the deployed instance

EC2 myapp-1 (Ubuntu 24.04, no inbound ports) myapp.servicegunicorn -b 0.0.0.0:8000 -w 2User=myapp · EnvironmentFile redis-server127.0.0.1:6379INCR hits /etc/myapp/env (0640 root:myapp)SECRET_KEY (Secrets Manager)APP_VERSION / GREETING (parameters) /opt/myappapp.py · venv (flask, gunicorn, redis) SSM AgentAnsible session · port forwarding Verification methodin-instance uri 127.0.0.1:8000 · SSM port forwarding
Figure 6-1 Same service structure as Lesson 2; only the “how to connect” is now SSM

Rolling deployment flow

Batch 1: myapp-1 wait_for_connectiongather min · read secrets roles: myapp handlers restart healthz = 200 Batch 2: myapp-2 Failure → max_fail_percentage: 0 → stop; myapp-2 is unaffected
Figure 6-2 With serial: 1, each host fully completes the role and health check before the next one starts

Interactive demo: rolling deployment timeline (SSM overhead visible)

Choose serial and whether to inject a health-check failure on myapp-1, then click “Start deployment”. Each cell represents a task stage, and color shows its status. Timing is an illustration based on typical SSM-scenario magnitudes (a few seconds per task), intended for comparing batch strategies, not exact durations.

Role (minimal version; if roles/myapp from Lesson 2 already exists, you can reuse it directly)

---
myapp_user: myapp
myapp_dir: /opt/myapp
myapp_port: 8000
myapp_workers: 2
myapp_version: v1
myapp_greeting: "Hello"
myapp_secret_key: ""          # injected by the caller from Secrets Manager
myapp_pip_packages:
  - "flask==3.1.*"
  - "gunicorn==23.*"
  - "redis>=5,<8"
---
- name: Install system packages (install several at once to reduce SSM round trips)
  ansible.builtin.apt:
    name: [python3-venv, redis-server, acl]
    update_cache: true
    cache_valid_time: 3600

- name: App user
  ansible.builtin.user:
    name: "{{ myapp_user }}"
    system: true
    shell: /usr/sbin/nologin
    home: "{{ myapp_dir }}"
    create_home: false

- name: Directories
  ansible.builtin.file:
    path: "{{ item }}"
    state: directory
    owner: root
    group: "{{ myapp_user }}"
    mode: "0750"
  loop: ["{{ myapp_dir }}", /etc/myapp]

- name: Virtualenv and dependencies
  ansible.builtin.pip:
    name: "{{ myapp_pip_packages }}"
    virtualenv: "{{ myapp_dir }}/venv"
    virtualenv_command: python3 -m venv
  notify: restart myapp

- name: App code
  ansible.builtin.template:
    src: app.py.j2
    dest: "{{ myapp_dir }}/app.py"
    owner: root
    group: "{{ myapp_user }}"
    mode: "0640"
  notify: restart myapp

- name: Environment file (contains secrets)
  ansible.builtin.template:
    src: env.j2
    dest: /etc/myapp/env
    owner: root
    group: "{{ myapp_user }}"
    mode: "0640"
  no_log: true
  notify: restart myapp

- name: systemd unit
  ansible.builtin.template:
    src: myapp.service.j2
    dest: /etc/systemd/system/myapp.service
    mode: "0644"
  notify: restart myapp

- name: Start service
  ansible.builtin.systemd_service:
    name: "{{ item }}"
    state: started
    enabled: true
    daemon_reload: true
  loop: [redis-server, myapp]
---
- name: restart myapp
  ansible.builtin.systemd_service:
    name: myapp
    state: restarted
    daemon_reload: true
import os, socket
from flask import Flask, jsonify
import redis

app = Flask(__name__)
r = redis.Redis(host="127.0.0.1", port=6379, socket_connect_timeout=2)

@app.get("/")
def index():
    return jsonify(greeting=os.getenv("GREETING", "hi"), version=os.getenv("APP_VERSION", "dev"),
                   host=socket.gethostname(), hits=r.incr("hits"))

@app.get("/healthz")
def healthz():
    r.ping()
    return "ok"
SECRET_KEY={{ myapp_secret_key }}
APP_VERSION={{ myapp_version }}
GREETING={{ myapp_greeting }}
[Unit]
Description=myapp (Flask + gunicorn)
After=network-online.target redis-server.service
Wants=network-online.target

[Service]
User={{ myapp_user }}
Group={{ myapp_user }}
WorkingDirectory={{ myapp_dir }}
EnvironmentFile=/etc/myapp/env
ExecStart={{ myapp_dir }}/venv/bin/gunicorn --bind 0.0.0.0:{{ myapp_port }} --workers {{ myapp_workers }} --access-logfile - app:app
Restart=on-failure
NoNewPrivileges=true
ProtectSystem=full

[Install]
WantedBy=multi-user.target

Deployment playbook

---
- name: Roll out myapp to EC2 via SSM
  hosts: role_web
  become: true
  serial: 1
  max_fail_percentage: 0
  gather_facts: true
  gather_subset: [min]
  pre_tasks:
    - name: Wait for SSM to be available
      ansible.builtin.wait_for_connection:
        timeout: 300

    - name: Read secrets and parameters (control node)
      ansible.builtin.set_fact:
        myapp_secret_key: "{{ lookup('amazon.aws.secretsmanager_secret', lab_prefix ~ '/myapp.secret_key', nested=true, profile=aws_profile, region=aws_region) }}"
        _params: "{{ lookup('amazon.aws.ssm_parameter', '/' ~ lab_prefix ~ '/myapp/', bypath=true, recursive=true, shortnames=true, profile=aws_profile, region=aws_region) }}"
      run_once: true
      no_log: true

    - name: Map parameters to role variables
      ansible.builtin.set_fact:
        myapp_version: "{{ _params.version }}"
        myapp_greeting: "{{ _params.greeting }}"
        myapp_port: "{{ _params.port | int }}"
  roles:
    - myapp
  post_tasks:
    - name: Run pending handlers now
      ansible.builtin.meta: flush_handlers

    - name: In-instance health check
      ansible.builtin.uri:
        url: "http://127.0.0.1:{{ myapp_port }}/healthz"
        return_content: true
      register: hz
      retries: 10
      delay: 3
      until: hz.status == 200
      become: false
cd ~/ansible-lab
ansible-playbook -i inventories/aws playbooks/aws/deploy-myapp.yml --check --diff   # dry run (on first deployment some tasks may error or be skipped because dependencies are not yet installed; this is normal)
time ansible-playbook -i inventories/aws playbooks/aws/deploy-myapp.yml
PLAY [Roll out myapp to EC2 via SSM] ************************************************
TASK [Wait for SSM to be available] ****************************************************************
ok: [i-0a1b2c3d4e5f60001]
TASK [myapp : Install system packages (install several at once to reduce SSM round trips)] ************************
changed: [i-0a1b2c3d4e5f60001]
…
RUNNING HANDLER [myapp : restart myapp] ********************************************
changed: [i-0a1b2c3d4e5f60001]
TASK [In-instance health check] ****************************************************************
ok: [i-0a1b2c3d4e5f60001]
PLAY [Roll out myapp to EC2 via SSM] ************************************************
…
PLAY RECAP *************************************************************************
i-0a1b2c3d4e5f60001 : ok=14  changed=9  unreachable=0  failed=0  skipped=0  rescued=0  ignored=0
i-0a1b2c3d4e5f60002 : ok=14  changed=9  unreachable=0  failed=0  skipped=0  rescued=0  ignored=0
real    4m12.6s

Access the app from the control node: SSM port forwarding

aws ssm start-session --target i-0a1b2c3d4e5f60001 --profile lab --region ca-central-1 \
  --document-name AWS-StartPortForwardingSession --parameters '{"portNumber":["8000"],"localPortNumber":["18000"]}'
# another terminal
curl -s localhost:18000/ ; echo; curl -s localhost:18000/healthz
Starting session with SessionId: andy-0b2c3d4e5f6a7b8c9
Port 18000 opened for sessionId andy-0b2c3d4e5f6a7b8c9.
Waiting for connections...

{"greeting":"Hello from EC2 via SSM","host":"ip-10-40-1-23","hits":1,"version":"v1"}
ok

How to verify: A second run of deploy-myapp.yml should changed=0 (apt cache is not refreshed within cache_valid_time). Common errors: pip install failures are usually caused by the instance being unable to reach PyPI (outbound 443 blocked). In production, use an internal mirror or bake the dependencies into the AMI. Production use: Change /ansible-lab/myapp/version parameter and rerun to complete a “configuration-driven” release.

Lab 6: Deploy myapp without SSH (about 8 minutes)

Prepare the role: if roles/myapp comes from Lesson 2, confirm its variable names match this lesson (myapp_port,myapp_secret_key etc.), otherwise create the minimal version following the “Commands” tab:
mkdir -p ~/ansible-lab/roles/myapp/{defaults,tasks,handlers,templates}
ls -R ~/ansible-lab/roles/myapp
Deploy: run deploy-myapp.yml, and watch the two batches run in sequence.
Verify:
ansible role_web -i inventories/aws -m ansible.builtin.uri -a "url=http://127.0.0.1:8000/ return_content=true" | grep -E "SUCCESS|hits"
ansible role_web -i inventories/aws -b -m ansible.builtin.command -a "systemctl is-active myapp redis-server"
ansible role_web -i inventories/aws -b -m ansible.builtin.stat -a "path=/etc/myapp/env" | grep -E '"mode"|"pw_name"|"gr_name"'
i-0a1b2c3d4e5f60001 | SUCCESS => {
        "content": "{\"greeting\":\"Hello from EC2 via SSM\",\"host\":\"ip-10-40-1-23\",\"hits\":2,\"version\":\"v1\"}\n",
i-0a1b2c3d4e5f60001 | CHANGED | rc=0 >>
active
active
        "gr_name": "myapp",
        "mode": "0640",
        "pw_name": "root",
Configuration-driven release: after changing the version to v2 and redeploying, only the env file change and restart are triggered:
aws ssm put-parameter --name /ansible-lab/myapp/version --value v2 --overwrite --profile lab --region ca-central-1
ansible-playbook -i inventories/aws playbooks/aws/deploy-myapp.yml | grep -E "changed:|RECAP" -A0
ansible role_web -i inventories/aws -m ansible.builtin.uri -a "url=http://127.0.0.1:8000/ return_content=true" | grep -o '"version\\":\\"v[0-9]'
Access via port forwarding: use the “Commands” tab to run AWS-StartPortForwardingSession Open http://localhost:18000/ in a browser.
Cleanup: keep the environment for the M7 troubleshooting lab; after finishing M7, run destroy.yml from M8.

Case 1: rolling release behind an ALB

Problem: Restarting the service directly on the instance causes the ALB to keep sending requests to the node that is restarting. Approach: Before each batch, use community.aws.elb_target (or elb_target_group) to deregister the instance from the target group and wait for connections to drain; after deploying and passing the health check, register it again. Limitation: The deregistration delay defaults to 300 seconds and must be tuned to the application, or releases will be very slow.

Case 2: first-time configuration of new Auto Scaling instances

Problem: New instances launched by ASG scale-out have no application. Approach: Pre-install dependencies in the AMI (Packer + the same Ansible role), and have user_data only fetch the version number and start; or use an ASG lifecycle hook → EventBridge → EDA/AWX job template, passing limit to target the new instance and run deploy-myapp.yml (Lesson 5). Limitation: In SSM push mode each instance takes several minutes, so for services sensitive to scale-out speed, prefer the AMI approach.

Case 3: SSM deployment is too slow

Problem: Deploying a role with 60 tasks to 40 instances over SSM takes 40 minutes. Approach: Merge apt/pip installs and remove unnecessary gather_facts,forks: 20,serial: 25%; move rarely-changing parts into the AMI; and for scenarios that still need heavy file transfer, switch to “SSH over SSM” to restore pipelining. Limitation: Watch the SSM session concurrency quota and API throttling (M7).

Common errors and fixes

Failed to update apt cache: … Could not connect to ca-central-1.ec2.archive.ubuntu.com:80

Cause: The security group's outbound rules or the NACL do not allow port 80 (Ubuntu's EC2 image mirrors use HTTP by default).

Fix: The M3 security group already allows port 80; private subnets need a NAT or an internal mirror.

Failed to set permissions on the temporary files Ansible needs to create when becoming an unprivileged user

Cause:become_user When becoming a non-root user, the target user cannot read the temporary module files uploaded by ssm-user.

Fix: Install acl package (the role's first step already installs it); or avoid becoming a non-privileged user.

uri health check: Status code was -1 and not [200]: Request failed: <urlopen error [Errno 111] Connection refused>

Cause: gunicorn did not start, or crashed after starting (for example, a malformed env file or missing dependencies).

ansible i-0a1b2c3d4e5f60001 -i inventories/aws -b -m ansible.builtin.command -a "journalctl -u myapp -n 30 --no-pager"

Fix: Correct based on the logs; confirm the handler has run (meta: flush_handlers).

wait_for_connection timeout: timed out waiting for ping module test

Cause: The new instance's agent has not registered yet, or SSM prerequisites are not met (see M4 troubleshooting).

Fix: First, run aws ssm describe-instance-information to confirm it shows Online; increase the timeout.

pip: Could not find a version that satisfies the requirement flask==3.1.*

Cause: The instance cannot reach PyPI, or the pip in the venv is too old.

Fix: Check outbound 443; before the pip task, add name: pip, state: latest; in production, use an internal artifact repository.

Command-line exercise
1. Redeploy only to the instance corresponding to myapp-2 (without modifying the playbook).
ansible-playbook -i inventories/aws playbooks/aws/deploy-myapp.yml --limit i-0a1b2c3d4e5f60002
2. Forward port 8000 on the instance to local port 18000.
aws ssm start-session --target i-0a1b2c3d4e5f60001 --document-name AWS-StartPortForwardingSession \
  --parameters '{"portNumber":["8000"],"localPortNumber":["18000"]}' --profile lab --region ca-central-1
Scenario analysis
The deployment playbook stopped after the health check failed on the first instance. The second instance was not modified, but the team wants to know “what would have happened with serial: 2?” Please analyze and give production recommendations.

With serial: 2, both hosts run in the same batch, so both would write the faulty version and restart, and the health checks would fail together → everything unavailable. serial: 1 + max_fail_percentage: 0 confines the failure to one host. Production recommendation: use 1 host or 10% as a canary first batch (serial: [1, "50%", "100%"]), combined with ALB deregistration/re-registration, and automatically roll back to the previous version when the health check fails (for example, use block/rescue to restore the previous env file and code).

Verified instructional videos

▶
Ansible 101 - Episode 6 - Ansible Vault and Roles — Jeff Geerling
English · 2020 · the role-structure section is useful for reviewing how roles/myapp is organized
▶
What is Ansible | Ansible Playbook explained | Ansible Tutorial for Beginners — TechWorld with Nana
English · review of playbook / play / task structure

No verified video on “deploying an app to EC2 via SSM” was found; please use the storyboard below.

Official documentation

Video storyboard script (about 80 seconds)

This courseware cannot directly generate video/MP3, so a storyboard and narration script are provided instead.

Shot 1 · 0–20s
Visual: static inventory + ssh on the left, dynamic inventory + SSM on the right, and the same roles/myapp folder in the middle.
Narration: the role does not change by a single line; only the inventory and connection method are swapped.
Shot 2 · 20–50s
Visual: two swim lanes; myapp-1 finishes all tasks first and turns on a green health light, and only then does myapp-2 start.
Narration: serial equals one, deploying host by host, and proceeding only after the health check passes.
Shot 3 · 50–80s
Visual: a laptop browser accesses localhost port 18000; an arrow passes through the SSM tunnel to port 8000 on the instance.
Narration: no inbound port is needed; you can still use SSM port forwarding to access the app locally.
or score ≥ 70% on the “Quiz”

Module 7 · Cloud troubleshooting in practice

44:00 – 53:00 · Assign faults to the correct layer: Python/SDK → credentials → IAM → inventory → SSM session → S3 relay → instance; each layer has one “verification command”
9 minutesLayered diagnosisInteractive troubleshooting tree★★★★★
Learning objectives
  • When you see an error, first determine which layer it comes from, then use that layer’s “verification command” to confirm or rule it out within one minute.
  • Become proficient in six common fault types: credentials (expired / wrong source), boto3 version, empty inventory, SSM connection failures (agent, S3 permissions, proxy), AccessDenied (including decoding authorization failure messages), and API throttling.
  • Be able to use -vvvv,debug_botocore_endpoint_logs, CloudTrail,aws ssm describe-instance-information to collect evidence.
Prerequisites: M1–M6. Importance:★★★★★

What: the seven-layer fault model for Ansible in the cloud

LayerTypical error / symptomVerification command
L1 Python / SDKFailed to import the required Python library (botocore and boto3), version too oldansible --version; in that Python, run import boto3
L2 CredentialsUnable to locate credentials,ExpiredToken,InvalidClientTokenId, expired SSO tokenenv | grep ^AWS_; aws sts get-caller-identity --profile lab
L3 IAM authorizationAccessDenied,UnauthorizedOperation (may include an Encoded authorization failure message)aws sts decode-authorization-message; the errorCode of the CloudTrail event
L4 Inventoryempty inventory, group does not exist, hostname is not an instance IDansible-inventory --graph --flush-cache -vvv
L5 SSM sessionTargetNotConnected,SessionManagerPlugin is not found, session timeoutaws ssm describe-instance-information; aws ssm start-session
L6 S3 relayPutObject AccessDenied, curl download stalls / 403, cross-region signature errorcontrol node aws s3 cp; inside the session curl -sI https://s3.<region>.amazonaws.com
L7 Instance / applicationapt/pip failures, service won’t start, health check failuresjournalctl,systemctl status (via SSM)

Why: why layering matters

Cloud errors often “look the same”: SSM hangs for 60 seconds and then times out. It could be an offline agent (L5), an instance that cannot reach S3 (L6), or just a local proxy (L5/L6). Confirm layer by layer from the bottom up; each layer has a command that verifies it independently of Ansible, so you can avoid blindly adding things to the playbook, such as retries.

How: key points for the six common fault types

  • Credentials: explicit parameters > environment variables > profile configuration (M1). On CI, clear first AWS_* then inject; humans use SSO; when it expires, run aws sso login.
  • boto3 version: amazon.aws 12.x requires boto3/botocore ≥ 1.38.23, installed in the Python that Ansible runs in (pipx inject). In AWX, this is an execution environment image issue (Lesson 5).
  • Empty inventory: file name suffix, region, filters (tag key case), instance state, the profile used by the inventory, cache.
  • SSM connection failures: agent not registered (instance role/DHMC, outbound to ssm/ssmmessages/ec2messages), missing control-node plugin, S3 permissions (control node) or S3 network (instance), corporate proxy not supporting WebSocket, bucket and region mismatch.
  • AccessDenied: distinguish “who the caller is” (aws_caller_info) from “which action/resource is missing” (error text, decoded message, CloudTrail); also consider explicit denies from SCPs, permission boundaries, resource policies, and KMS key policies.
  • Throttling: RequestLimitExceeded (EC2),ThrottlingException (SSM/STS/Secrets Manager, etc.),Rate exceeded. Use botocore’s adaptive retry mode, lower forks or use throttle, use set_fact to cache lookups, and enable inventory caching.

When: tools for collecting evidence

ToolPurpose
ansible-playbook -vvvvSee each step of the connection plugin (SSM session setup, file upload, commands executed)
debug_botocore_endpoint_logs: true (common AWS module parameters)Return in the result resource_actions: which APIs the module actually calls, useful for writing a least-privilege policy
CloudTrail lookup-eventswho, when, which API was called, and what the errorCode is
aws ssm describe-instance-informationwhether the managed node is Online, agent version
EC2 serial console / get-console-outputagent startup logs, cloud-init errors
Common misconceptions① “Increasing ansible_aws_ssm_timeout can fix connection problems” — timeouts are just a symptom; no matter how much you raise it, it does not help when the agent is offline or S3 is unreachable. ② “AccessDenied just means the policy was never written” — it can also be an explicit deny from an SCP, permission boundary, session policy, resource policy, or KMS key policy. ③ “Throttling means AWS has a problem” — it is almost always caused by your own concurrency and repeated calls.

Layered diagnosis diagram

L7 Instance / application: apt, pip, systemd, health check L6 S3 relay: PutObject permission (control node) · curl reachability (instance) L5 SSM session: agent Online · plugin · StartSession permission · proxy L4 Inventory: suffix · region · filters · hostnames · cache L3 IAM: identity policy · SCP · permission boundary · resource policy · KMS L2 Credentials: source order · expiry · account L1 Python / SDK: interpreter · boto3/botocore version · collection version Bottom to topConfirm layer by layer ansible --versionaws sts get-caller-identitydecode-authorization-messageansible-inventory --graphdescribe-instance-informationaws s3 cp / curl -sIjournalctl -u myapp
Figure 7-1 Each layer has a verification command independent of Ansible

The same “timeout”, three root causes

task hangs → timeout Agent offline (PingStatus ConnectionLost) → L5: instance role, outbound 443, agent service start-session works, but module transfer hangs → L6: instance access to S3 / presigned URL region CLI start-session also stuck at “Starting session” → control-node proxy blocks WebSocket
Figure 7-2 First use aws ssm start-session split the problem into “session layer” and “transfer layer” halves

Fault localization simulator: which layer does this error belong to?

Select a real error and click “Start diagnosis”. The simulator runs verification commands layer by layer from L1 upward, stops at the faulty layer, and gives the fix. This is the automated version of the troubleshooting tree on the “Troubleshooting” tab.

Diagnostic command quick reference

CommandPurposeNotes
env | grep ^AWS_Check leftover credentials / regionRun first
aws configure list --profile labValue and source of each configuration itemShows type (env, shared-credentials-file, sso…)
aws sts decode-authorization-messageDecode authorization failure messages returned by EC2 and othersRequires sts:DecodeAuthorizationMessage
aws cloudtrail lookup-eventsQuery recent API calls by event name / userManagement events have a delay of several minutes
aws ssm describe-instance-informationManaged node statusOnline / ConnectionLost / Inactive
ANSIBLE_DEBUG=1 / -vvvvAnsible internals and connection plugin debuggingLots of output; redirect to a file
AWS_RETRY_MODE=adaptive AWS_MAX_ATTEMPTS=10botocore retries and client-side rate limitingcan also be written to the profile: retry_mode,max_attempts
# Let the module tell you which APIs it calls (a handy tool for writing least-privilege policies)
ansible localhost -m amazon.aws.ec2_vpc_net_info \
  -a "profile=lab region=ca-central-1 filters={'tag:Project':'ansible-lab'} debug_botocore_endpoint_logs=true" | jq '.resource_actions'
[
  "ec2:DescribeVpcs"
]
# Decode the encoded message in UnauthorizedOperation
MSG='Paste the Encoded authorization failure message from the error here'
aws sts decode-authorization-message --encoded-message "$MSG" --profile lab --query DecodedMessage --output text \
  | jq '{allowed, explicitDeny, action: .context.action, resource: .context.resource}'
# Failed API calls in the last 15 minutes (CloudTrail)
aws cloudtrail lookup-events --profile lab --region ca-central-1 --max-results 50 \
  --start-time "$(date -u -d '-15 min' +%FT%TZ)" \
  --query 'Events[].CloudTrailEvent' --output text | jq -c 'select(.errorCode != null) | {eventName, errorCode, errorMessage}' | head
{"eventName":"PutObject","errorCode":"AccessDenied","errorMessage":"Access Denied"}
{"eventName":"StartSession","errorCode":"TargetNotConnected","errorMessage":"i-0a1b2c3d4e5f60002 is not connected."}

Note: S3 object-level operations (PutObject) belong to data events, which are not logged to CloudTrail by default; you need to enable data event tracking separately. The output above assumes it is enabled.

[profile lab]
sso_session = lab-sso
sso_account_id = 111122223333
sso_role_name = LabAdmin
region = ca-central-1
retry_mode = adaptive
max_attempts = 10
- name: Query volumes for each instance (avoid EC2 API throttling)
  amazon.aws.ec2_vol_info:
    profile: "{{ aws_profile }}"
    region: "{{ aws_region }}"
    filters:
      attachment.instance-id: "{{ instance_id }}"
  delegate_to: localhost
  throttle: 5

Lab 7: Create 3 faults and fix them (about 8 minutes)

Fault A: empty inventory (L4)—change the filter’s tag to lowercase:
cd ~/ansible-lab
sed -i 's/tag:Project: ansible-lab/tag:project: ansible-lab/' inventories/aws/lab.aws_ec2.yml
ansible-inventory -i inventories/aws --graph --flush-cache
# Diagnose: use the same filter with the CLI
aws ec2 describe-instances --profile lab --region ca-central-1 --filters Name=tag:project,Values=ansible-lab --query 'length(Reservations)'
aws ec2 describe-instances --profile lab --region ca-central-1 --filters Name=tag:Project,Values=ansible-lab --query 'length(Reservations)'
# Fix
sed -i 's/tag:project: ansible-lab/tag:Project: ansible-lab/' inventories/aws/lab.aws_ec2.yml
ansible-inventory -i inventories/aws --graph --flush-cache | head -5
@all:
  |--@ungrouped:
0
2
@all:
  |--@ungrouped:
  |--@aws_ec2:
  |  |--i-0a1b2c3d4e5f60001
  |  |--i-0a1b2c3d4e5f60002

Conclusion: EC2 tag keys are case-sensitive.

Fault B: S3 relay failure (L6)—specify a bucket that does not exist:
ansible role_web -i inventories/aws -m ansible.builtin.ping -e ansible_aws_ssm_bucket_name=ansible-lab-no-such-bucket-$RANDOM -vvv 2>&1 | grep -iE "NoSuchBucket|AccessDenied|error" | head -3
aws s3 ls s3://ansible-lab-no-such-bucket-12345 --profile lab 2>&1 | head -1
… An error occurred (NoSuchBucket) when calling the PutObject operation: The specified bucket does not exist
An error occurred (NoSuchBucket) when calling the ListObjectsV2 operation: The specified bucket does not exist

Note -e Extra variables have the highest precedence and override group variables. Fix: remove -e. If the bucket belongs to someone else (exists but no permission), the error becomes AccessDenied.

Fault C: wrong credential source (L2):
export AWS_ACCESS_KEY_ID=AKIAFAKEFAKEFAKE AWS_SECRET_ACCESS_KEY=fake
unset AWS_PROFILE
ansible-inventory -i inventories/aws --graph --flush-cache 2>&1 | tail -3      # inventory file specifies profile: lab → still succeeds
ansible localhost -m amazon.aws.aws_caller_info -a region=ca-central-1 2>&1 | grep -o "InvalidClientTokenId"
env | grep ^AWS_ ; unset AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY

The inventory plugin explicitly sets profile is unaffected, while modules that do not pass a profile are hijacked by the fake key in the environment variables—this is the typical reason why “some succeed and some fail on the same machine.”

(Optional) Fault D: agent offline (L5)—disassociate the instance profile:
ASSOC=$(aws ec2 describe-iam-instance-profile-associations --profile lab --region ca-central-1 \
  --filters Name=instance-id,Values=i-0a1b2c3d4e5f60002 --query 'IamInstanceProfileAssociations[0].AssociationId' --output text)
aws ec2 disassociate-iam-instance-profile --association-id "$ASSOC" --profile lab --region ca-central-1
# After a few minutes to tens of minutes (once the credentials held by the agent expire), PingStatus changes to ConnectionLost; walk through this with the troubleshooting tree
# Fix: rerun provision.yml (ec2_instance reassociates the instance profile), or:
aws ec2 associate-iam-instance-profile --instance-id i-0a1b2c3d4e5f60002 --iam-instance-profile Name=ansible-lab-ssm-profile --profile lab --region ca-central-1

Before the temporary credentials held by the agent expire, sessions may still work, so the symptoms appear with a delay; this is also a common cause of “permissions changed but did not take effect immediately” problems.

Cleanup: confirm lab.aws_ec2.yml has been restored, environment variables cleared, and the instance profile reassociated: ansible role_web -i inventories/aws -m ansible.builtin.ping All SUCCESS.

Case 1: an organization SCP causes “denied even though permission was granted”

Problem: In a new account, ec2_instance reports UnauthorizedOperation, the IAM policy is AdministratorAccess. Approach: Decode the authorization failure message and find that explicitDeny comes from an SCP: the organization forbids creating resources in non-approved regions, while the playbook’s region variable was overridden to us-east-1 (aws_ssm’s default region is also us-east-1). Fix: Explicitly set all region parameters and assert them; document the SCP.

Case 2: batch playbook fails at dawn: RequestLimitExceeded

Problem: The nightly inspection playbook runs against 500 hosts; delegate_to: localhost calls ec2_*_info per host, with forks=50. Approach: Instead, make a single call from localhost ec2_instance_info (with filters) to fetch all the data, then process it in memory; set botocore adaptive retries; add to tasks that must be called per host throttle. Effect: API calls drop from thousands to single digits.

Case 3: SSM intermittently disconnects in a proxied environment

Problem: The control node is inside a corporate network; some tasks report session timeouts. Approach:-vvvv The WebSocket is reset after it is established; the proxy has a 60-second idle timeout on long-lived connections. Fix: Proxy for ssmmessages.*.amazonaws.com relax the idle timeout and do not perform TLS decryption; or move the control node (AWX execution node) into the VPC.

Interactive troubleshooting tree: Ansible faults on AWS

Step through choices starting from the symptoms; finally, get diagnostic commands and fixes. Covers credentials, boto3 version, empty inventory, SSM connection failures (S3 permissions, proxy), AccessDenied, and throttling.

Supplement: more real errors

An error occurred (ExpiredToken) when calling the DescribeInstances operation: The security token included in the request is expired

Cause: The temporary credentials in use (assume role / manually exported session token) have expired; the most common case is expiry partway through a long-running play.

Fix: Use a profile so botocore refreshes automatically, instead of exporting temporary credentials as environment variables; sts_assume_role the duration_seconds must not exceed the role’s maximum session duration.

An error occurred (RequestLimitExceeded) when calling the DescribeInstances operation (reached max retries: 4): Request limit exceeded.

Cause: EC2 API throttling (token bucket); too much concurrency and repeated calls.

export AWS_RETRY_MODE=adaptive AWS_MAX_ATTEMPTS=10
ansible-playbook … -f 10

Fix: Merge queries, lower forks,throttle, use inventory caching, and use set_fact for lookups.

An error occurred (ThrottlingException) when calling the StartSession operation: Rate exceeded

Cause: A large number of hosts establish SSM sessions at the same time (one session per host; reconnects after failures amplify the problem).

Fix: Lower forks or serial, reduce ansible_aws_ssm_retries retry storms; check the related Systems Manager quotas in Service Quotas.

[WARNING]: Platform linux on host i-… is using the discovered Python interpreter at /usr/bin/python3.12 …

Cause: Interpreter auto-discovery notice (harmless). Over SSM, each discovery adds an extra round trip.

Fix: Set in group variables ansible_python_interpreter: /usr/bin/python3 (already set in this lesson).

Command-line exercise
1. Have ec2_instance_info tell you which APIs it calls.
ansible localhost -m amazon.aws.ec2_instance_info -a "profile=lab region=ca-central-1 debug_botocore_endpoint_logs=true" | jq .resource_actions
2. List all managed nodes in ca-central-1 that are not Online.
aws ssm describe-instance-information --profile lab --region ca-central-1 \
  --query "InstanceInformationList[?PingStatus!='Online'].[InstanceId,PingStatus,LastPingDateTime]" --output table
Scenario analysis
The same playbook succeeds on your laptop but fails in AWX: inventory sync succeeds, but the first task reports SessionManagerPlugin is not found. After fixing the plugin, it then reports Failed to import the required Python library (botocore and boto3). Analyze the cause and give a long-term plan.

In AWX, tasks run inside the execution environment (EE) container, independent of your laptop’s environment: inventory sync may have used the default EE containing boto3, while the EE used by the job template has neither the Session Manager plugin nor boto3. Long-term plan: build a custom EE with ansible-builder, declaring in execution-environment.yml the amazon.aws collection (its Python dependencies boto3/botocore get installed) and the Session Manager plugin (as a system dependency or an extra build step), pin the versions, and test in CI (Lesson 5).

Verified instructional videos

No verified video on “Ansible + AWS troubleshooting” was found. You can revisit Jeff Geerling Episode 11 from M2 (approach to debugging inventory plugins).

▶
Ansible 101 - Episode 11 - Dynamic Inventory and Smart Inventories — Jeff Geerling
English · 2020 · inventory plugins and debugging

Official documentation

Video storyboard script (about 90 seconds)

This courseware cannot directly generate video/MP3, so a storyboard and narration script are provided instead.

Shot 1 · 0–20s
Visual: seven colored blocks, labeled from bottom to top: Python, credentials, IAM, inventory, SSM, S3, instance.
Narration: Ansible faults in the cloud can be divided into seven layers. Confirm layer by layer from the bottom up.
Shot 2 · 20–50s
Visual: one “timeout” error splits into three paths, pointing to the agent, S3, and the proxy.
Narration: a timeout can have completely different root causes. First use start-session to separate the session layer from the transfer layer.
Shot 3 · 50–75s
Visual: a string of garbled authorization failure text is decoded into JSON, with explicitDeny highlighted.
Narration: when access is denied, first decode the message to see who it is, what is missing, and who denied it.
Shot 4 · 75–90s
Visual: the API call counter drops from one thousand to five.
Narration: throttling is almost always self-inflicted. Merge queries, lower concurrency, and cache results.
or score ≥ 70% on the “Quiz”

Module 8 · Cost, cleanup and self-test

53:00 – 60:00 · Ansible has no state, so you must write deletion yourself; find resources by tag, delete in reverse dependency order, then check again after deletion
7 minutesdestroy.ymlUnit prices are subject to the AWS pricing page★★★★☆
Learning objectives
  • List the billable items of this lesson and estimate costs: EC2 instances, public IPv4, EBS, S3, Secrets Manager (Session Manager itself adds no charge for EC2; Parameter Store standard parameters are free).
  • by dependency in reverse order Write idempotent destroy.yml, handling repeated runs where “the resource no longer exists”.
  • Use the tagging API and the CLI for leftover checks, and be able to name production mechanisms for preventing forgotten resources (budget alerts, expiry tags, scheduled cleanup).
Prerequisites: M3 resource inventory. Importance:★★★★☆

What: billable items of this lesson (ca-central-1, example unit prices)

ResourceQuantityBilling methodExample unit price (refer to the pricing page)Approx. per hour
EC2 t3.micro (Linux, on-demand)2Per second (minimum 60 seconds)≈ 0.0116 USD/hour≈ 0.023
Public IPv4 address2Per hour (all public IPv4 addresses charged since 2024-02)0.005 USD/hour0.010
EBS gp3 root volume 8 GiB2Per GB-month≈ 0.088 USD/GB-month≈ 0.002
Secrets Manager secret1Per secret per month + per 10,000 API calls≈ 0.40 USD/month≈ 0.0006
S3 relay bucket1Storage + requestsFiles are very small; can be ignored≈ 0
Parameter Store standard parameters3Standard tier is free00
Session Manager—No extra charge for EC2 instances00
Total≈ 0.036 USD/hour

The AWS free tier rules for new accounts were adjusted in 2025 (now a credit-based model); whether they cover the costs above depends on your account and the AWS Free Tier pagefor the authoritative answer. If you switch to the production-recommended private subnet approach,NAT gateway and interface VPC endpoints (ssm, ssmmessages, ec2messages, billed hourly per availability zone) often cost more than the instance itself—see the calculator on the “Animation” tab.

Why: why cleanup must be automated

Deleting manually in the console easily misses “invisible” resources: IAM roles and instance profiles (global), S3 buckets, secrets scheduled for deletion, unassociated EIPs, route tables. Ansible has no state, so destroy must explicitly list each resource type; the advantage is that, like provisioning, it is repeatable and reviewable.

How: deletion order (reverse of creation)

  1. EC2 instances (state: absent, wait for termination, release the network interface and public IP; the root volume is deleted with the instance by default).
  2. Instance profile → IAM role (the module handles removing and detaching managed policies).
  3. S3 buckets (force: true delete objects first).
  4. Secrets (recovery_window: 0 delete immediately) and parameters.
  5. Security groups (must wait for the instance’s network interfaces to be released) → route tables → subnets → IGW (detach first) → VPC.

When: preventing forgotten resources in production

  • AWS Budgets Budget alerts (for example, monthly 5 USD, email at 80%).
  • Tag resources with ExpiresAt / Owner tags, and run scheduled jobs that scan for expired resources (Ansible, Lambda, or AWS Config rules).
  • In sandbox accounts, use aws-nuke a tool that clears them periodically (always scope it to the account).
  • Hand long-term infrastructure to a tool with state (Terraform); deletion is terraform destroy.
Common misconceptions① “Stopping an instance means you stop paying”—after stopping, instance charges stop, but EBS and public IPv4 (if it is an EIP) are still billed; this lesson terminates directly. ② “Deleting a secret deletes it immediately”—by default there is a 7–30 day recovery window; a secret with the same name cannot be recreated during this period, and it is billed until it is actually deleted (refer to the official documentation). ③ “Deleting a VPC also deletes everything inside it”—at the API level DeleteVpc requires dependent resources (subnets, IGW, non-default security groups, network interfaces, etc.) to be deleted first; the console’s “one-click delete” deletes them one by one for you.

Dependency deletion diagram (reverse order)

① EC2 × 2terminate + wait ② Instance profile IAM role ③ S3 bucket force ④ Secret / parameters ⑤ Security group Route table Subnet IGW (detach) VPC After the instance is terminated, its network interface is released, and only then can the security group and subnet be deleted; the IGW must be detached from the VPC first
Figure 8-1 The task order in destroy.yml is the topological order of this diagram

Cost structure: public subnet approach vs private subnet approach

This lesson: public subnet + no inboundInstance + public IPv4 + EBSNo NAT, no interface endpointsSecurity: no inbound via security group + IAM≈ 0.04 USD/hour Production: private subnetInstance + EBS (no public IP)3 interface endpoints × AZ + S3 gateway endpoint (free)or NAT gateway (hourly + per-GB processing fee)fixed costs are clearly higher, but there is no public exposure
Figure 8-2 For learning environments, save money first; for production, minimize the exposure surface first

Interactive calculator: cost estimate

Adjust the parameters to view the estimates per hour / per day / per month. Unit prices are example values for ca-central-1 (order of magnitude around 2026-11), for comparing options only; actual figures should be taken from the AWS pricing pageand Cost Explorer.

Number of instances: 2
Instance type:
Running hours: 2 hours

destroy.yml (idempotent, can be rerun)

---
- name: Clean up AWS lab environment
  hosts: localhost
  connection: local
  gather_facts: false
  module_defaults:
    group/amazon.aws.aws:
      profile: "{{ aws_profile }}"
      region: "{{ aws_region }}"
  vars:
    vpc_cidr: 10.40.0.0/16
    subnet_cidr: 10.40.1.0/24
  tasks:
    - name: Confirm identity (prevent deleting in the wrong account)
      amazon.aws.aws_caller_info:
      register: me

    - name: Second confirmation
      ansible.builtin.pause:
        prompt: "Will delete resources in account {{ me.account }} / {{ aws_region }} with Project={{ lab_tags.Project }}; press Enter to continue, or Ctrl+C then A to cancel"
      when: not (auto_approve | default(false) | bool)

    - name: ① Terminate instances
      amazon.aws.ec2_instance:
        state: absent
        filters:
          "tag:Project": "{{ lab_tags.Project }}"
        wait: true

    - name: ② Instance profile
      amazon.aws.iam_instance_profile:
        name: "{{ lab_prefix }}-ssm-profile"
        state: absent

    - name: ② IAM role
      amazon.aws.iam_role:
        name: "{{ lab_prefix }}-ssm-role"
        state: absent

    - name: ③ S3 bucket (including objects)
      amazon.aws.s3_bucket:
        name: "{{ lab_prefix }}-ssm-{{ me.account }}-{{ aws_region }}"
        state: absent
        force: true

    - name: ④ Secret (delete immediately)
      community.aws.secretsmanager_secret:
        profile: "{{ aws_profile }}"
        region: "{{ aws_region }}"
        name: "{{ lab_prefix }}/myapp"
        state: absent
        recovery_window: 0

    - name: ④ Parameters
      community.aws.ssm_parameter:
        profile: "{{ aws_profile }}"
        region: "{{ aws_region }}"
        name: "/{{ lab_prefix }}/myapp/{{ item }}"
        state: absent
      loop: [version, greeting, port]

    - name: Find VPC
      amazon.aws.ec2_vpc_net_info:
        filters:
          "tag:Name": "{{ lab_prefix }}-vpc"
          cidr: "{{ vpc_cidr }}"
      register: vpcs

    - name: ⑤ Network resources (when VPC exists)
      when: vpcs.vpcs | length > 0
      vars:
        vpc_id: "{{ vpcs.vpcs[0].id }}"
      block:
        - name: Security groups
          amazon.aws.ec2_security_group:
            name: "{{ lab_prefix }}-sg"
            vpc_id: "{{ vpc_id }}"
            state: absent

        - name: Find route tables for this lab
          amazon.aws.ec2_vpc_route_table_info:
            filters:
              vpc-id: "{{ vpc_id }}"
              "tag:Project": "{{ lab_tags.Project }}"
          register: rts

        - name: Route tables
          amazon.aws.ec2_vpc_route_table:
            vpc_id: "{{ vpc_id }}"
            route_table_id: "{{ item.id }}"
            lookup: id
            state: absent
          loop: "{{ rts.route_tables }}"
          loop_control:
            label: "{{ item.id }}"

        - name: Subnets
          amazon.aws.ec2_vpc_subnet:
            vpc_id: "{{ vpc_id }}"
            cidr: "{{ subnet_cidr }}"
            state: absent

        - name: Internet gateway
          amazon.aws.ec2_vpc_igw:
            vpc_id: "{{ vpc_id }}"
            state: absent

        - name: VPC
          amazon.aws.ec2_vpc_net:
            name: "{{ lab_prefix }}-vpc"
            cidr_block: "{{ vpc_cidr }}"
            state: absent

    - name: Clear inventory cache
      ansible.builtin.file:
        path: ~/.cache/ansible/aws_ec2
        state: absent
cd ~/ansible-lab
ansible-playbook -i inventories/aws playbooks/aws/destroy.yml
ansible-playbook -i inventories/aws playbooks/aws/destroy.yml -e auto_approve=true   # run again; everything should be ok/skipped
TASK [① Terminate instances] ****************************************************************
changed: [localhost]
TASK [② Instance profile] ************************************************************
changed: [localhost]
…
TASK [VPC] *************************************************************************
changed: [localhost]
PLAY RECAP *************************************************************************
localhost : ok=17  changed=12  unreachable=0  failed=0  skipped=0  rescued=0  ignored=0

Leftover check (fallback)

P=lab; R=ca-central-1
aws resourcegroupstaggingapi get-resources --tag-filters Key=Project,Values=ansible-lab \
  --profile $P --region $R --query 'ResourceTagMappingList[].ResourceARN'
aws ec2 describe-instances --filters Name=tag:Project,Values=ansible-lab Name=instance-state-name,Values=pending,running,stopping,stopped \
  --profile $P --region $R --query 'Reservations[].Instances[].InstanceId'
aws ec2 describe-addresses --profile $P --region $R --query 'Addresses[].PublicIp'
aws ec2 describe-volumes --filters Name=status,Values=available --profile $P --region $R --query 'Volumes[].VolumeId'
aws iam get-role --role-name ansible-lab-ssm-role --profile $P 2>&1 | head -1
aws s3 ls --profile $P | grep ansible-lab || echo "no lab buckets"
aws secretsmanager list-secrets --include-planned-deletion --filters Key=name,Values=ansible-lab --profile $P --region $R --query 'SecretList[].Name'
[]
[]
[]
[]
An error occurred (NoSuchEntity) when calling the GetRole operation: The role with name ansible-lab-ssm-role cannot be found.
no lab buckets
[]

How to verify: All of the above should be empty / NoSuchEntity. The tagging API may still return deleted resources for a short time after deletion (eventual consistency), so check again a few minutes later. Common errors: Deleting a security group reports DependencyViolation happens because the instance has not fully terminated yet (wait: true avoids this); if deleting a subnet reports the same error, check whether leftover network interfaces remain (describe-network-interfaces --filters Name=subnet-id,…).

Lab 8: Clean up and verify zero leftovers (about 6 minutes)

(Optional) first check today’s costs in Cost Explorer (cost data is delayed and may not show yet):
aws ce get-cost-and-usage --profile lab --time-period Start=$(date -u +%F),End=$(date -u -d tomorrow +%F) \
  --granularity DAILY --metrics UnblendedCost --query 'ResultsByTime[0].Total.UnblendedCost'

Cost Explorer API charges a small fee per request (see official pricing); run it only once.

Run destroy.yml (see the “Commands” tab); after confirming the account ID in the prompt is correct, press Enter.
Run again: -e auto_approve=true, there should be no failures—this proves destroy is also idempotent.
Leftover check: run the fallback check commands on the “Commands” tab; everything should be empty.
Set up budget alerts (one-time, strongly recommended):
ACC=$(aws sts get-caller-identity --profile lab --query Account --output text)
aws budgets create-budget --account-id "$ACC" --profile lab \
  --budget '{"BudgetName":"lab-monthly-5usd","BudgetLimit":{"Amount":"5","Unit":"USD"},"TimeUnit":"MONTHLY","BudgetType":"COST"}' \
  --notifications-with-subscribers '[{"Notification":{"NotificationType":"ACTUAL","ComparisonOperator":"GREATER_THAN","Threshold":80,"ThresholdType":"PERCENTAGE"},"Subscribers":[{"SubscriptionType":"EMAIL","Address":"you@example.com"}]}]'

Replace the email with your address; AWS Budgets has a small free allowance, and anything beyond it follows official pricing.

Local cleanup: env | grep ^AWS_ Confirm there are no leftovers; optionally aws sso logout. Keep the project files for Lesson 5 (CI/CD will reuse these playbooks).

Case 1: automatically clean up expired test environments every night

Problem: Developers forget to delete branch environments, and the month-end bill doubles. Approach: During provisioning, apply ExpiresAt=2026-11-20 tags; an AWX scheduled job runs ec2_instance_info to find expired instances, and by Project tag, calls the matching destroy.yml and notifies the Owner on Slack. Limitation: IAM, S3, and other non-EC2 resources must also get the same tags and be included in the scan.

Case 2: DependencyViolation interrupts cleanup

Problem: destroy fails when deleting the security group, so the VPC is not deleted; the next day a NAT gateway is found still billing. Approach: Add a wait after instance termination wait: true; put hourly-billed resources such as NAT gateways, EIPs, and VPC endpoints at the very start of destroy (when they have no dependencies); on failure, block/rescue emit an alert instead of exiting silently.

Case 3: cost attribution

Problem: Finance requires cloud costs to be allocated by team. Approach: Activate in Billing Project,Owner as cost allocation tags; Ansible’s lab_tags injects them uniformly; combine with an Organizations tag policy to enforce them as required. Limitation: Cost allocation tags only apply to charges incurred after activation.

Common errors and fixes

An error occurred (DependencyViolation) when calling the DeleteSecurityGroup operation: resource sg-… has a dependent object

Cause: a network interface still references the security group (the instance has not fully terminated, or an ENI was created by another service).

aws ec2 describe-network-interfaces --filters Name=group-id,Values=sg-xxxx --profile lab --region ca-central-1 --query 'NetworkInterfaces[].[NetworkInterfaceId,Status,Description]'

Fix: Wait for the instance to terminate, then rerun destroy.yml (idempotent).

An error occurred (BucketNotEmpty) when calling the DeleteBucket operation: The bucket you tried to delete is not empty

Cause: not set force: true, or the bucket has versioning enabled (historical versions / delete markers exist).

Fix:force: true; a versioned bucket must have all versions deleted (aws s3api list-object-versions). This is one of the reasons this lesson recommends that the relay bucket not use versioning.

An error occurred (DeleteConflict) when calling the DeleteRole operation: Cannot delete entity, must remove roles from instance profile first.

Cause: Manual deletion in the wrong order (the instance profile still contains the role).

aws iam remove-role-from-instance-profile --instance-profile-name ansible-lab-ssm-profile --role-name ansible-lab-ssm-role --profile lab
aws iam delete-instance-profile --instance-profile-name ansible-lab-ssm-profile --profile lab

Fix: Follow the order in destroy.yml: instance profile first, then the role.

destroy succeeded, but the next day the bill still shows EC2 charges

Cause: The filter did not cover all instances (for example, someone manually created an instance without the Project tag), resources were created in another region, or cost data is delayed.

Fix: Review Cost Explorer grouped by region and service; run leftover checks in all regions; use an SCP to restrict the allowed regions.

Command-line exercise
1. List the ARNs of all resources tagged Project=ansible-lab in ca-central-1 of the current account.
aws resourcegroupstaggingapi get-resources --tag-filters Key=Project,Values=ansible-lab --profile lab --region ca-central-1 --query 'ResourceTagMappingList[].ResourceARN'
2. Run destroy.yml non-interactively.
ansible-playbook -i inventories/aws playbooks/aws/destroy.yml -e auto_approve=true
Scenario analysis
The team wants to use this lesson’s approach in production: instances must have no public IP, all operations must be auditable, and costs must be controllable. Provide a modification checklist and the main cost changes.

① Private subnet, remove assign_public_ip; ② create interface endpoints for ssm, ssmmessages, and ec2messages (multi-AZ) and an S3 gateway endpoint (free); add logs and kms endpoints if you need session logs or KMS—fixed costs increase by “number of endpoints × AZs × hours”; ③ if instances still need internet access (apt, PyPI), choose a NAT gateway (hourly fee + data processing fee) or an internal mirror / artifact repository; ④ in Session Manager preferences, enable S3/CloudWatch session logs and KMS encryption, and enable S3 data events in CloudTrail; ⑤ relay bucket with SSE-KMS, no versioning, lifecycle expiration, and a bucket policy that allows only the deployment role; ⑥ change the control node to an AWX/AAP execution node inside the VPC, using an instance profile + assume role; ⑦ Budgets + cost allocation tags.

Self-check list for this lesson (tick when done)

Verified instructional videos

No verified video on “cleaning up AWS resources with Ansible / cloud cost control” was found; please use the storyboard below.

▶
Ansible in 100 Seconds — Fireship
English · about 2 minutes · quick review of core Ansible concepts at the end of the course

Official documentation

Video storyboard script (about 70 seconds)

This courseware cannot directly generate video/MP3, so a storyboard and narration script are provided instead.

Shot 1 · 0–20s
Visual: a meter ticking over time, with a small table each for the instance, public IP, disk, and secret.
Narration: cloud resources bill by the hour, so delete them as soon as you finish learning.
Shot 2 · 20–50s
Visual: the dependency graph goes dark from right to left: instance, IAM, bucket, secret, security group, route table, subnet, gateway, VPC.
Narration: deletion order is the reverse of creation. Ansible has no state, so every resource type must be listed explicitly.
Shot 3 · 50–70s
Visual: leftover-check commands all return empty arrays, plus a budget alert email icon.
Narration: check again after deleting, then set a budget alert as one more safety net.
or score ≥ 70% on the “Quiz”

Command quick reference

amazon.aws · aws_ec2 · aws_ssm · lookup plugins · troubleshooting · cleanup
After classamazon.aws 12.1.0

1. Installation and versions

pipx inject ansible boto3 botocore
ansible-galaxy collection install -r requirements.yml -p ./collections
ansible-galaxy collection list amazon.aws
ansible --version | grep -E "core|python"
ansible-doc -t connection amazon.aws.aws_ssm

2. Credentials

aws configure sso --profile lab
aws sso login --profile lab
aws sts get-caller-identity --profile lab
env | grep ^AWS_
aws configure list --profile lab
ansible localhost -m amazon.aws.aws_caller_info -a "profile=lab region=ca-central-1"

3. Dynamic inventory

ansible-inventory -i inventories/aws --graph
ansible-inventory -i inventories/aws --graph --flush-cache
ansible-inventory -i inventories/aws --host i-0a1b2c3d4e5f60001
ansible 'role_web:&env_lab' -i inventories/aws --list-hosts
ansible-doc -t inventory amazon.aws.aws_ec2

4. SSM connection

aws ssm describe-instance-information --profile lab --region ca-central-1 \
  --query 'InstanceInformationList[].[InstanceId,PingStatus]' --output text
aws ssm start-session --target i-0a1b2c3d4e5f60001 --profile lab --region ca-central-1
ansible role_web -i inventories/aws -m ansible.builtin.ping
ansible role_web -i inventories/aws -b -m ansible.builtin.command -a id
aws ssm start-session --target i-… --document-name AWS-StartPortForwardingSession \
  --parameters '{"portNumber":["8000"],"localPortNumber":["18000"]}'

5. Secrets and parameters

{{ lookup('amazon.aws.secretsmanager_secret', 'ansible-lab/myapp.secret_key',
           nested=true, region='ca-central-1', profile='lab') }}
{{ lookup('amazon.aws.ssm_parameter', '/ansible-lab/myapp/', bypath=true,
           recursive=true, shortnames=true, region='ca-central-1', profile='lab') }}
{{ lookup('amazon.aws.ssm_parameter', '/x/y', on_missing='skip') | default('d', true) }}

6. Playbook flow

ansible-playbook -i inventories/aws playbooks/aws/whoami.yml
ansible-playbook -i inventories/aws playbooks/aws/provision.yml
ansible-playbook -i inventories/aws playbooks/aws/secrets.yml
ansible-playbook -i inventories/aws playbooks/aws/deploy-myapp.yml
ansible-playbook -i inventories/aws playbooks/aws/destroy.yml -e auto_approve=true

7. Troubleshooting

ansible-playbook … -vvvv 2>&1 | tee /tmp/run.log
ansible localhost -m amazon.aws.ec2_instance_info \
  -a "profile=lab region=ca-central-1 debug_botocore_endpoint_logs=true" | jq .resource_actions
aws sts decode-authorization-message --encoded-message "$MSG" --query DecodedMessage --output text | jq .
export AWS_RETRY_MODE=adaptive AWS_MAX_ATTEMPTS=10

8. Leftover checks

aws resourcegroupstaggingapi get-resources --tag-filters Key=Project,Values=ansible-lab \
  --profile lab --region ca-central-1 --query 'ResourceTagMappingList[].ResourceARN'
aws iam get-role --role-name ansible-lab-ssm-role --profile lab
aws s3 ls --profile lab | grep ansible-lab
aws secretsmanager list-secrets --include-planned-deletion --profile lab --region ca-central-1

Quick troubleshooting table

Symptom / errorLayerFirst commandCommon fix
Failed to import … botocore and boto3L1ansible --versionpipx inject ansible boto3 botocore
requires boto3 >= 1.38.23L1Print the version in Ansible’s Pythonpipx inject --force …
Unable to locate credentials / ExpiredToken / InvalidClientTokenIdL2env | grep ^AWS_Pass the profile; aws sso login; clear leftover key
AccessDenied / UnauthorizedOperationL3aws_caller_info + decode the messageAdd permissions; check SCP, permission boundary, KMS
Empty inventoryL4ansible-inventory --graph --flush-cache -vvvsuffix, region, tag case, running filter
TargetNotConnectedL5describe-instance-informationInstance role, outbound 443, agent
SessionManagerPlugin is not foundL5command -v session-manager-pluginInstall the plugin or configure ansible_aws_ssm_plugin
PutObject AccessDenied / NoSuchBucketL6aws s3 ls s3://bucketBucket name, bucket policy, KMS permissions
Module transfer hangs and times outL6inside the session curl -sI https://s3.ca-central-1.amazonaws.comOutbound 443 / S3 gateway endpoint / addressing style
RequestLimitExceeded / ThrottlingExceptionL3/L5CloudTrail errorCodeadaptive retries, lower forks, throttle, cache
DependencyViolation (during cleanup)—describe-network-interfacesRerun destroy after the instance terminates

Recommended configuration snippet

plugin: amazon.aws.aws_ec2
profile: lab
regions: [ca-central-1]
filters:
  instance-state-name: running
  tag:Project: ansible-lab
hostnames: [instance-id]
compose:
  ansible_host: instance_id
keyed_groups:
  - { key: tags.Role, prefix: role }
  - { key: tags.Env, prefix: env }
cache: true
cache_plugin: ansible.builtin.jsonfile
cache_connection: ~/.cache/ansible/aws_ec2
cache_timeout: 300
ansible_connection: amazon.aws.aws_ssm
ansible_aws_ssm_region: ca-central-1
ansible_aws_ssm_profile: lab
ansible_aws_ssm_bucket_name: ansible-lab-ssm-111122223333-ca-central-1
ansible_aws_ssm_bucket_sse_mode: AES256
ansible_aws_ssm_timeout: 120
ansible_python_interpreter: /usr/bin/python3
- hosts: localhost
  connection: local
  gather_facts: false
  module_defaults:
    group/amazon.aws.aws:
      profile: "{{ aws_profile }}"
      region: "{{ aws_region }}"

Integrated lab + final quiz

EC2 without SSH: create the environment from scratch → dynamic inventory → deploy myapp via SSM → cloud secrets → verify → cleanup, without opening any inbound port at any point
After class ≈ 40 minutesCosts about 0.03 USDIntegrate all modules
Scenario Security team rule: newly launched myapp instances must not open any inbound port or use SSH keys, all secrets must be stored in Secrets Manager, and all resources must carry Project tags and be removable with one command. In ca-central-1, use one set of playbooks to complete the whole process from creation to cleanup, and leave auditable evidence.
Cost: About 0.04 USD/hour; completing all steps usually costs less than 0.1 USD. Permissions: See Module 0. Risk: Control node credentials and S3 relay files; be sure to run Step 8 when you finish.
Pre-check (M1)
cd ~/ansible-lab
aws sso login --profile lab
ansible-playbook -i inventories/aws playbooks/aws/whoami.yml
env | grep ^AWS_ || true
command -v session-manager-plugin && ansible-galaxy collection list amazon.aws | tail -1
Create the environment (M3):
ansible-playbook -i inventories/aws playbooks/aws/provision.yml
ansible-playbook -i inventories/aws playbooks/aws/provision.yml | tail -1    # changed=0
Verify zero inbound and IMDSv2 (M3):
aws ec2 describe-security-groups --profile lab --region ca-central-1 --filters Name=group-name,Values=ansible-lab-sg \
  --query 'SecurityGroups[0].IpPermissions'
aws ec2 describe-instances --profile lab --region ca-central-1 --filters Name=tag:Project,Values=ansible-lab Name=instance-state-name,Values=running \
  --query 'Reservations[].Instances[].[InstanceId,KeyName,MetadataOptions.HttpTokens]' --output text
[]
i-0a1b2c3d4e5f60001	None	required
i-0a1b2c3d4e5f60002	None	required
Inventory and SSM (M2, M4):
ansible-inventory -i inventories/aws --graph --flush-cache
aws ssm describe-instance-information --profile lab --region ca-central-1 --query 'InstanceInformationList[].[InstanceId,PingStatus]' --output text
ansible role_web -i inventories/aws -m ansible.builtin.ping
Secrets and deployment (M5, M6):
ansible-playbook -i inventories/aws playbooks/aws/secrets.yml
ansible-playbook -i inventories/aws playbooks/aws/deploy-myapp.yml
ansible role_web -i inventories/aws -m ansible.builtin.uri -a "url=http://127.0.0.1:8000/healthz return_content=true" | grep -E "SUCCESS|content"
Audit evidence (M4, M7):
aws cloudtrail lookup-events --lookup-attributes AttributeKey=EventName,AttributeValue=StartSession \
  --max-results 5 --profile lab --region ca-central-1 --query 'Events[].[EventTime,Username]' --output table
aws s3 ls "s3://ansible-lab-ssm-$(aws sts get-caller-identity --profile lab --query Account --output text)-ca-central-1/" --recursive --profile lab | wc -l

In CloudTrail you should see StartSession calls made by your identity; the S3 relay bucket should contain 0 objects after the play ends.

One configuration-driven release (M5, M6):
aws ssm put-parameter --name /ansible-lab/myapp/version --value v2 --overwrite --profile lab --region ca-central-1
ansible-playbook -i inventories/aws playbooks/aws/deploy-myapp.yml
ansible role_web -i inventories/aws -m ansible.builtin.uri -a "url=http://127.0.0.1:8000/ return_content=true" | grep -o 'v2' | sort | uniq -c
Cleanup and leftover check (M8):
ansible-playbook -i inventories/aws playbooks/aws/destroy.yml
ansible-playbook -i inventories/aws playbooks/aws/destroy.yml -e auto_approve=true
aws resourcegroupstaggingapi get-resources --tag-filters Key=Project,Values=ansible-lab --profile lab --region ca-central-1 --query 'ResourceTagMappingList[].ResourceARN'
aws iam get-role --role-name ansible-lab-ssm-role --profile lab 2>&1 | grep -c NoSuchEntity
Acceptance checklist

Open-ended self-test (answer first, then expand the reference answer)

1. Why does the AWS module write hosts: localhost? Whose credentials do it and the SSM connection plugin each use?

AWS modules call the AWS API directly through boto3 on the control node; they do not log in to any host and use the control node’s credential chain. The SSM connection plugin likewise uses the control node’s credentials to call StartSession and S3; the SSM Agent on the instance communicates with the SSM service using the instance role (or DHMC).

2. Describe the full process by which aws_ssm executes one task, and point out the two most common breakpoints.

Render AnsiballZ → StartSession → session-manager-plugin WebSocket → Agent starts a shell → mkdir temp directory → PutObject to S3 → presigned URL + instance curl download → python3 execution (can become) → JSON returned through the session → clean up the directory and S3 object. Common breakpoints: agent not registered (TargetNotConnected); S3 relay (the control node lacks bucket permissions, or the instance cannot reach S3).

3. In the aws_ec2 inventory, how should hostnames and compose’s ansible_host be set for SSM and for SSH respectively?

SSM: use instance-id (or a readable name) for hostnames,ansible_host must be the instance ID. SSH: hostnames can use tag:Name,ansible_host set to the private IP (via a bastion or VPN) or the public DNS name.

4. What is the key difference between Ansible creating cloud resources and Terraform? How does this lesson make up for Ansible’s shortcomings?

Ansible has no state: idempotency relies on looking up by name or tag, and deletion must be written explicitly state: absent, with dependency order guaranteed by task order. This lesson compensates with unified tags, explicit filters, a dedicated idempotent destroy.yml, and leftover checks; for long-term infrastructure, Terraform is recommended.

5. Should secrets be read by Ansible at deployment time and written to the instance, or read by the application at runtime? What are the pros and cons of each?

Ansible reads: the application needs no SDK, but the secret passes through the control node, the S3 relay, and session logs, and after rotation you must redeploy. The application reads: the secret never passes through Ansible, rotation is supported natively, and permissions can be scoped precisely to the instance role; but the application must integrate an SDK and handle caching and failures. For secrets that need rotation, prefer the latter.

6. In production, what changes would you make to the approach in this lesson?

Private subnets + SSM/S3 VPC endpoints; SSE-KMS relay bucket + lifecycle rules + strict bucket policy; session logging and KMS encryption; control node placed inside the VPC (AWX/AAP) using an instance profile + assume role; least-privilege policies (tag conditions); rolling releases integrated with an ALB; dependencies baked into the AMI to shorten SSM deployment time; Budgets, cost allocation tags, and automatic cleanup of expired resources.

Final quiz (12 questions, covering all modules)

Source and version notes

Verification basis for the technical facts in this lesson (verified on 2026-11-15)
TopicVerified conclusionSource (accessed 2026-11-15)
ansible-core / Ansible packagecore 2.21 (control node Python 3.12–3.14); Ansible 14.x is based on core 2.21Unified course standard (verified against the docs.ansible.com release and maintenance page)
amazon.aws versionLatest on Galaxy is 12.1.0; the “latest” documentation page on docs.ansible.com shows 11.5.1 (shipped with the Ansible package)Galaxy amazon.aws · Collection index
amazon.aws dependenciesansible-core ≥ 2.18; Python ≥ 3.9 (3.9 is deprecated; versions after 2027-04-01 will require 3.10+); 12.x requires boto3/botocore ≥ 1.38.23; SDK support policy is “SDKs within 12 months before the major release”; 12.0.0 removed the placement_group and tenancy parameters of ec2_instanceamazon.aws README · CHANGELOG
community.awsLatest on Galaxy is 12.0.0; includes modules such as secretsmanager_secret, ssm_parameter, and s3_lifecycleGalaxy community.aws · Collection index
aws_ssm connection pluginName amazon.aws.aws_ssm, moved in from community.aws in 10.0.0 (first seen in community.aws 1.0.0); requires the SSM Agent, the Session Manager plugin on the control node, curl on the instance, and S3 accessible from both sides; the instance needs no S3 IAM credentials (the control node generates the presigned URL); the control node needs s3:GetObject/PutObject/ListBucket/DeleteObject/GetBucketLocation; region defaults to us-east-1; ssm_timeout defaults to 60 and reconnection_retries defaults to 3; remote_user and ansible_user are not supported; S3 files are prefixed with the instance ID and deleted when the run ends; options were renamed in 11.3.0/11.4.0 (old names remain as aliases)aws_ssm connection
aws_ec2 inventory pluginThe file name must end with aws_ec2.yml/yaml; regions defaults to all regions; filters defaults to {} (running state is not filtered automatically); cache_plugin defaults to memory and cache_timeout defaults to 3600; include/exclude_filters, use_ssm_inventory, iam_role_arn (alias assume_role_arn), hostvars_prefixaws_ec2 inventory
ec2_instancenetwork Deprecated (to be removed after 2026-12-01); use network_interfaces (added in 8.2.0); metadata_options.http_tokens; iam_instance_profile (alias instance_role)ec2_instance
Migration of ec2_vpc_*9.0.0 moved ec2_vpc_nacl, peering, vgw, vpn, and others in from community.aws; the instance profile option of iam_role was deprecated in 8.2.0 in favor of iam_instance_profileCHANGELOG
Lookup pluginssecretsmanager_secret (alias aws_secret) and ssm_parameter (alias aws_ssm) were renamed in 6.0.0; options nested/join/bypath/on_missing/on_denied/on_deleted; ssm_parameter’s droppath was added in 8.2.0, and decrypt defaults to truesecretsmanager_secret · ssm_parameter
boto3 credentials and retriesCredential chain order; standard/adaptive retry modesCredentials · Retries
Session Manager / SSMPlugin install path, VPC endpoints (ssm, ssmmessages, ec2messages, S3 gateway), DHMC, port forwarding documentationSession Manager · VPC endpoints
PricingExample unit prices (t3.micro, public IPv4 0.005 USD/hour, gp3, Secrets Manager 0.40 USD/secret/month), for order-of-magnitude reference onlyAWS Pricing

Video verification notes

The following videos had their titles and channels verified on 2026-11-15 using the YouTube oEmbed API: Fireship “Ansible in 100 Seconds” (xRMPKQweySE); TechWorld with Nana “What is Ansible | Ansible Playbook explained | Ansible Tutorial for Beginners” (1id6ERvfozo); NetworkChuck “you need to learn Ansible RIGHT NOW!! (Linux Automation)” (5hycyr-8EKs); Jeff Geerling “Ansible 101 - Episode 11 - Dynamic Inventory and Smart Inventories” (_rDzMYp-fBs; the AWS inventory plugin demo is around 41:04, timestamp taken from the author’s blog chapter list), “Ansible 101 - Episode 6 - Ansible Vault and Roles” (JFweg2dUvqM), and “Ansible 101 - Episode 9 - First 5 min server security with Ansible” (gV_16dU7XjM). oEmbed does not return durations or publication dates, so the cards only show known information. For the aws_ssm connection plugin, Secrets Manager lookups, creating VPC/EC2 with amazon.aws, and cloud troubleshooting and cost cleanup,no verified dedicated videos were found, so storyboard scripts are provided. All videos are in English and were recorded before amazon.aws 12.x, so module names and options follow this lesson.

Voice narration notes

The “Audio” tab uses the browser’s Web Speech API (en-US) to read the narration script aloud, with English terms pronounced in en-US; the result depends on the voice packs installed on the system. This courseware cannot embed MP3; if you need offline audio, give the narration script to a TTS service to generate it.

Known limitations

  • The commands in this courseware have not been run in a real AWS account; account IDs, instance IDs, IPs, session IDs, version numbers, times, and durations in the “expected output” are example values.
  • The internal command text of the aws_ssm plugin (wrapper markers, curl arguments) is illustrative; API names and order follow the official documentation; -vvv output wording changes between versions. Whether an instance needs S3 IAM permissions depends on the plugin version; this lesson follows the current documentation (presigned URL, no instance S3 permissions needed).
  • Prices are order-of-magnitude examples and were not checked item by item against the ca-central-1 pricing page for 2026-11; free tier rules depend on the actual account.
  • The default SSM session user ssm-user and its sudo configuration are Session Manager default behavior; if an organization changes session preferences or the session document (runAs), the results will differ.
  • Some original error messages (for example, the version-too-low prompt or the ResourceNotFound text of lookup plugins) may differ slightly in wording in your environment.
  • If the myapp role variable names in Lesson 3 (Azure) and Lesson 2 differ from those in this lesson, align them with the minimal role provided in M6.
  • Times and counts in the animations are illustrative values, used to explain the mechanism.