Search code examples
ansibleansible-inventory

Reload Ansible's dynamic inventory


I'm using Ansible to setup EC2 instances and deploy an application. There's a hosts script which gathers tags related servers and groups info. I'd like to run these actions as a single playbook, so

  1. New instances are created if needed
  2. Hosts script loads inventory (including servers' facts)
  3. Deployment playbook works

However, the inventory is loaded in advance, so, there is no servers/groups data if servers are created/updated during the play. I can

  1. separate provision and deployment playbooks
  2. use add_host trick to emulate dynamic inventory when servers are updated

But, there are drawbacks in those approaches.

Can I force Ansible to reload inventory?
My test files are: hosts script:

#!/bin/sh
echo `date` >> log.log
echo "{\"standalone\":[\"localhost\"]}"

Sample playbook.yml:

---
- hosts: all
  tasks:
    - name: show inventory_hostname
      command: echo {{ inventory_hostname }}

I run it with the command ansible-playbook -i hosts playbook.yml -v and see two runs:

$> cat log.log
Thu Mar 12 09:43:16 SAMT 2015
Thu Mar 12 09:43:16 SAMT 2015

but I haven't found a command to double it.


Solution

  • With Ansible 2.0+, you can refresh your inventory mid-play by running the task:

    - meta: refresh_inventory