ansible blockinfile to add several hosts to file /etc/hosts
[root@localhost ~]# cat etchosts.yml
- hosts: localhost
become: true
tasks:
- name: Add mappings to /etc/hosts
blockinfile:
path: /etc/hosts
block: |
{{ item.ip }} {{ item.name }}
marker: "# {mark} ANSIBLE MANAGED BLOCK {{ item.name }}"
with_items:
- { name: host1, ip: 192.168.0.108 }
- { name: host2, ip: 192.168.0.109 }
- { name: host3, ip: 192.168.0.110 }
[root@localhost ~]#
[root@localhost ~]# ansible-playbook etchosts.yml
PLAY [localhost] ***************************************************************
TASK [Gathering Facts] *********************************************************
ok: [localhost]
TASK [Add mappings to /etc/hosts] **********************************************
changed: [localhost] => (item={u'ip': u'192.168.0.108', u'name': u'host1'})
changed: [localhost] => (item={u'ip': u'192.168.0.109', u'name': u'host2'})
changed: [localhost] => (item={u'ip': u'192.168.0.110', u'name': u'host3'})
PLAY RECAP *********************************************************************
localhost : ok=2 changed=1 unreachable=0 failed=0
[root@localhost ~]# cat /etc/hosts
192.168.0.104 localhost
# BEGIN ANSIBLE MANAGED BLOCK host1
192.168.0.108 host1
# END ANSIBLE MANAGED BLOCK host1
# BEGIN ANSIBLE MANAGED BLOCK host2
192.168.0.109 host2
# END ANSIBLE MANAGED BLOCK host2
# BEGIN ANSIBLE MANAGED BLOCK host3
192.168.0.110 host3
# END ANSIBLE MANAGED BLOCK host3
[root@localhost ~]#
- hosts: localhost
become: true
tasks:
- name: Add mappings to /etc/hosts
blockinfile:
path: /etc/hosts
block: |
{{ item.ip }} {{ item.name }}
marker: "# {mark} ANSIBLE MANAGED BLOCK {{ item.name }}"
with_items:
- { name: host1, ip: 192.168.0.108 }
- { name: host2, ip: 192.168.0.109 }
- { name: host3, ip: 192.168.0.110 }
[root@localhost ~]#
[root@localhost ~]# ansible-playbook etchosts.yml
PLAY [localhost] ***************************************************************
TASK [Gathering Facts] *********************************************************
ok: [localhost]
TASK [Add mappings to /etc/hosts] **********************************************
changed: [localhost] => (item={u'ip': u'192.168.0.108', u'name': u'host1'})
changed: [localhost] => (item={u'ip': u'192.168.0.109', u'name': u'host2'})
changed: [localhost] => (item={u'ip': u'192.168.0.110', u'name': u'host3'})
PLAY RECAP *********************************************************************
localhost : ok=2 changed=1 unreachable=0 failed=0
[root@localhost ~]# cat /etc/hosts
192.168.0.104 localhost
# BEGIN ANSIBLE MANAGED BLOCK host1
192.168.0.108 host1
# END ANSIBLE MANAGED BLOCK host1
# BEGIN ANSIBLE MANAGED BLOCK host2
192.168.0.109 host2
# END ANSIBLE MANAGED BLOCK host2
# BEGIN ANSIBLE MANAGED BLOCK host3
192.168.0.110 host3
# END ANSIBLE MANAGED BLOCK host3
[root@localhost ~]#
Comments
Post a Comment