Adding hosts to Ansible host file

2019-05-30 15:42发布

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?

2条回答
Luminary・发光体
2楼-- · 2019-05-30 15:50

You can use template to create hosts file.

Task File

---
- name: Create HostsFile
  hosts: development
  user: vagrant
  become: yes
  become_method: sudo

  tasks:
    - name: Run the Template
      template: src=hostsFile.j2 dest=/tmp/file.conf owner=root group=root

Template File :- HostsFile.j2

{{ ansible_managed }}

127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6


{% for group in groups %}
{% if groups[group] and group != 'all' %}
{% for host in groups[group] %}
{{hostvars[host].ansible_default_ipv4.address}} {{ ansible_hostname }}
{% endfor %}

{% endif %}
{% endfor %}
查看更多
疯言疯语
3楼-- · 2019-05-30 16:08

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
查看更多
登录 后发表回答