Static inventories go stale in the cloud. The amazon.aws.aws_ec2 plugin builds inventory from the API.
ansible-galaxy collection install amazon.aws
pip install boto3 botocore
inventory/aws_ec2.yml:
plugin: amazon.aws.aws_ec2
regions: [ap-south-1]
filters:
tag:Env: prod
instance-state-name: running
keyed_groups:
- key: tags.Role
prefix: role
hostnames: [private-ip-address]
ansible-inventory -i inventory/aws_ec2.yml --graph
ansible role_web -i inventory/aws_ec2.yml -m ping
ansible-playbook -i inventory/aws_ec2.yml site.yml --limit role_web
Instances tagged Role=web land in the group role_web automatically. Use a controller with an IAM role granting ec2:DescribeInstances. For servers with no SSH exposure, the community.aws.aws_ssm connection plugin runs Ansible through Systems Manager Session Manager, which needs an S3 bucket for file transfer.