1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Ansible】templateモジュールを使わずに、jinja2のloop.indexが使いたい

Last updated at Posted at 2020-12-11

はじめに

<バージョン>
ansible 2.9.1
jinja2 2.11

jinja2ではfor文でループする際に、「現在何ループ目か」を表す変数loop.indexが存在します。
Ansibleではtemplateモジュールによりこの変数を使えるのですが、
このモジュールを使わずにloop.indexを使う方法はあるのかというお話をします。

jinja_sample.j2
{% set list_sample = ['a', 'b', 'c'] %}
{% for tmp in list_sample %}
{{ loop.index }}: {{ tmp }}
{% endfor %}
出力
1: a
2: b
3: c

Playbookの紹介

Ansible Documentationを見ると、どうやらAnsible2.8からloopの拡張機能としてloop.indexが
使えるようになったようです。その代わり、ansibleとjinja2で変数名が異なります。
 jinja2: loop.index
 Ansible: ansible_loop.index
また、loop_controlの拡張機能を使うことを宣言しないとエラーになるので注意しましょう。

loop_test.yml
---
- name: "loop test"
  hosts: localhost
  gather_facts: no
  vars:
    list_sample:
      - a
      - b
      - c
  tasks:
    - name: "debug loop"
      debug:
        msg: >-
          {{ ansible_loop.index }}: {{ item }}
      loop: "{{ list_sample }}"
      loop_control:    # ポイント
        extended: yes

実行結果

想定通り、ansible_loop.indexに1~3の値が代入されていることが確認できます。

出力
[ec2-user@ip-<ip addr> ansible]$ ansible-playbook loop_test.yml

PLAY [loop test] *******************************************************************************************************

TASK [debug loop] ******************************************************************************************************
ok: [localhost] => (item=a) =>
  msg: '1: a'
ok: [localhost] => (item=b) =>
  msg: '2: b'
ok: [localhost] => (item=c) =>
  msg: '3: c'

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

参考記事

Jinja - Jinja Documentation
Loops - Ansible Documentation

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?