Ansible Dynamic Inventory
Generate Ansible inventory (host and groups) dynamically using AWS API #
Dynamic Inventory #
Ansible dynamic inventory is a feature in Ansible that allows you to generate inventory (host and group information) dynamically rather than statically defining it in a static inventory file. This dynamic approach is particularly useful in dynamic and cloud-based environments where the number and state of hosts can change frequently.
Inventory Sources: Ansible dynamic inventory sources are scripts or plugins that generate inventory data dynamically. These sources can fetch information from various sources like cloud providers, databases, or external systems.
Available sources:
- AWS EC2: AWS Ansible Dynamic Inventory Plugin.
- OpenStack: the
openstack.cloud.openstackinventory plugin. - Custom Plugins: You can write custom dynamic inventory plugins to fetch inventory data from your specific environment or system.
Dynamic Generation: when you run Ansible commands or playbooks, Ansible executes the inventory source(s) to gather the current host and group information. This information is generated on the fly based on the current state of your infrastructure.
Flexible Configuration: Ansible allows you to configure dynamic inventory sources in your Ansible configuration files (ansible.cfg) or specify them on the command line using the -i option.
Example: AWS EC2 inventory plugin #
The amazon.aws.aws_ec2 plugin reads the instances of AWS EC2 from the AWS API and creates groups from their tags and other attributes. Save this file as inventory/aws_ec2.yml:
plugin: amazon.aws.aws_ec2
regions:
- us-east-1
filters:
instance-state-name: running
keyed_groups:
# Creates groups such as tag_environment_pro from the tag "environment"
- key: tags.environment
prefix: tag_environment
- key: tags.app
prefix: tag_app
Check the result with ansible-inventory:
$ ansible-galaxy collection install amazon.aws
$ ansible-inventory -i inventory/aws_ec2.yml --graph
The groups follow the mandatory tags of AWS Tagging Best Practices, and are used as shown in Ansible Multiple Environment Best Practices and Ansible Playbook Structure Best Practices. The tutorial Terraform, AWS, and Ansible together uses the older ec2.py script, which has the same purpose.
Benefits of using dynamic inventory in Ansible #
- Scalability: Easily adapt to changing infrastructure sizes and configurations.
- Automation: Automate the process of updating your inventory as your infrastructure changes.
- Consistency: Ensure your inventory is always up to date without manual intervention.
- Integration: Seamlessly integrate with cloud providers and other external systems.
Dynamic inventory in Ansible is a powerful feature for managing infrastructure in dynamic and cloud-native environments, making it easier to automate configuration management and orchestration tasks.