Day-24: Ansible Dynamic Inventory real time practical.

Mokadi Surya Prasad
2 min readDec 3, 2024

--

What is a Dynamic Inventory?

Dynamic inventories in Ansible allow you to source your inventory data from external systems dynamically. This can be from cloud providers, databases, or any system that can output JSON formatted to Ansible’s specifications. Dynamic inventories ensure that your playbook runs reflect the current state of your systems, without needing manual updates to inventory files.

Why Use Dynamic Inventories?

  • Scalability: Automatically adapts to changes in your infrastructure.
  • Accuracy: Ensures that your playbooks use the most current server information.
  • Flexibility: Easily integrates with cloud providers and other dynamic systems.

Basic Usage of Dynamic Inventories

Dynamic inventories are typically scripts or programs that output JSON formatted in a specific way that Ansible can understand. Ansible ships with several ready-to-use dynamic inventory scripts for popular cloud platforms like AWS, Azure, and Google Cloud. Now we can login to the AWS EC2 console with root access and move to the ansible location /etc/ansible/ then create new one file.

cp ansible.cfg /tmp/

. Now we can clone the client’s git repo into ansible-files location then enter the below commands to create clients’ servers with terraform.

cd ansible-files
git clone https://github.com/mokadi-suryaprasad/Ansible-day-01.git
terraform init
terraform apply --var-file "15.terraform.tfvars" --auto-approve

. Now we can edit the ansible.cfg file like this enable_plugin=aws_ec2
inventory= /etc/ansible/aws_ec2.yaml

. Now we can create the aws_ec2.yaml file in the location.

nano aws_ec2.yaml
plugin: aws_ec2
regions:
- us-east-1
keyed_groups:
- key: tags
prefix: tag

- prefix: instance_type
key: instance_type

- key: placement.region
prefix: aws_region

. Now we need to install the related python dependencies to run the plugin.

sudo apt update
sudo apt-get install python3-pip -y
sudo apt install python3-boto3
curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
unzip awscliv2.zip
sudo ./aws/install

aws --version

. Now we can run the aws_ec2 plugin with the below command.

ansible-inventory -i /etc/ansible/aws_ec2.yaml --list
ansible-inventory -i /etc/ansible/aws_ec2.yaml --list | jq

. Now we can call the instances with the dynamic way with managed tags.

ansible -i /etc/ansible/aws_ec2.yaml tag_Terraform_Managed_Yes -m ping

. Now we can export the directory with the below name and we can easily call the command no need to mention the directory name.

export dynamic='/etc/ansible/aws_ec2.yaml'
ansible-inventory -i /etc/ansible/aws_ec2.yaml --graph
ansible -i $dynamic instance_type_t2_medium -m shell -a "df-h"
ansible-playbook -i $dynamic playbooks01/8.Dyanmic-Inventory/dynamic_nginx-jinja2.yml

--

--

Mokadi Surya Prasad
Mokadi Surya Prasad

No responses yet