AWS - Use Keyed Groups
Populate groups within a dynamic inventory of hosts deployed on AWS using keyed groups.
We'll cover the following
Limitation of groups
A limitation of the groups is that new hosts that don’t match the conditions are not accounted for. If a new EC2 instance is deployed with a Linux operating system and the Name
tag doesn’t match it won’t be added to the correct group. Using name matching is a fairly fragile and complex solution, especially if there isn’t a naming standard.
Keyed groups
Keyed groups
offer another way to define and populate groups within a dynamic inventory. Instead of specifying the group name, keyed groups base the group name on the variable’s value, and the existence of the variable determines group membership. Groups using Jinja2 conditions make the group memberships dynamic, but keyed groups make the groups and the group memberships dynamic.
Another solution is to leverage keyed groups to both create the groups and to assign group memberships dynamically.
When you deployed the ec2 instances, a tag of os
was applied to them. The value was either linux
or windows
depending on the instance image. Using tags with keyed groups in this manner allows complete control over the groups and their assignments.
Let’s update the hosts_aws_ec2.yml
with a keyed group based on the tag.os
host variable.
plugin: aws_ec2regions:- us-east-1filters:tag:app: ansible# groups:# linux: "'linux' in tags.Name"# windows: "'win' in tags.Name"keyed_groups:- key: tags.osseparator: ""
By default, the keyed_groups are populated by separators as _
. Setting the separator
parameter to ""
removes that from the group name.
Click on the Run
button and wait for the environment to set up.
plugin: aws_ec2 regions: - us-east-1 filters: tag:app: ansible # groups: # linux: "'linux' in tags.Name" # windows: "'win' in tags.Name" keyed_groups: - key: tags.os separator: ""
Once set up, you can run the ansible-inventory
command to confirm the keyed groups are correct.
ansible-inventory -i hosts_aws_ec2.yml --graph
Using the --list
option you can see the group_vars
being applied to each host.
ansible-inventory -i hosts_aws_ec2.yml --list
Run the site.yml
playbook to configure the web servers. Update the <Password>
with the password created using the ansible-vault
command in the group_vars/linux.yml
and group_vars/windows.yml
files.
ansible-playbook site.yml -i hosts_aws_ec2.yml --ask-vault-pass
Try it now
Change the hostnames
By default, the Ansible inventory hostnames are set to the Public DNS names. Use the
hostnames
parameter of theaws_ec2.yml
inventory plugin to change the hostnames to use the value of theName
tag.Review the
aws_ec2
inventory plugin documentation for an example.
In this lesson, we introduced an alternate way to group hosts using keyed_groups
.
Get hands-on with 1300+ tech skills courses.