Write a dynamic inventory for AWS EC2 grouped by tags.
AdvancedHands-onWrite-an-Ansible-playbook tasks
Answer
# inventory/aws_ec2.yml (filename must end in aws_ec2.yml)
plugin: amazon.aws.aws_ec2
regions: [ap-south-1]
filters:
instance-state-name: running
tag:Project: devopsshack
keyed_groups:
- key: tags.Role
prefix: role
- key: tags.Environment
prefix: env
hostnames:
- private-ip-address
compose:
ansible_host: private_ip_address
ansible-inventory -i inventory/aws_ec2.yml --graph
ansible-playbook -i inventory/aws_ec2.yml site.yml --limit role_web
Key trick → keyed_groups creates groups like role_web and env_prod from tags, so playbooks target roles and never hardcode IPs. It needs boto3 and the amazon.aws collection.
More on Write-an-Ansible-playbook tasks
Write a playbook that installs and starts Nginx on Ubuntu web servers.BeginnerWrite an inventory with groups, a group of groups, and per-group variables.BeginnerWrite a playbook that deploys a config file from a Jinja2 template and restarts the service only if it changed.BeginnerWrite a role structure for a Node.js app and show what goes in each folder.IntermediateWrite a task that creates multiple users with SSH keys from a list.BeginnerWrite a rolling deploy playbook: 2 servers at a time, removed from the load balancer during the update.Advanced