0

I need to save the target host's IP addresses to a file using set_fact. Below is my playbook, but it's giving output as a list.

  hosts:  all
  tasks:
    - set_fact:
        data:  "{{ ansible_all_ipv4_addresses }}"
    - set_fact:
        ip: "{{ data.split(',')  }}"

    - name: Show the devices
      shell: echo {{ item }} >> /tmp/ips
      with_items: "{{  ip  }}"

output: ok: [system1] => { "data": [ "172.19.0.1", "172.18.0.1", "172.20.0.1", "172.17.0.1", "172.16.108.124", "10.0.41.117" ] }

cat /tmp/ips
[u'172.19.0.1', u'172.18.0.1', u'172.20.0.1', u'172.17.0.1', u'172.16.108.124', u'10.0.41.117']


Desired o/p is 
 172.168.1.21
 172.168.1.22
0

Instead of

shell: echo {{ item }} >> /tmp/ips
with_items: "{{  ip  }}"

Use template.

template:
  src: ips.j2
  dest: /tmp/ips

with template ips.j2

{% for item in ip %}
{{ item }}
{% endfor %}
0

ansible_all_ipv4_addresses is already an array so you don't need to split it:

- copy:
    dest: /tmp/ips
    content: "{{ ansible_all_ipv4_addresses | join('\n') }}"

This will produce the desired output.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.