1

I have several IPs in my Ansible hosts file and would like to have it listed in the file that will be copied to each of these hosts. Say, this hosts are 1.1.1.1, 1.1.2.3 etc, and the is file on each of the hosts named list.txt should contain the following:

All hosts in the group are: 1.1.1.1, 1.1.2.3

I do understand I can copy file with static content or I can iterate over vars set separately but how to iterate over host list entries?

1 Answer 1

2

Q: "How to iterate over host list entries?"

A: There are 2 standard options. Either special variable ansible_play_hosts_all or groups. For example, with the inventory

shell> cat hosts
10.1.0.51
10.1.0.52
10.1.0.53

both templates

shell> cat list1.txt.j2 
All hosts in the group are: 
{%- for host in ansible_play_hosts_all -%}
{{ host }}{% if not loop.last %}, {% endif %}{% endfor %}

shell> cat list2.txt.j2 
All hosts in the group are: 
{%- for host in groups.all -%}
{{ host }}{% if not loop.last %}, {% endif %}{% endfor %}

and the playbook

shell> cat playbook.yml
- hosts: all
  tasks:
    - template:
        src: list1.txt.j2
        dest: /tmp/list.txt

give on all remote hosts

shell> cat /tmp/list.txt
All hosts in the group are:10.1.0.51, 10.1.0.52, 10.1.0.53

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .