# Ansible Dynamic Inventory ### What is Ansible Dynamic Inventory? #### Install boto3 and botocore ````yaml= sudo apt-get install software-properties-common -y sudo apt-add-repository universe sudo apt-get update -y sudo apt-get install python3 -y sudo apt-get install python3-pip -y sudo pip install boto3 botocore ```` :mag: boto3 and botocore are prerequisites for Ansible Dynamic inventory ***aws_ec2*** plugin #### Create a new directory "ansible-dynamic-inv" ````yaml= mkdir ansible-dynamic-inv && cd ansible-dynamic-inv ```` :mag: This directory will be used to keep all files relevant to dynamic inventory at one place. #### Copy the Private key from your laptop to Ansible Controller ````yaml= vi ansible-inv.pem ```` #### Create a new ansible.cfg file for AWS Dynamic Inventory operations ````yaml= ## vi ansible.cfg [defaults] remote_user = ec2-user private_key_file = ansible-inv.pem # pipelining = True host_key_checking = False [inventory] enable_plugins = aws_ec2 ```` #### Create dynamic inventory file with aws_ec2.yaml extension ````yaml= ## vi aws_ec2_1.yaml --- ## Dynamic inventory file for aws ec2 instances plugin: aws_ec2 aws_access_key: <your-aws-access-key> aws_secret_key: <your-aws-secret-key> aws_secret_token: <your-aws-token> regions: - us-east-1 keyed_groups: - key: tags prefix: tag ```` :mag: Please note that the file name should end in aws_ec2.[yaml|yml] only. For example: ***my-inv_aws_ec2.yaml*** #### Check / validate your configuration ````yaml= ansible-inventory -i aws_ec2.yaml --list ansible-inventory -i aws_ec2.yaml --graph ```` :mag: Now you should be able to run any ansible ad-hoc commands or playbooks against this aws_ec2.yaml inventory file using "-i" flag #### Additional Dynamic inventory settings (Optional) ````yaml=1 plugin: aws_ec2 regions: - us-west-2 filters: tag:Name: redacted keyed_groups: - key: tags.Name prefix: tag_Name # Following will display IPs instead of hostnames in the output for ansible-inventory command. hostnames: - ip-address # default is hostnames ````