iterate counter within loop

25 views
Skip to first unread message

David Bush

unread,
Sep 8, 2020, 9:37:36 AM9/8/20
to Ansible Project
Hi All,

I am after some advise please as I am struggling to think of a method to do this.

I have a task in a role that needs to create a file on each target host in a host-group that should look like this:
 
server.0=<host1_ip>:1234
server.1=<host2_ip>:1234
server.2=<host3_ip>:1234

I can get the host IPs to work using `groups[<group_name>]`.
I am stuck on how to iterate the server.x counter in each line.

I have tried using something like this:

- name: create dynamic config file
  lineinfile:
  path: <file_path>
  line: server.{{ item.hostIndex }}={{ item.hostIp }}:2888:3888;2181
  with_items:
    - { hostIndex: "{{ [play_hosts.index(inventory_hostname)] }}", hostIp: "{{ groups[ <group_name>] }}" }

but of course it only uses the index from the host running the play :-( 

What I would like to do is set a counter for say 0, then iterate that on each loop for hosts in `groups[ <group_name>]`.

I could not see a way to do this within a task - is this possible and if so what would be the method to use.

Thanks in advance...


Stefan Hornburg (Racke)

unread,
Sep 8, 2020, 11:15:59 AM9/8/20
to ansible...@googlegroups.com
This look like a list of nodes in cluster, is that correct?

You can create a list as follows (replace all with your group name):

{% for host in groups['all'] %}
server.{{ loop.index }}={{ hostvars[host]['ansible_default_ipv4']['address'] }}:1234
{% endfor %}"

lineinfile is not appropriate (what happens when a node is removed ?), use blockinfile
or template.

Regards
Racke

>
> --
> You received this message because you are subscribed to the Google Groups "Ansible Project" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to
> ansible-proje...@googlegroups.com <mailto:ansible-proje...@googlegroups.com>.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/ansible-project/aad38c87-0410-4c95-b3a1-c5b8a1202cebn%40googlegroups.com
> <https://groups.google.com/d/msgid/ansible-project/aad38c87-0410-4c95-b3a1-c5b8a1202cebn%40googlegroups.com?utm_medium=email&utm_source=footer>.


--
Ecommerce and Linux consulting + Perl and web application programming.
Debian and Sympa administration. Provisioning with Ansible.

signature.asc

Stefan Hornburg (Racke)

unread,
Sep 8, 2020, 11:17:56 AM9/8/20
to ansible...@googlegroups.com
Little correction:

Use {{ loop.index - 1 }} instead of {{ loop.index }}

Regards
Racke
signature.asc
Reply all
Reply to author
Forward
0 new messages