Interview Prep/Real-World Interview/Write-an-Ansible-playbook tasks

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.

All Real-World Interview questions Roadmap: Interview readiness

More on Write-an-Ansible-playbook tasks