linuxfan
linuxfan

Reputation: 1160

Updating /etc/ansible/hosts with ansible

I want to update just one entry from inventory file /etc/ansible/hosts depending on some conditions (e.g. change in network properties). From this snippet of my inventory file, I would like to update the entry under [south_side_hosts]. Is there a way, with ansible, to update this file? I could write a python script to parse and update the file but was hoping to find a solution with ansible.

[south_side_hosts]
sshost.eng.corp.com

[south_side_ips]
192.168.100.2

[num_hosts]
83

Upvotes: 2

Views: 2143

Answers (1)

Thomas Hirsch
Thomas Hirsch

Reputation: 2308

The format of the inventory file is INI, as stated in the documentation.

So the ini_file module can work. Use allow_no_value: true, and two tasks to remove the old "option" and add the new one:

- name: Remove host from 'south_side_hosts' group
  ini_file:
    path: /etc/ansible/hosts
    section: south_side_hosts
    option: sshost.eng.corp.com
    state: absent

- name: Add host to 'south_side_hosts' group
  ini_file:
    path: /etc/ansible/hosts
    section: south_side_hosts
    option: sshost2.eng.corp.com
    allow_no_value: true

You need to refresh the inventory after this, if you want to configure the new host from the same playbook:

- name: Refresh the inventory
  meta: refresh_inventory

Note that if you intend to do this with random hostnames that you pass on the command line, then a dynamic inventory might indeed be what you are looking for in the long run.

Upvotes: 2

Related Questions