The play below shows how you can use the index
- hosts: all
tasks:
- debug:
msg: "Copy {{ file }} to {{ item }}"
loop: "{{ ansible_play_hosts_all }}"
loop_control:
extended: true
vars:
index: "{{ '%02d' % ansible_loop.index }}"
file: "/kafka_certification/kafka.server{{ index }}.keystore.jk"
run_once: true
delegate_to: localhost
gives (abridged)
msg: Copy /kafka_certification/kafka.server01.keystore.jk to app01
msg: Copy /kafka_certification/kafka.server02.keystore.jk to app02
msg: Copy /kafka_certification/kafka.server03.keystore.jk to app03
msg: Copy /kafka_certification/kafka.server04.keystore.jk to app04
msg: Copy /kafka_certification/kafka.server05.keystore.jk to app05
msg: Copy /kafka_certification/kafka.server06.keystore.jk to app06
There is a simpler approach. The play below gives the same result without iteration
- hosts: all
tasks:
- debug:
msg: "Copy {{ file }} to {{ inventory_hostname }}"
vars:
idx: "{{ ansible_play_hosts_all.index(inventory_hostname) + 1 }}"
index: "{{ '%02d' % idx|int }}"
file: "/kafka_certification/kafka.server{{ index }}.keystore.jk"
This option complies with the Ansible context. See Plays:
... playbook object maps managed nodes (hosts) to tasks.
Q: "Copy file to all nodes. Use loop.index on inventory host group [all_servers]"
A: In this particular case the play below gives the same result
- hosts: all_servers
tasks:
- debug:
msg: "Copy {{ file }} to {{ inventory_hostname }}"
vars:
idx: "{{ groups.all_servers.index(inventory_hostname) + 1 }}"
index: "{{ '%02d' % idx|int }}"
file: "/kafka_certification/kafka.server{{ index }}.keystore.jk"
PLAY [all_servers] ****************************************************************************
TASK [debug] **********************************************************************************
ok: [app02] =>
msg: Copy /kafka_certification/kafka.server02.keystore.jk to app02
ok: [app01] =>
msg: Copy /kafka_certification/kafka.server01.keystore.jk to app01
ok: [app04] =>
msg: Copy /kafka_certification/kafka.server04.keystore.jk to app04
ok: [app03] =>
msg: Copy /kafka_certification/kafka.server03.keystore.jk to app03
ok: [app05] =>
msg: Copy /kafka_certification/kafka.server05.keystore.jk to app05
ok: [app06] =>
msg: Copy /kafka_certification/kafka.server06.keystore.jk to app06
PLAY RECAP ************************************************************************************
app01: ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
app02: ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
app03: ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
app04: ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
app05: ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
app06: ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0