Adding hosts to Ansible host file

ansibleansible-inventoryansible-playbook

I have been trying to add a host name to my hosts file using an Ansible playbook. My Ansible play look as below and my host file resides at /etc/ansible/hosts:

- name: adding host playbook
  hosts: localhost
  connection: local
  tasks:
  - name: add host to ansible host file
    add_host:
      name: myvm.cloud.azure.com
      groups: mymasters

Playbook executes successfully, but the new host name is not added to the Ansible hosts file. Can anybody help me on this?

Best Answer

add_host module does not add a host to your inventory file, but instead creates and adds a host to an inventory existing only in memory. You can use this inventory in subsequent plays, but it won't be saved to a file.

If you really wanted to add a host to the inventory file with Ansible, you'd need to use a regular file-editing module, like lineinfile or blockinfile.


You can also trick inifile module to handle the Ansible inventory, but it's really a hack, as the inventory file does not really have a proper INI-file structure:

- ini_file:
    dest: /etc/ansible/hosts
    section: mymasters
    option: myvm ansible_host
    value: myvm.cloud.azure.com
    no_extra_spaces: yes
Related Topic