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.
*.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.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.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.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.| # | Time | Module | Core content | Animation / interaction | Lab (AWS ca-central-1) |
|---|---|---|---|---|---|
| 0 | Before class | Warm-up and AWS setup | AWS CLI v2, SSO login, Session Manager plugin, collection and boto3, project directory and variables | Environment self-check checklist | aws sts get-caller-identity Success |
| 1 | 00–06 | amazon.aws and authentication | Collection structure, boto3/botocore version requirements, credential chain, SSO profile, assume role,module_defaults | Credential chain lookup simulator | Calling with SSO profile and assume role aws_caller_info |
| 2 | 06–13 | aws_ec2 dynamic inventory | File naming rules, filters / include / exclude, keyed_groups, hostnames, compose, caching | EC2 instances → inventory group generator | Write out lab.aws_ec2.yml and ansible-inventory --graph |
| 3 | 13–22 | Creating AWS resources with Ansible | VPC, subnets, IGW, route tables, security groups, IAM roles and instance profiles, EC2 (IMDSv2), tags and idempotency | Create resources step by step along the dependency chain | provision.yml Create 2 EC2 instances |
| 4 | 22–30 | Managing without SSH: the SSM connection plugin | Prerequisites (S3 bucket, SSM Agent, instance role, Session Manager plugin), connection variables, become, performance and limits | Core animation: The full run of one task through S3 + SSM | ansible -m ping Via SSM |
| 5 | 30–37 | Secrets: Secrets Manager and SSM parameters | Two lookup plugins, running on the control node, on_missing/on_denied, KMS, comparison with Ansible Vault, no_log | Demo: when lookup plugins are evaluated | Create a secret and a parameter and read them in a play |
| 6 | 37–44 | Configuring EC2 and deploying the app | Applying the myapp role to EC2 via SSM, become and ssm-user, rolling deployment serial, health checks | Rolling deployment timeline | Deploy myapp and verify it on the instance /healthz |
| 7 | 44–53 | Cloud troubleshooting in practice | Credentials, boto3 version, empty inventory, SSM connection failures (S3 permissions, proxy), AccessDenied, throttling | Interactive troubleshooting tree | Deliberately cause 3 faults and fix them |
| 8 | 53–60 | Cost, cleanup and self-test | Billable items (EC2, public IPv4, EBS, S3, Secrets Manager, KMS), cleanup by tag, cleanup order, self-test | Cost calculator | destroy.yml + leftover check |
| — | After class | Cheat sheet · Capstone lab | Deploy myapp to EC2 without SSH, then clean up | Final quiz (12 questions) | Capstone lab |
| Target skills | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | Key commands | Labs |
|---|---|---|---|---|---|---|---|---|---|---|
| Install amazon.aws and boto3, manage short-term credentials | ✓ | · | · | · | · | · | ✓ | · | ansible-galaxy collection install,aws sso login | M1 lab |
| Dynamic inventory and grouping by tag | · | ✓ | · | ✓ | · | ✓ | ✓ | · | ansible-inventory -i lab.aws_ec2.yml --graph | M2 lab |
| Idempotent creation of network and compute resources | · | · | ✓ | · | · | · | · | ✓ | ansible-playbook provision.yml | provision.yml |
| IAM roles, instance profiles and least privilege | ✓ | · | ✓ | ✓ | ✓ | · | ✓ | · | iam_role,iam_instance_profile | M3 / M4 labs |
| Manage instances without SSH via SSM | · | ✓ | · | ✓ | · | ✓ | ✓ | · | ansible_connection: amazon.aws.aws_ssm | M4 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_connection | M6 lab |
| Cloud fault diagnosis | ✓ | ✓ | · | ✓ | ✓ | · | ✓ | · | -vvvv,aws ssm describe-instance-information | M7 lab |
| Cost control and complete cleanup | · | · | ✓ | · | · | · | · | ✓ | destroy.yml,resourcegroupstaggingapi | M8 lab |
| Topic | Why not in this lesson | Where to learn |
|---|---|---|
| Azure VMs, azure.azcollection, azure_rm dynamic inventory | Covered in the previous lesson; this lesson mirrors its structure one-to-one | Hour 3 |
| Managing EKS / ECS and CloudFormation modules with Ansible | Container orchestration and declarative IaC tools are a better fit | K8s lesson · Terraform lesson(Lesson 4, AWS) |
| GitHub Actions OIDC, AWS credential types in AWX, EDA listening to SQS/CloudTrail | Belongs to the automation operations topic | Hour 5 |
| Multi-tier architecture (nginx + 2 app nodes + PostgreSQL) | This lesson deploys only the single-tier myapp | Hour 6 |
| Windows EC2 (PowerShell via SSM) | Time is limited, so it is mentioned only briefly in M4 ansible_shell_type: powershell | Official aws_ssm examples |
| VPC interface endpoints (PrivateLink), fully offline SSM in private subnets | Each endpoint is billed hourly; this lesson uses public subnets with no inbound rules to keep costs down | M4 “production case” gives the key configuration points;AWS docs |
destroy.yml, then confirm with the leftover-check command in M8.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.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).aws configure, but delete the access key after class.Project=ansible-lab, and look them up by tag when cleaning up.| Item | Lesson 3 (Azure) | Lesson 4 (AWS) |
|---|---|---|
| Collection | azure.azcollection | amazon.aws (+ a few community.aws) |
| Python dependencies | Collection's bundled requirements (a long list of Azure SDK packages) | Only needs boto3 + botocore |
| Authentication | az login / service principal / managed identity | SSO profile / assume role / instance profile |
| Dynamic inventory | *.azure_rm.yml | *.aws_ec2.yml |
| Connection method | SSH (or Azure Bastion) | SSM Session Manager, zero inbound ports |
| Secrets | Key Vault lookup | Secrets Manager / SSM Parameter Store lookup |
| Unchanged | Control node,ansible.cfg,roles/myapp, playbook syntax, idempotency concepts,--check --diff | |
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
amazon.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.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"
}
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
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.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
| Category | Description |
|---|---|
| IAM permissions | The 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 cost | 2 × 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 risks | Lesson 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. |
| Cleanup | Use the M8 destroy.yml; fallback commands are on the M8 “Commands” page. |
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 .
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.
amazon.aws (Red Hat supported, core services) from community.aws (community-maintained, long-tail services), and know the FQCN changes caused by module migration.module_defaults to pass profile/region uniformly, or use sts_assume_role to temporarily switch roles.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.
| Item | amazon.aws (12.1.0) | community.aws (12.0.0) |
|---|---|---|
| Maintainer | Red Hat + AWS community, AAP-certified content | Community |
| Typical content | ec2_instance, ec2_vpc_net, ec2_security_group, iam_role, iam_instance_profile, s3_bucket, aws_ec2 inventory, aws_ssm connection, secretsmanager_secret / ssm_parameter lookups | ec2_launch_template, elb_target_group, ecs_*, wafv2_* and other long-tail services |
| Dependencies | ansible-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.
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.
| Order | Source | How it appears in Ansible |
|---|---|---|
| 1 | Explicit parameters | Module parameters access_key/secret_key/session_token, or profile (when a profile is specified, credentials come from that profile's configuration) |
| 2 | Environment variables | AWS_ACCESS_KEY_ID,AWS_SECRET_ACCESS_KEY,AWS_SESSION_TOKEN; AWS_PROFILE Selected profile |
| 3 | role/SSO settings in config | the profile contains role_arn + source_profile (assume role),web_identity_token_file (OIDC, lesson 5),sso_session (IAM Identity Center) |
| 4 | ~/.aws/credentials | Static access key (not recommended) |
| 5 | ~/.aws/config | credential_process etc. |
| 6 | Container credentials | ECS task role, EKS Pod Identity (when the control node runs in a container) |
| 7 | Instance 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.
aws sso login; the token expires after a few hours by default and refreshes automatically).role_arn + source_profile), or use amazon.aws.sts_assume_role.AssumeRoleWithWebIdentity (lesson 5).| Ansible + amazon.aws | Terraform AWS provider | Ansible + azure.azcollection (previous lesson) | |
|---|---|---|---|
| Where API calls are made | Control node boto3 | Provider plugin (Go SDK) | Control node Azure SDK |
| Credential chain | boto3 standard chain | AWS SDK for Go standard chain (same config files) | az CLI / environment variables / MSI |
| State | Stateless; queries the current state by tag/name on each run | state file | Stateless |
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.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.
| Command / module | Purpose | Key parameters / notes |
|---|---|---|
ansible-galaxy collection install -r requirements.yml -p ./collections | Install the collection into the project directory | Use together with ansible.cfg the collections_path; pin the major version |
pipx inject ansible boto3 botocore | Install the SDK into Ansible's virtual environment | Use for upgrades pipx inject --force ansible boto3 botocore |
aws configure sso / aws sso login | Configure and sign in to IAM Identity Center | --profile lab; sign in again when the token expires |
amazon.aws.aws_caller_info | Returns the current identity (account, arn, user_id) | “whoami” in a playbook; suitable as the first task |
amazon.aws.sts_assume_role | Switch roles within a play | role_arn,role_session_name,duration_seconds; returns sts_creds |
module_defaults: group/amazon.aws.aws | Set default profile/region for all modules in the collection | Avoid 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”.
[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.
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
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_.
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.
env | grep ^AWS_ only AWS_PROFILE remains (or is empty).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.
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).
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.
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 }}".
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).
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.
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.
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).
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.
ansible localhost -m amazon.aws.aws_caller_info -a "profile=lab region=ca-central-1" | grep '"account"'
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__)"
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.
No verified video on “amazon.aws authentication / SSO profile” was found; please use the storyboard script below.
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.
hosts: localhost highlighted; an arrow points from a laptop to a cloud icon, not to EC2.aws_caller_info showing the account and arn, next to a green-check assert.lab.aws_ec2.yml: regions, filters, include_filters/exclude_filters, hostnames, compose, keyed_groups, groups.ansible_host also must be the instance ID), while SSH scenarios usually use a private IP or DNS name.--flush-cache; use ansible-inventory --graph/--host to check the results.azure_rm inventory. Importance:★★★★★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”.
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”.
| Option | Purpose | Default / notes |
|---|---|---|
regions | Which regions to query | Default [] = all available regions (slow! always set this explicitly) |
filters | EC2 API filters (server-side filtering) | Default {},does not automatically exclude stopped instances; it is recommended to write instance-state-name: running |
include_filters / exclude_filters | additional OR conditions / exclusion conditions | Exclusions take priority |
hostnames | List host name sources in priority order; use the first non-empty value | Can be instance-id,tag:Name,private-ip-address,dns-name etc.; the dictionary form supports name/prefix/separator |
compose | Generate host variables with Jinja2 | SSM: ansible_host: instance_id |
keyed_groups | Automatically create groups based on variable values | Illegal characters in group names (such as -) are replaced with _ |
groups | Put hosts into a group based on a Jinja2 condition | Added when the condition is true |
cache family | Cache API results | cache_plugin Default memory; cache_timeout default 3600 seconds |
use_ssm_inventory | Merge SSM Inventory data into host variables | Default false |
iam_role_arn (alias assume_role_arn) | Query after assuming a role (cross-account) | — |
hostvars_prefix | Prefix variables sourced from AWS | avoid name clashes with your own variables |
strict | Raise an error instead of skipping when compose/keyed_groups fails | Default false; enable when debugging |
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.private-ip-address, combined with ansible_ssh_common_args: -J bastion.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).| aws_ec2 plugin | legacy ec2.py script | azure_rm plugin (previous lesson) | |
|---|---|---|---|
| Format | YAML config + in-collection plugin | Python script + ini (deprecated) | YAML config |
| Grouping | keyed_groups/groups/compose | Fixed tag_xxx groups | Same Constructable mechanism |
| Caching | Ansible cache plugin | Script's own file cache | Ansible cache plugin |
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.ansible-inventory --graphOn 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.
| Command | Purpose | Key parameters |
|---|---|---|
ansible-inventory -i FILE --graph | Show groups and hosts as a tree | --vars Also show variables |
ansible-inventory -i FILE --host HOST | All variables for a given host | Check compose results |
ansible-inventory -i FILE --list --yaml | Full output | --output file |
ansible-inventory … --flush-cache | Clear the inventory cache and query again | Use after creating/deleting instances |
ansible-doc -t inventory amazon.aws.aws_ec2 | View all options offline | Based 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.
---
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.aws_ec2.yml save it to inventories/aws/.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
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
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-0a1b2c3d4e5f60002ls -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
rm -rf ~/.cache/ansible/aws_ec2.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.
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.
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).
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.
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.
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).
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).
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.
ansible-inventory -i inventories/aws --graph --flush-cache >/dev/null ansible 'role_web:&env_lab' -i inventories/aws --list-hosts
ansible-doc -t inventory amazon.aws.aws_ec2 | less
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}.
This courseware cannot directly generate video/MP3; a storyboard and narration script are provided.
lab.aws_ec2.yml → DescribeInstances with filters → only two of the five instances light up.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.| Resource | Module (FQCN) | “Primary key” (basis for idempotency) | Notes |
|---|---|---|---|
| VPC 10.40.0.0/16 | amazon.aws.ec2_vpc_net | name + cidr_block | Same name and same CIDR are treated as the same VPC |
| Internet gateway | amazon.aws.ec2_vpc_igw | vpc_id | At most one per VPC |
| Public subnet 10.40.1.0/24 | amazon.aws.ec2_vpc_subnet | vpc_id + cidr | map_public: true |
| Route table | amazon.aws.ec2_vpc_route_table | vpc_id + tags (lookup: tag, default) | 0.0.0.0/0 → IGW |
| Security group | amazon.aws.ec2_security_group | name + vpc_id | No inbound rules, outbound allows only 80/443 |
| IAM role | amazon.aws.iam_role | name | Trust ec2.amazonaws.com, attach AmazonSSMManagedInstanceCore |
| Instance profile | amazon.aws.iam_instance_profile | name | EC2 can only use a role through an instance profile |
| S3 bucket (for SSM transfers) | amazon.aws.s3_bucket + community.aws.s3_lifecycle | name (globally unique) | Block public access, SSE, no versioning, 1-day expiration |
| EC2 × 2 | amazon.aws.ec2_instance | filters (this lesson uses the Name + Project tags) | Ubuntu 24.04, t3.micro, IMDSv2, no key pair |
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.
changed: true.--check check mode (Describe only, no changes),--diff and support for diff varies by module.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.RunInstances report Invalid IAM Instance Profile name. Use retries/until to retry.metadata_options.http_tokens: required Enforces session tokens to prevent SSRF from stealing instance credentials; the SSM Agent supports IMDSv2./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).ec2_instance 's network parameter is deprecated (to be removed in releases after 2026-12-01); use network_interfaces (added in 8.2.0).| Ansible amazon.aws | Terraform AWS provider | CloudFormation | |
|---|---|---|---|
| State | None (looked up on each run) | state file | Stack (AWS-managed) |
| Delete resources | explicit state: absent | Removing it from the code is enough for plan to show a deletion | Removing it from the template is enough |
| Dependency order | task order (manual) | dependency graph (automatic parallelism) | dependency graph |
| Best for | create-then-configure, temporary environments | long-lived infrastructure | AWS-only, needs stack-level rollback |
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.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.
| Module | Key parameters | Common keys in return values |
|---|---|---|
ec2_vpc_net | name,cidr_block,tags,dns_hostnames | vpc.id |
ec2_vpc_igw | vpc_id,tags | gateway_id |
ec2_vpc_subnet | vpc_id,cidr,az,map_public | subnet.id |
ec2_vpc_route_table | vpc_id,subnets,routes,tags | route_table.id |
ec2_security_group | name,description,vpc_id,rules,rules_egress | group_id |
iam_role | assume_role_policy_document,managed_policies,create_instance_profile | iam_role.arn |
iam_instance_profile | name,role | iam_instance_profile.arn |
s3_bucket | name,public_access,encryption,versioning | name |
ec2_instance | name,image_id,instance_type,vpc_subnet_id,security_group,network_interfaces,iam_instance_profile,metadata_options,filters,wait | instance_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.
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.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"
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.
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
--flush-cache to view the dynamic inventory groups.destroy.yml.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.
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.
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.
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.
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).
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.
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.
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).
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"'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
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.
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.
This courseware cannot directly generate a video or MP3, so a storyboard and narration script are provided.
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.ssm-user, evaluate trade-offs and performance, and know when to switch to “SSH over SSM”.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).
ssm:StartSession), so offboarding and key rotation no longer require distributing keys.StartSession record in CloudTrail; session output can optionally be written to S3/CloudWatch Logs, and sessions can be encrypted with KMS.AnsiballZ_xxx.py (the same as with SSH).ssm:StartSession (target = ansible_host the instance ID from the inventory, optionally a custom ssm_document) to get SessionId, StreamUrl, and TokenValue.session-manager-plugin process, which connects via WebSocket to ssmmessages endpoint for the data channel.ssm-user), launching the shell.exec_command).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.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.keep_remote_files is set, the S3 files are still deleted).| Location | Requirement | How this lesson meets it |
|---|---|---|
| Instance | SSM Agent running and registered as a managed node; on Linux, curl and Python | The official Ubuntu 24.04 AMI preinstalls SSM Agent (snap), curl, and python3 |
| Instance permissions | Permissions for Agent registration and sessions: attach to the instance role AmazonSSMManagedInstanceCore, or enable Default Host Management Configuration (DHMC) | M3’s instance profile |
| Network | Instance outbound 443 to ssm, ssmmessages, ec2messages, and S3 (or the corresponding VPC endpoints); control node outbound 443 to SSM and S3 | Public subnet + outbound 443 |
| Control node | boto3/botocore,Session Manager plugin | Module 0 |
| Control node permissions | ssm:StartSession/TerminateSession (plus ResumeSession), and on the bucket s3:GetObject,PutObject,ListBucket,DeleteObject,GetBucketLocation | the sandbox administrator permission set; for the minimal policy, see the “Commands” tab |
| S3 bucket | Must 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 |
| aws_ssm plugin | SSH (direct / bastion) | SSH over SSM (ProxyCommand) | |
|---|---|---|---|
| Inbound ports | None | 22 | None |
| Keys | None (IAM) | Required | Required (or pushed temporarily via EC2 Instance Connect) |
| File transfer | Via S3 (PutObject + curl) | SFTP/SCP or pipelining | SFTP/SCP or pipelining |
| pipelining | Not applicable (every module goes through S3) | Supported, significantly faster | Supported |
| Per-task overhead | High: session round trips + S3 upload + curl download, typically seconds | Low (ControlPersist reuses connections) | Low (reused after the session is first established) |
remote_user | Not supported; use become_user | Supported | Supported |
| Auditing | CloudTrail + session logs | Must be built yourself | CloudTrail (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).
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.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).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.
| Variable | Purpose | Notes / default |
|---|---|---|
ansible_connection: amazon.aws.aws_ssm | Enable plugin | Older environments may use community.aws.aws_ssm |
ansible_host / ansible_aws_ssm_instance_id | Session target | Instance ID |
ansible_aws_ssm_bucket_name | File transfer bucket | Required |
ansible_aws_ssm_region | SSM region | Default us-east-1; always set it |
ansible_aws_ssm_profile | Profile to use | can also use AWS_PROFILE |
ansible_aws_ssm_bucket_endpoint_url / ansible_aws_ssm_s3_addressing_style | S3 endpoint and addressing style | Often needed when the bucket and instance are in different regions virtual |
ansible_aws_ssm_bucket_sse_mode / …_sse_kms_key_id | Transfer file encryption | AES256 or aws:kms |
ansible_aws_ssm_document | Custom session document | for example, set runAsDefaultUser, shell configuration |
ansible_aws_ssm_timeout / ansible_aws_ssm_retries | Timeout / reconnect count | Default 60 seconds / 3 attempts |
ansible_aws_ssm_plugin | Session Manager plugin path | Looks 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.
{
"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.
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).
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
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"
}# 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.
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.
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 …).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.
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.
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.
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.
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.
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.
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.
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.
aws ssm start-session --target i-0a1b2c3d4e5f60001 --profile lab --region ca-central-1
ansible role_web -i inventories/aws -b -m ansible.builtin.command -a "snap services amazon-ssm-agent"
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.
No verified video on the “Ansible aws_ssm connection plugin” was found (search results are all written tutorials); please use the storyboard script below.
This courseware cannot directly generate a video or MP3, so a storyboard and narration script are provided.
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.no_log to keep secrets out of logs.amazon.aws.secretsmanager_secret | amazon.aws.ssm_parameter | |
|---|---|---|
| Backend | AWS Secrets Manager (GetSecretValue) | SSM Parameter Store (GetParameter/GetParametersByPath) |
| Old name (alias) | amazon.aws.aws_secret | amazon.aws.aws_ssm (note: same name as the aws_ssm connection plugin but a different type, so they do not conflict) |
| Common options | nested (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 |
| Authentication | the 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 call | Standard parameters are free (standard throughput); advanced parameters and high throughput are billed separately; SecureString decryption involves KMS requests |
| Highlights | Automatic rotation (Lambda / managed rotation, RDS, etc.), cross-account sharing, version stages AWSCURRENT/AWSPREVIOUS | hierarchical paths, public parameters (such as the M3 AMI ID), inexpensive |
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.
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.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.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.
| Scenario | Recommended |
|---|---|
| Database passwords, API keys; rotation needed | Secrets Manager (or have the application read it directly) |
| Feature flags, version numbers, ports, and other non-sensitive configuration | Parameter Store String (free) |
| A few sensitive settings; budget-sensitive | Parameter Store SecureString (KMS encrypted) |
| Offline environments and cloud-independent secrets (such as switch passwords) | Ansible Vault or an external Vault (HashiCorp) |
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).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).
| Command / plugin | Purpose | Key parameters |
|---|---|---|
community.aws.secretsmanager_secret (module) | Create/update/delete a secret | json_secret,recovery_window (0 = delete immediately) |
community.aws.ssm_parameter (module) | Create/update a parameter | string_type,value,overwrite_value |
lookup('amazon.aws.secretsmanager_secret', NAME) | Read a secret | nested=true,on_missing |
lookup('amazon.aws.ssm_parameter', PATH, bypath=true) | Read parameters by path | recursive,shortnames |
aws secretsmanager get-secret-value | CLI 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.
secrets.yml.---
- 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.
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.
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.
recovery_window: 0 to delete the secret immediately and remove the parameters.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).
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.
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.
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.
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.
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.
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.
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') }}"aws secretsmanager delete-secret --secret-id ansible-lab/myapp --force-delete-without-recovery --profile lab --region ca-central-1
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.
No verified video on the Secrets Manager / Parameter Store lookup plugins was found; please use the storyboard script below.
This courseware cannot directly generate a video or MP3, so a storyboard and narration script are provided.
wait_for_connection,become and ssm-user,gather_subset speed-ups and secrets no_log.serial + max_fail_percentage for rolling deployment, and verify through uri (on the instance) or via SSM port forwarding /healthz.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”:
| Layer | Lesson 2 (container node) | Lesson 4 (EC2) |
|---|---|---|
| Inventory | Static hosts.yml (node1–3) | lab.aws_ec2.yml (role_web group) |
| Connection | ssh | amazon.aws.aws_ssm (group_vars/aws_ec2.yml) |
| Secrets | Ansible Vault | Secrets Manager + Parameter Store (M5) |
| Role | roles/myapp (identical) | |
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).
hosts: role_web,become: true,serial: 1,max_fail_percentage: 0.gather_facts: true + gather_subset: [min]: the setup module is slow over SSM, so gather only the minimum facts.pre_tasks: wait_for_connection (the agent on a new instance may not be ready yet),set_fact + run_once read secrets (M5).roles: [myapp]: apt install → user and directories → venv + pip → app code → env file (no_log) → systemd unit → handlers restart.post_tasks: inside the instance, use uri http://127.0.0.1:8000/healthz retry until 200.ssm-user , and the agent configures passwordless sudo for it, so become: true works directly.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.ansible_user: aws_ssm does not support it.| Ansible push (this lesson) | user_data / cloud-init | Bake an AMI (Packer + Ansible) | SSM State Manager + AWS-ApplyAnsiblePlaybooks | |
|---|---|---|---|---|
| Timing | Any time, repeatable | First boot only | At build time | Periodically / on association, the instance pulls its own config |
| Best for | Ongoing configuration and change releases | Bootstrapping (installing agent, registration) | Large-scale, fast scale-out | Massive fleets, no central control node |
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.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.
--- 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
---
- 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
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.
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/myappdeploy-myapp.yml, and watch the two batches run in sequence.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",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]'
AWS-StartPortForwardingSession Open http://localhost:18000/ in a browser.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.
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.
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).
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.
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.
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).
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.
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.
ansible-playbook -i inventories/aws playbooks/aws/deploy-myapp.yml --limit i-0a1b2c3d4e5f60002
aws ssm start-session --target i-0a1b2c3d4e5f60001 --document-name AWS-StartPortForwardingSession \
--parameters '{"portNumber":["8000"],"localPortNumber":["18000"]}' --profile lab --region ca-central-1With 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).
No verified video on “deploying an app to EC2 via SSM” was found; please use the storyboard below.
This courseware cannot directly generate video/MP3, so a storyboard and narration script are provided instead.
-vvvv,debug_botocore_endpoint_logs, CloudTrail,aws ssm describe-instance-information to collect evidence.| Layer | Typical error / symptom | Verification command |
|---|---|---|
| L1 Python / SDK | Failed to import the required Python library (botocore and boto3), version too old | ansible --version; in that Python, run import boto3 |
| L2 Credentials | Unable to locate credentials,ExpiredToken,InvalidClientTokenId, expired SSO token | env | grep ^AWS_; aws sts get-caller-identity --profile lab |
| L3 IAM authorization | AccessDenied,UnauthorizedOperation (may include an Encoded authorization failure message) | aws sts decode-authorization-message; the errorCode of the CloudTrail event |
| L4 Inventory | empty inventory, group does not exist, hostname is not an instance ID | ansible-inventory --graph --flush-cache -vvv |
| L5 SSM session | TargetNotConnected,SessionManagerPlugin is not found, session timeout | aws ssm describe-instance-information; aws ssm start-session |
| L6 S3 relay | PutObject AccessDenied, curl download stalls / 403, cross-region signature error | control node aws s3 cp; inside the session curl -sI https://s3.<region>.amazonaws.com |
| L7 Instance / application | apt/pip failures, service won’t start, health check failures | journalctl,systemctl status (via SSM) |
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.
AWS_* then inject; humans use SSO; when it expires, run aws sso login.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.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.| Tool | Purpose |
|---|---|
ansible-playbook -vvvv | See 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-events | who, when, which API was called, and what the errorCode is |
aws ssm describe-instance-information | whether the managed node is Online, agent version |
EC2 serial console / get-console-output | agent startup logs, cloud-init errors |
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.aws ssm start-session split the problem into “session layer” and “transfer layer” halvesSelect 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.
| Command | Purpose | Notes |
|---|---|---|
env | grep ^AWS_ | Check leftover credentials / region | Run first |
aws configure list --profile lab | Value and source of each configuration item | Shows type (env, shared-credentials-file, sso…) |
aws sts decode-authorization-message | Decode authorization failure messages returned by EC2 and others | Requires sts:DecodeAuthorizationMessage |
aws cloudtrail lookup-events | Query recent API calls by event name / user | Management events have a delay of several minutes |
aws ssm describe-instance-information | Managed node status | Online / ConnectionLost / Inactive |
ANSIBLE_DEBUG=1 / -vvvv | Ansible internals and connection plugin debugging | Lots of output; redirect to a file |
AWS_RETRY_MODE=adaptive AWS_MAX_ATTEMPTS=10 | botocore retries and client-side rate limiting | can 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
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.
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.
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.”
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.
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.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.
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.
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.
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.
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.
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.
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.
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).
ansible localhost -m amazon.aws.ec2_instance_info -a "profile=lab region=ca-central-1 debug_botocore_endpoint_logs=true" | jq .resource_actions
aws ssm describe-instance-information --profile lab --region ca-central-1 \ --query "InstanceInformationList[?PingStatus!='Online'].[InstanceId,PingStatus,LastPingDateTime]" --output table
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).
No verified video on “Ansible + AWS troubleshooting” was found. You can revisit Jeff Geerling Episode 11 from M2 (approach to debugging inventory plugins).
This courseware cannot directly generate video/MP3, so a storyboard and narration script are provided instead.
destroy.yml, handling repeated runs where “the resource no longer exists”.| Resource | Quantity | Billing method | Example unit price (refer to the pricing page) | Approx. per hour |
|---|---|---|---|---|
| EC2 t3.micro (Linux, on-demand) | 2 | Per second (minimum 60 seconds) | ≈ 0.0116 USD/hour | ≈ 0.023 |
| Public IPv4 address | 2 | Per hour (all public IPv4 addresses charged since 2024-02) | 0.005 USD/hour | 0.010 |
| EBS gp3 root volume 8 GiB | 2 | Per GB-month | ≈ 0.088 USD/GB-month | ≈ 0.002 |
| Secrets Manager secret | 1 | Per secret per month + per 10,000 API calls | ≈ 0.40 USD/month | ≈ 0.0006 |
| S3 relay bucket | 1 | Storage + requests | Files are very small; can be ignored | ≈ 0 |
| Parameter Store standard parameters | 3 | Standard tier is free | 0 | 0 |
| Session Manager | — | No extra charge for EC2 instances | 0 | 0 |
| 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.
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.
state: absent, wait for termination, release the network interface and public IP; the root volume is deleted with the instance by default).force: true delete objects first).recovery_window: 0 delete immediately) and parameters.ExpiresAt / Owner tags, and run scheduled jobs that scan for expired resources (Ansible, Lambda, or AWS Config rules).terraform destroy.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.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.
---
- 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
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,…).
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.
-e auto_approve=true, there should be no failures—this proves destroy is also idempotent.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.
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).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.
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.
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.
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).
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.
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.
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.
aws resourcegroupstaggingapi get-resources --tag-filters Key=Project,Values=ansible-lab --profile lab --region ca-central-1 --query 'ResourceTagMappingList[].ResourceARN'
ansible-playbook -i inventories/aws playbooks/aws/destroy.yml -e auto_approve=true
① 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.
No verified video on “cleaning up AWS resources with Ansible / cloud cost control” was found; please use the storyboard below.
This courseware cannot directly generate video/MP3, so a storyboard and narration script are provided instead.
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
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"
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
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"]}'{{ 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) }}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
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
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
| Symptom / error | Layer | First command | Common fix |
|---|---|---|---|
| Failed to import … botocore and boto3 | L1 | ansible --version | pipx inject ansible boto3 botocore |
| requires boto3 >= 1.38.23 | L1 | Print the version in Ansible’s Python | pipx inject --force … |
| Unable to locate credentials / ExpiredToken / InvalidClientTokenId | L2 | env | grep ^AWS_ | Pass the profile; aws sso login; clear leftover key |
| AccessDenied / UnauthorizedOperation | L3 | aws_caller_info + decode the message | Add permissions; check SCP, permission boundary, KMS |
| Empty inventory | L4 | ansible-inventory --graph --flush-cache -vvv | suffix, region, tag case, running filter |
| TargetNotConnected | L5 | describe-instance-information | Instance role, outbound 443, agent |
| SessionManagerPlugin is not found | L5 | command -v session-manager-plugin | Install the plugin or configure ansible_aws_ssm_plugin |
| PutObject AccessDenied / NoSuchBucket | L6 | aws s3 ls s3://bucket | Bucket name, bucket policy, KMS permissions |
| Module transfer hangs and times out | L6 | inside the session curl -sI https://s3.ca-central-1.amazonaws.com | Outbound 443 / S3 gateway endpoint / addressing style |
| RequestLimitExceeded / ThrottlingException | L3/L5 | CloudTrail errorCode | adaptive retries, lower forks, throttle, cache |
| DependencyViolation (during cleanup) | — | describe-network-interfaces | Rerun destroy after the instance terminates |
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: 300ansible_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 }}"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.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
ansible-playbook -i inventories/aws playbooks/aws/provision.yml ansible-playbook -i inventories/aws playbooks/aws/provision.yml | tail -1 # changed=0
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
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
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"
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.
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
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
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).
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).
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.
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.
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.
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.
| Topic | Verified conclusion | Source (accessed 2026-11-15) |
|---|---|---|
| ansible-core / Ansible package | core 2.21 (control node Python 3.12–3.14); Ansible 14.x is based on core 2.21 | Unified course standard (verified against the docs.ansible.com release and maintenance page) |
| amazon.aws version | Latest 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 dependencies | ansible-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_instance | amazon.aws README · CHANGELOG |
| community.aws | Latest on Galaxy is 12.0.0; includes modules such as secretsmanager_secret, ssm_parameter, and s3_lifecycle | Galaxy community.aws · Collection index |
| aws_ssm connection plugin | Name 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 plugin | The 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_prefix | aws_ec2 inventory |
| ec2_instance | network 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_profile | CHANGELOG |
| Lookup plugins | secretsmanager_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 true | secretsmanager_secret · ssm_parameter |
| boto3 credentials and retries | Credential chain order; standard/adaptive retry modes | Credentials · Retries |
| Session Manager / SSM | Plugin install path, VPC endpoints (ssm, ssmmessages, ec2messages, S3 gateway), DHMC, port forwarding documentation | Session Manager · VPC endpoints |
| Pricing | Example unit prices (t3.micro, public IPv4 0.005 USD/hour, gp3, Secrets Manager 0.40 USD/secret/month), for order-of-magnitude reference only | AWS Pricing |
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.
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.
-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).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.