Ansible Tips & Tricks - Static Inventory Manipulation

I recently faced the challenge that I needed to modify the Ansible inventory (/etc/ansible/hosts) from within a playbook. My use-case was to build the node names and put them into the Ansible hosts file. (Note that for my simple use-case I did not want to use a dynamic inventory.)

While manipulating the hosts file quite simple from a Ansible playbook perspective, the interesting part lies in the fact that the inventory file is read before processing of plays starts. So what I needed was some way to dynamically update the node set, or simply reload the inventory from within my playbook.

The latter, as it turned out, is actually quite simple!
There is a meta task named refresh_inventory for exactly that purpose!

See the example below:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
- name: replace something in Ansible inventory
  replace:
    path: /path/to/my/hosts
    regexp: foo
    replace: bar
    backup: no

- name: Refresh inventory file to get updated inventory node names
  meta: refresh_inventory

- name: test new inventory
  ping:  

Thanks to fredl for discovering this not-so-well-known Ansible task.

updatedupdated2019-04-162019-04-16