Categories
Ansible

Adding Dynamic EC2 Inventory to Ansible

Working with Ansible is cool. To be able to work quickly with Ansible on AWS it can be handy to use a dynamic inventory. This has some real benefits:

  1. You don’t need to edit the inventory by hand
  2. No more typo’s or ip mismatches
  3. Automated is always better 😉

To do this you create an inventory file like this one:

---
    plugin: aws_ec2
    regions:
      - eu-central-1
    
    keyed_groups:
      - key: tags
        separator: '_'
        prefix: tag
    
    compose:
      ansible_user: "'ec2-user'"

An example. When initiate your new EC2 instance, make sure you add an application tag. For example the tag application with value webserver.

If you now want to run a playbook for certain hosts you can start you playbook this way:

---
    - hosts:  tag_application_webserver
      become: yes
      become_user: root

If you are using Ansible Tower or AWX you can also add an AWS inventory with ease.

Create dynamic inventory within AWX

Good luck and have fun.

By Stuart Eight

Love automation and virtualisation. Have a passion for programming.

Leave a Reply

Your email address will not be published. Required fields are marked *