Ansible: Dynamic AWS inventory with groups

I have setup a mixed (static and dynamic aws) inventory inside my ansible folder.

$ ls inventory/
ec2.ini
ec2.py
inventory.yml

The configuration for that is as follows:

$ grep 'inventory' ansible.cfg
hostfile = ./inventory
inventory_ignore_extensions = .ini, .pyc, .pyo, .retry

My static inventory has hosts grouped via the ini-style directives. e.g.:

[webservers]
host1.domain.tld
host2.domain.tld
host3.domain.tld

[database]
host4.domain.tld
host5.domain.tld
host6.domain.tld

How can I group hosts in my dynamic inventory?


When using an dynamic inventory with Ansible hosts can be grouped and addressed by using tags like this:

---
- hosts: tag_Ansible_Slave
  user: ec2-user
  become: True
  tasks:
   - name: Update all packages to latest
     yum: name=* state=latest

patterns can be used to define hosts based on the combination, intersection, etc of ec2 tags, like this: tag_webservers:&tag_Ansible_Slave

Tags can be set with Ansible with the ec2 module with the instance_tags parameter when initializing the instances in AWS.

You might want to checkout this blog post for further instructions.