Dynamic inventory management is essential for DevOps teams managing cloud infrastructure at scale. This task focuses on integrating dynamic inventory scripts with Ansible for cloud providers (AWS EC2, Azure) to automate inventory updates, resource tagging, and grouping based on metadata. The implementation will ensure that inventory is always up to date, reducing manual overhead and improving efficiency in cloud infrastructure management.
The high-level architecture consists of:
Install Ansible inventory plugins:
ansible-galaxy collection install amazon.aws
ansible-galaxy collection install azure.azcollection
plugin: amazon.aws.aws_ec2
regions:
- us-east-1
- us-west-1
filters:
tag:Environment: production
keyed_groups:
- key: tags.Name
prefix: tag_
- key: instance_type
prefix: type_
plugin: azure.azcollection.azure_rm
auth_source: auto
keyed_groups:
- key: tags.Environment
prefix: env_
- key: location
prefix: region_
Test dynamic inventory:
ansible-inventory -i aws_inventory.yaml --graph
ansible-inventory -i azure_inventory.yaml --graph
import boto3
ec2 = boto3.client('ec2')
instances = ec2.describe_instances()
for reservation in instances['Reservations']:
for instance in reservation['Instances']:
instance_id = instance['InstanceId']
ec2.create_tags(
Resources=[instance_id],
Tags=[{'Key': 'Environment', 'Value': 'Production'}]
)
az resource tag --resource-group myResourceGroup --tags Environment=Production
Create Jenkins Pipeline for Inventory Updates:
pipeline {
agent any
stages {
stage('Fetch AWS Inventory') {
steps {
sh 'ansible-inventory -i aws_inventory.yaml --graph'
}
}
stage('Fetch Azure Inventory') {
steps {
sh 'ansible-inventory -i azure_inventory.yaml --graph'
}
}
stage('Deploy Playbook') {
steps {
sh 'ansible-playbook -i aws_inventory.yaml deploy.yml'
}
}
}
}
This project provides a scalable solution for dynamic inventory management, making cloud infrastructure more manageable and efficient.