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?
You can use template to create hosts file.
Task File
Template File :- HostsFile.j2
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
orblockinfile
.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: