Ansible AWS Automation uses Ansible playbooks to manage AWS resources declaratively, with the amazon.aws collection. The key takeaway: always use state: present or state: absent explicitly, and handle API rate limits by enabling retries and delay in task parameters to avoid throttling failures in production.
✦ Definition~90s read
What is Ansible AWS Automation?
Ansible AWS automation is the practice of using Ansible playbooks to manage AWS infrastructure as code. The amazon.aws collection (version 5.0.0+) is the official, community-maintained set of modules that replace the older community.aws modules. It provides modules for EC2, S3, IAM, RDS, VPC, and many other AWS services, all designed with idempotency in mind.
★
Think of Ansible for AWS like a smart remote control for your cloud infrastructure.
In the Ansible ecosystem, the amazon.aws collection fits as the primary interface between Ansible and AWS. It leverages the boto3 and botocore Python libraries to make API calls. The key advantage over writing raw aws CLI commands or using CloudFormation is that Ansible modules handle state management — you declare the desired end state, and Ansible figures out what actions (create, update, delete) are needed to reach that state.
The problem it solves is the complexity of AWS API interactions: handling pagination, eventual consistency, error retries, and idempotency. Without Ansible, you'd have to write scripts with error handling, retries, and state checks. The amazon.aws collection encapsulates these patterns, allowing you to focus on infrastructure design rather than API quirks.
Plain-English First
Think of Ansible for AWS like a smart remote control for your cloud infrastructure. Instead of clicking buttons in the AWS console, you write a recipe (playbook) that says 'I want exactly 3 servers of this type, with these security settings, and this S3 bucket for logs.' Ansible talks to AWS APIs to make it happen, and if you run the recipe again, it checks what's already there and only changes what's needed — that's idempotency. But AWS is a distributed system, so sometimes when you create a server, it takes a moment for the list of servers to update. Ansible has a 'wait and retry' feature to handle that. And for secrets like database passwords, you store them in AWS SSM Parameter Store, a secure vault, and Ansible pulls them at runtime without exposing them in your code.
I still remember the 3 AM wake-up call. Our production deployment had been running smoothly for months, but that night, a seemingly innocuous change to an Ansible playbook caused a 45-minute outage. The root cause? I had used the deprecated ec2 module instead of ec2_instance, and the module didn't handle idempotency correctly — it terminated all existing instances and created new ones, thinking they were 'extra'. That incident taught me the hard way that Ansible AWS automation requires deep understanding of module behavior, API consistency, and cloud state management.
Historically, Ansible's AWS support started with basic modules like ec2 and s3, which were monolithic and often inconsistent. The community developed workarounds, but the real game-changer was the amazon.aws collection (introduced in Ansible 2.9, now the standard). This collection provides focused, idempotent modules like ec2_instance, s3_bucket, iam_role, and rds_instance, designed to work with the AWS API's eventual consistency model.
In this article, I'll share production patterns I've developed over years of managing thousands of AWS resources with Ansible. We'll cover the essential modules from the amazon.aws collection, dynamic inventory with the aws_ec2 plugin, handling idempotency and eventual consistency, and securing secrets with AWS SSM Parameter Store. Every code example is battle-tested in production environments.
By the end, you'll have a practical playbook (pun intended) for building robust, scalable AWS automation with Ansible that won't cause 3 AM phone calls.
Setting Up the amazon.aws Collection for Production
The first step is ensuring you have the correct collection version. The amazon.aws collection is the replacement for the deprecated community.aws collection. Install it with:
For authentication, use IAM instance profiles on EC2 or environment variables (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY). In production, avoid hardcoding secrets; use Ansible Vault or SSM Parameter Store (covered later).
Do NOT mix amazon.aws and community.aws modules in the same playbook. They use different module namespaces and can conflict. Stick to amazon.aws for all AWS operations.
📊 Production Insight
In one incident, we had a playbook using community.aws.ec2_instance which was actually a redirect to amazon.aws.ec2_instance. After upgrading the collection, the redirect broke and tasks failed with 'module not found'. We fixed it by explicitly using amazon.aws.ec2_instance and removing community.aws from requirements.
🎯 Key Takeaway
Always use amazon.aws collection pinned to a major version, and ensure boto3/botocore are up to date on the control node.
thecodeforge.io
Ansible Aws Automation
Managing EC2 Instances with ec2_instance Module
The ec2_instance module is the modern way to manage EC2 instances. It supports exact_count for idempotent instance management. Here's a production playbook snippet:
exact_count: Ensures exactly that many instances exist. If fewer, it creates; if more, it terminates extras. Without it, the module is not idempotent.
instance_role: Attaches an IAM instance profile. Use the profile name, not ARN.
wait: yes and wait_timeout: Crucial for production — waits for instance to reach running state.
network: Allows specifying network interfaces. For multiple ENIs, use network_interfaces.
Gotcha: The exact_count parameter works by filtering instances based on name tag and other filters you provide. If you don't set name, it may count unrelated instances. Always set name and tags to scope the count.
For updating instances (e.g., change instance type), use state: running and modify parameters. However, not all attributes are updatable in place; some require replacement. Use instance_ids to target specific instances for operations like stop/start.
Always use exact_count when you want a fixed number of instances. Without it, the module will create a new instance every run, leading to drift and cost overruns.
📊 Production Insight
We once had a playbook that created instances without exact_count. After a few runs, we had 50 instances instead of 3. Adding exact_count: 3 with proper name and tags filters immediately terminated the extras and prevented future drift.
🎯 Key Takeaway
Use ec2_instance with exact_count, name, and tags for idempotent EC2 management. Always set wait: yes.
Creating S3 Buckets and Objects with Idempotency
The s3_bucket and s3_object modules manage S3 resources. s3_bucket is idempotent by default: if the bucket exists and is owned by you, it reports ok. If it exists but is owned by another account, it fails with BucketAlreadyExists. For production:
Gotcha: The s3_bucket module does not manage bucket policies. Use a separate task with aws_s3_bucket_policy or iam_policy.
Idempotency for objects: The s3_object module with mode: put will upload the file every time unless you use force: false (default). To avoid unnecessary uploads, use overwrite: different (new in amazon.aws 5.0.0) which compares MD5 checksums:
``yaml - name: Upload config only if changed amazon.aws.s3_object: bucket: my-app-bucket object: /config/app.conf src: /local/path/app.conf mode: put overwrite: different ``
S3 bucket names must be globally unique and DNS-compliant. Use a naming convention like company-app-environment-region to avoid collisions.
📊 Production Insight
We had a bucket creation fail because another team had already created a bucket with the same name in a different account. We switched to using account-specific prefixes (e.g., myapp-{{ aws_account_id }}-bucket) to guarantee uniqueness.
🎯 Key Takeaway
Use s3_bucket with state: present and permission: private. For objects, use overwrite: different to avoid unnecessary uploads.
thecodeforge.io
Ansible Aws Automation
Creating IAM Roles and Instance Profiles
IAM role management is critical for security. The iam_role module creates roles and attaches policies. Production example:
Gotcha: The iam_role module is idempotent only if the assume_role_policy_document is exactly the same. If you change the file, the module updates the role. However, managed_policies are additive — if you remove a policy from the list, the module does NOT detach it. To manage policies precisely, use iam_policy module or set managed_policies: [] and manage separately.
For instance profiles, create_instance_profile: yes creates a profile with the same name as the role. To attach the profile to an EC2 instance, use ec2_instance with instance_role parameter.
The assume_role_policy_document must be a JSON string, not a YAML dict. Use lookup('file', ...) or lookup('template', ...) to ensure proper formatting.
📊 Production Insight
We once had a role update fail because the JSON file had a trailing comma. The module reported 'MalformedPolicyDocument'. We added a validation step: - name: Validate JSON | set_fact: policy_json={{ lookup('file', 'policy.json') | from_json }} before the IAM task.
🎯 Key Takeaway
Use iam_role with assume_role_policy_document from a file, and create_instance_profile: yes. Validate JSON before applying.
Provisioning RDS Instances with rds_instance
The rds_instance module manages RDS databases. Production example:
skip_final_snapshot: In production, set to no and provide final_snapshot_identifier to avoid data loss on deletion.
wait_timeout: RDS creation can take 10-20 minutes. Set to 1200 seconds (20 minutes).
master_user_password: Use Ansible Vault or SSM Parameter Store (see section on secrets).
Gotcha: The module does not support changing master_username after creation. If you need to change, you must delete and recreate.
Idempotency: The module checks for an existing instance with the same db_instance_identifier. If found, it compares parameters and updates if necessary. Not all parameters are updatable in place; some require replacement.
Never set skip_final_snapshot: yes in production. Always create a final snapshot before deletion. Use a unique identifier with timestamp to avoid conflicts.
📊 Production Insight
We once had a playbook that deleted a production RDS instance because state: absent was triggered accidentally. The final_snapshot_identifier allowed us to restore within minutes. Without it, we would have lost 2 TB of data.
🎯 Key Takeaway
Always set skip_final_snapshot: no with a unique final snapshot identifier. Use wait: yes and wait_timeout: 1200.
Building VPC Networks with aws_vpc and Subnet Modules
VPC modules allow you to define network infrastructure as code. Production example:
Idempotency: These modules use tags and cidr_block to identify existing resources. If you change the CIDR, it creates a new resource (the old one is not deleted). To delete, set state: absent.
Gotcha: The ec2_vpc_subnet module requires vpc_id or vpc_name. Using vpc_name is convenient but can be ambiguous if multiple VPCs have the same name. Prefer vpc_id.
Production insight: Use ec2_vpc_route_table with subnets list to associate subnets. The module is idempotent: if routes and associations match, it does nothing.
When referencing VPCs, use vpc_id instead of vpc_name to avoid ambiguity. You can retrieve the VPC ID using ec2_vpc_net_info with filters.
📊 Production Insight
We had a situation where two VPCs had the same name 'production' (different regions). Using vpc_name caused the playbook to modify the wrong VPC. We switched to using vpc_id obtained from ec2_vpc_net_info with region filter.
🎯 Key Takeaway
Use vpc_id for idempotent operations. Tag all resources with Name and Environment for easy identification.
Using Dynamic Inventory with AWS EC2 Plugin
The aws_ec2 inventory plugin dynamically builds inventory from AWS EC2 instances. Configure it in inventory/aws_ec2.yml:
Use ansible-inventory -i inventory/aws_ec2.yml --list --flush-cache to refresh the cache on demand.
📊 Production Insight
We once had a deployment that failed because the dynamic inventory still showed old instances after a scale-down. The cache had a 1-hour timeout. We added a pre-task to flush cache: - name: Flush cache | meta: refresh_inventory.
🎯 Key Takeaway
Enable caching with cache: yes to avoid API rate limits, but flush cache during deployments with --flush-cache or meta: refresh_inventory.
Ensuring Idempotency in Cloud Modules
Idempotency means running a playbook multiple times produces the same result. AWS modules in amazon.aws are designed to be idempotent, but there are pitfalls.
Pattern 1: Use state: present with unique identifiers. For example, ec2_instance with name and tags uniquely identifies instances. Without name, the module may create duplicates.
Pattern 2: Use exact_count for EC2. This ensures exactly N instances exist. Without it, each run creates a new instance.
Pattern 3: Use force: false (default) on s3_bucket to avoid recreating.
Pattern 4: For IAM roles, the assume_role_policy_document must match exactly. If you use a template that changes every run (e.g., with timestamps), the role will be updated every time. Avoid dynamic content in policy documents.
Pattern 5: Use register and when to skip tasks if resource already exists. For example:
This pattern is useful for modules that are not fully idempotent (e.g., some community modules).
Gotcha: Some modules like ec2_instance with exact_count can be slow because they query all instances matching filters. Use specific filters to limit scope.
idempotent_sg.ymlYAML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
---
- name: Ensure security group exists
amazon.aws.ec2_security_group:
name: "web-sg-{{ env }}"
description: Security group for web servers
vpc_id: vpc-12345678
rules:
- proto: tcp
ports:
- 80
- 443
cidr_ip: 0.0.0.0/0
rules_egress:
- proto: all
cidr_ip: 0.0.0.0/0
state: present
purge_rules: yes
purge_rules_egress: yes
register: sg_result
Output
changed=0 group_id='sg-12345678'
⚠ Idempotency and Tags
Tags are often used to identify resources. If you don't set tags, the module may not find existing resources and create duplicates. Always set tags with a Name key.
📊 Production Insight
We had a playbook that created security groups without tags. Each run created a new SG because the module couldn't find the existing one. Adding tags: { Name: my-sg } fixed it.
🎯 Key Takeaway
Use unique identifiers (name, tags) and state: present for idempotency. For EC2, use exact_count. Avoid dynamic content in policy documents.
Handling Eventual Consistency with Retries
AWS APIs are eventually consistent — after creating a resource, it may not be immediately visible in other APIs. This causes failures in subsequent tasks. The amazon.aws collection provides retries and delay parameters.
Many AWS modules return 404 if the resource doesn't exist yet. Use retries and until with a condition that checks for existence (e.g., vpcs | length > 0).
📊 Production Insight
We had a playbook that created a VPC and then immediately tried to create subnets. The subnet creation failed because the VPC wasn't visible yet. Adding retries: 10, delay: 5 on the VPC info check before subnet creation fixed it.
🎯 Key Takeaway
Always add retries and delay after resource creation, especially for VPC, RDS, and IAM resources. Use until with existence checks.
Storing Secrets with AWS SSM Parameter Store
Never hardcode secrets in playbooks. Use AWS SSM Parameter Store with the aws_ssm_parameter module to manage parameters, and lookup to retrieve them securely.
Use hierarchical paths like /app/env/parameter for organization. Ensure the IAM role has ssm:GetParametersByPath permission to list parameters.
📊 Production Insight
We once had a secret leak because a developer forgot no_log: true on a set_fact task. The password appeared in CI logs. We added a pre-commit hook to check for no_log: true on tasks that use aws_ssm_parameter lookup.
🎯 Key Takeaway
Use aws_ssm_parameter to store secrets and lookup to retrieve them. Always use no_log: true on tasks handling secrets.
Advanced: Combining Modules for Multi-Tier Deployments
Production applications often require multiple AWS resources. Here's a playbook that creates a VPC, subnets, security groups, RDS, and EC2 instances in a coordinated way.
Create VPC first, then subnets, security groups, RDS subnet group, RDS, and finally EC2. Use wait: yes on RDS to ensure it's ready before EC2 tries to connect.
📊 Production Insight
We once had a playbook that created RDS and EC2 in parallel using async. The EC2 instances booted before RDS was ready, causing application failures. We switched to sequential with wait: yes on RDS.
🎯 Key Takeaway
Orchestrate resource creation in dependency order. Use wait: yes and register to pass IDs between tasks.
Testing and Validating AWS Playbooks Locally
Testing AWS playbooks without affecting real infrastructure is crucial. Use --check mode and --diff to preview changes.
Limitations: --check mode does not actually call AWS APIs for creation tasks; it simulates. Some modules return 'changed' even in check mode. To validate syntax:
Some modules (e.g., iam_role) do not support check mode fully. They may report 'changed' even when no changes would occur. Always verify with a dry run in a test environment.
📊 Production Insight
We had a playbook that passed --check but failed in production because of a missing IAM permission. We added a pre-validation task that calls aws iam simulate-principal-policy to check permissions before running the main playbook.
🎯 Key Takeaway
Use --check and --diff for dry runs. Use Molecule with EC2 driver for integration testing. Always test in a separate AWS account.
● Production incidentPOST-MORTEMseverity: high
The Idempotency Fail: ec2 Module vs ec2_instance
Symptom
After running the playbook, all EC2 instances in the auto scaling group were terminated and new ones launched with different IPs, causing a full outage.
Assumption
The engineer assumed the ec2 module was idempotent and would only create instances if the count was insufficient.
Root cause
The ec2 module does not have an exact_count parameter that properly handles existing instances. It treated all running instances as 'extra' and terminated them before creating new ones.
Fix
Replaced the ec2 module with ec2_instance using exact_count: 3 and instance_role parameters. Also added instance_ids to target specific instances for updates.
Key lesson
Always use the latest module from amazon.aws collection (e.g., ec2_instance over ec2).
The old modules are deprecated for a reason — they lack proper idempotency and state management.
Production debug guideSymptom → Root cause → Fix4 entries
Symptom · 01
Playbook hangs at 'ec2_instance' task for 5+ minutes
→
Fix
Root cause: AWS API rate limiting or network timeout. Fix: Add timeout: 120 to the module and use retries: 5, delay: 10 for eventual consistency tasks.
Symptom · 02
S3 bucket creation fails with 'BucketAlreadyOwnedByYou' error
→
Fix
Root cause: Module not idempotent for existing buckets. Fix: Use s3_bucket module with state: present and force: false (default). The error is benign; add ignore_errors: yes or check bucket existence with aws_s3_bucket_info first.
Symptom · 03
IAM role creation fails with 'MalformedPolicyDocument'
→
Fix
Root cause: JSON policy document has trailing comma or invalid quotes. Fix: Use lookup('file', 'policy.json') and validate with json.loads via a set_fact before the task.
Symptom · 04
RDS instance creation succeeds but ec2_instance_info doesn't find it for 30 seconds
→
Fix
Root cause: AWS eventual consistency — RDS is not immediately visible in all APIs. Fix: Add wait: yes, wait_timeout: 600 to rds_instance module, then use retries: 10, delay: 10 on subsequent tasks that query RDS.
★ Ansible AWS Automation Quick Referenceprint this for your desk
Use lookup('aws_ssm_parameter', '/myapp/dbpassword', decrypt=True, region=ssm_region)
Comparison of EC2 Instance Modules
Feature
ec2 (community.aws)
ec2_instance (amazon.aws)
Notes
Idempotent
No (creates every run)
Yes (with exact_count)
Use ec2_instance for production
Count management
count parameter (additive)
exact_count (absolute)
exact_count prevents drift
Tags
Requires separate task
Built-in tags parameter
Simpler playbooks
Wait for ready
wait=yes not reliable
wait=yes with timeout
Avoids race conditions
Instance profile
Not supported
instance_role parameter
Simplifies IAM integration
Network interfaces
Complex
network parameter
Easier multi-ENI setup
Stateful updates
No (replace only)
Yes (modify in place)
Reduces downtime
⚙ Quick Reference
12 commands from this guide
File
Command / Code
Purpose
requirements.yml
collections:
Setting Up the amazon.aws Collection for Production
ec2_instance.yml
- name: Launch EC2 instance
Managing EC2 Instances with ec2_instance Module
s3_bucket.yml
- name: Create S3 bucket with versioning
Creating S3 Buckets and Objects with Idempotency
iam_role.yml
- name: Create IAM role for EC2
Creating IAM Roles and Instance Profiles
rds_instance.yml
- name: Provision RDS MySQL instance
Provisioning RDS Instances with rds_instance
vpc_network.yml
- name: Create VPC
Building VPC Networks with aws_vpc and Subnet Modules
aws_ec2.yml
plugin: amazon.aws.aws_ec2
Using Dynamic Inventory with AWS EC2 Plugin
idempotent_sg.yml
- name: Ensure security group exists
Ensuring Idempotency in Cloud Modules
retry_iam.yml
- name: Wait for IAM role propagation
Handling Eventual Consistency with Retries
ssm_secret.yml
- name: Store secret in SSM
Storing Secrets with AWS SSM Parameter Store
multi_tier.yml
- name: Deploy multi-tier app
Advanced
test_locally.sh
pip install moto[server] ansible
Testing and Validating AWS Playbooks Locally
Key takeaways
1
Use amazon.aws collection (>=5.0.0) for all AWS modules; avoid community.aws.
2
EC2
Use ec2_instance with exact_count, name, tags, and wait=yes.
3
S3
Use s3_bucket with state=present and permission=private; for objects use overwrite=different.
4
IAM
Use iam_role with assume_role_policy_document from file; validate JSON first.
5
RDS
Use rds_instance with skip_final_snapshot=no and final_snapshot_identifier.
6
VPC
Use ec2_vpc_net, ec2_vpc_subnet with tags for idempotency; prefer vpc_id over vpc_name.
7
Dynamic inventory
Use aws_ec2 plugin with cache=yes and keyed_groups.
8
Eventual consistency
Add retries, delay, and until conditions after resource creation.
9
Secrets
Store in SSM Parameter Store with SecureString; retrieve via lookup with no_log: true.
10
Test with --check, --diff, and Molecule in separate AWS account.
11
Always set tags on resources for idempotent identification.
12
Orchestrate resource creation in dependency order with wait and register.
INTERVIEW PREP · PRACTICE MODE
Interview Questions on This Topic
Q01SENIOR
How do you ensure idempotency when creating EC2 instances with Ansible?
Q02SENIOR
What is the difference between `ec2` and `ec2_instance` modules?
Q03SENIOR
How do you handle eventual consistency when creating an RDS instance in ...
Q04SENIOR
How do you securely manage database passwords in Ansible AWS playbooks?
Q05SENIOR
What is the best practice for dynamic inventory with AWS EC2?
Q06SENIOR
How do you create a VPC with subnets using Ansible?
Q07SENIOR
What are common pitfalls when using Ansible to manage IAM roles?
Q08SENIOR
How do you test Ansible AWS playbooks without affecting production?
Q01 of 08SENIOR
How do you ensure idempotency when creating EC2 instances with Ansible?
ANSWER
Use the amazon.aws.ec2_instance module with the exact_count parameter. Provide filters like name and tags to scope the count. Without exact_count, the module creates a new instance every run. Also set state: present and use wait: yes to ensure the instance is running before proceeding.
Q02 of 08SENIOR
What is the difference between `ec2` and `ec2_instance` modules?
ANSWER
The ec2 module is deprecated and part of the community.aws collection. It is not idempotent — it creates instances on every run unless you manually check state. The ec2_instance module is from amazon.aws collection, supports exact_count for idempotency, built-in tag management, instance profiles, and wait timeouts. Always use ec2_instance for new projects.
Q03 of 08SENIOR
How do you handle eventual consistency when creating an RDS instance in Ansible?
ANSWER
After creating the RDS instance with rds_instance, use the wait: yes parameter with a high wait_timeout (e.g., 1200 seconds). Then, in subsequent tasks that query the instance (e.g., rds_instance_info), use retries: 10 and delay: 10 with an until condition checking for db_instance_status == 'available'. This handles the delay in RDS becoming visible in the API.
Q04 of 08SENIOR
How do you securely manage database passwords in Ansible AWS playbooks?
ANSWER
Store the password in AWS SSM Parameter Store as a SecureString using the aws_ssm_parameter module. Retrieve it at runtime with the lookup('aws_ssm_parameter', ...) plugin with decrypt=True. Always use no_log: true on tasks that handle the password. The IAM role must have ssm:GetParameter and kms:Decrypt permissions.
Q05 of 08SENIOR
What is the best practice for dynamic inventory with AWS EC2?
ANSWER
Use the amazon.aws.aws_ec2 inventory plugin. Configure it in a YAML file with filters (tags, instance states), cache settings (cache: yes, cache_plugin: jsonfile, cache_timeout: 3600), and hostname composition. Use keyed_groups to organize instances by tags. Run with ansible-playbook -i inventory/aws_ec2.yml playbook.yml.
Q06 of 08SENIOR
How do you create a VPC with subnets using Ansible?
ANSWER
Use amazon.aws.ec2_vpc_net to create the VPC. Then use amazon.aws.ec2_vpc_subnet to create subnets, providing the vpc_id from the VPC creation task. Use loop to create multiple subnets. For internet access, add ec2_vpc_igw and ec2_vpc_route_table with routes. All modules are idempotent when using tags and CIDR blocks.
Q07 of 08SENIOR
What are common pitfalls when using Ansible to manage IAM roles?
ANSWER
The iam_role module requires the assume_role_policy_document to be a valid JSON string, not a YAML dict. Use lookup('file', ...) to load from file. The module is idempotent only if the policy document matches exactly. Also, managed_policies are additive — removing a policy from the list does not detach it. Use iam_policy for precise policy management.
Q08 of 08SENIOR
How do you test Ansible AWS playbooks without affecting production?
ANSWER
Use --check and --diff for dry runs. For integration testing, use Molecule with the EC2 driver to spin up temporary instances in a test AWS account. Set check_mode: yes in tasks with conditional logic to skip destructive operations. Always test in a separate AWS account or use resource tagging to isolate test resources.
01
How do you ensure idempotency when creating EC2 instances with Ansible?
SENIOR
02
What is the difference between `ec2` and `ec2_instance` modules?
SENIOR
03
How do you handle eventual consistency when creating an RDS instance in Ansible?
SENIOR
04
How do you securely manage database passwords in Ansible AWS playbooks?
SENIOR
05
What is the best practice for dynamic inventory with AWS EC2?
SENIOR
06
How do you create a VPC with subnets using Ansible?
SENIOR
07
What are common pitfalls when using Ansible to manage IAM roles?
SENIOR
08
How do you test Ansible AWS playbooks without affecting production?
SENIOR
FAQ · 8 QUESTIONS
Frequently Asked Questions
01
What is the difference between amazon.aws and community.aws collections?
amazon.aws is the official, community-maintained collection replacing community.aws. It provides modern, idempotent modules like ec2_instance, s3_bucket, and iam_role. community.aws is deprecated and should not be used for new projects.
Was this helpful?
02
How do I install the amazon.aws collection?
Run ansible-galaxy collection install amazon.aws:==5.0.0. Pin the version in requirements.yml and install with ansible-galaxy collection install -r requirements.yml.
Was this helpful?
03
Why does my EC2 instance creation fail with 'wait timeout'?
Increase wait_timeout (default 300) to 600 or more. Also check that the AMI and instance type are valid in your region. Use --vvv to see detailed API responses.
Was this helpful?
04
How do I make S3 bucket creation idempotent?
The s3_bucket module with state: present is idempotent. If the bucket exists and you own it, it reports 'ok'. If another account owns it, it fails. Use unique bucket names to avoid conflicts.
Was this helpful?
05
Can I update an IAM role's managed policies with Ansible?
Yes, but the iam_role module's managed_policies is additive. To remove a policy, you must either set managed_policies: [] and manage separately with iam_policy, or use the iam_managed_policy module.
Was this helpful?
06
How do I pass the VPC ID from one task to another?
Use `register: vpc on the VPC creation task, then reference {{ vpc.vpc.id }}` in subsequent tasks. Ensure the VPC module returns the vpc ID in the result.
Was this helpful?
07
What is the best way to handle secrets in Ansible for AWS?
Use AWS SSM Parameter Store with the aws_ssm_parameter module to store secrets, and the lookup('aws_ssm_parameter', ...) plugin to retrieve them. Always set no_log: true on tasks handling secrets.
Was this helpful?
08
How do I refresh the dynamic inventory cache?
Run ansible-inventory -i inventory/aws_ec2.yml --list --flush-cache or use the meta: refresh_inventory task in a playbook.