ansible loopでindexを取得する。

ansibleで、タスクを配列の要素数だけループさせるときに、
各ループのインデックスを取得する方法の備忘録

インデックスを取得するために、loop_controlのindex_varを使用する。
indexは0から取得できる。

〇indexを取得するサンプルプレイブック

---
- name: Example of getting index with loop in Ansible
  hosts: localhost
  vars:
    items:
      - name: item1
      - name: item2
      - name: item3
  tasks:
    - name: Print item with index
      debug:
        msg: "Item {{ index }}: {{ item.name }}"
      loop: "{{ items }}"
      loop_control:
        index_var: index

〇実行結果

[root@629bed370fc3 workspace]# ansible-playbook sample.yml
[WARNING]: No inventory was parsed, only implicit localhost is available
[WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all'


PLAY [Example of getting index with loop in Ansible] *****************************************************************************************************

TASK [Print item with index] *****************************************************************************************************************************
ok: [localhost] => (item={'name': 'item1'}) => {
    "msg": "Item 0: item1"
}
ok: [localhost] => (item={'name': 'item2'}) => {
    "msg": "Item 1: item2"
}
ok: [localhost] => (item={'name': 'item3'}) => {
    "msg": "Item 2: item3"
}

PLAY RECAP ***********************************************************************************************************************************************
localhost                  : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0  

〇その他
indexに、+1する場合は、{{}}の中に入れる。

    - name: Print item with index
      debug:
        msg: "Item {{ index + 1 }}: {{ item.name }}"
      loop: "{{ items }}"
      loop_control:
        index_var: index

index > 1のときのみ、処理するようにする。

    - name: Print item with index
      debug:
        msg: "Item {{ index }}: {{ item.name }}"
      loop: "{{ items }}"
      loop_control:
        index_var: index
      when: index > 1

loopの際に、pauseを入れる。

    - name: debug
      debug: msg="test"
      loop: "{{ range(2) | list }}"
      loop_control:
        pause: 5