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.

Jinja2 templateを用いて listから indexを取得する

Posted at

はじめに

Ansible templateモジュールでファイルを作成する際にインプットとなるリスト型の変数に対してインデックス番号がほしい時があります
変数を書き換えて辞書型にすることでも対応できますが、その変数を使っていた処理に影響を及ぼしてしまします

困っていた所、Jinja2テンプレートの機能を使うことで、変数はリスト型のまま変更せずにインデックス番号が取得することができました(Pythonのenumerate関数的なことができます)

ちょっと救われたのでこれを記載します

何をしたいのか

たとえば以下のようなlistがあったとします。

---
vars:
  team_member:
    - Alph
    - Brittany
    - Charlie

このlist(team_member)を元に、以下のようなファイルを作成することを目指します.

{ID: 1, Name: Alph}
{ID: 2, Name: Brittany}
{ID: 3, Name: Charlie}

どうやったのか

以下のようなtemplateを作成します。
ポイントは、loop.indexという変数です。これが読み込んだlist変数に対してindexを割り当ててくれます。

{% for member in team_member %}
{ID: {{ loop.index }}, Name: {{ member }}}
{% endfor %}

上記のtemplateを以下のplaybookを用いてファイルを生成します.

---
- name: Enumerate in jinja2 template
  hosts: localhost
  gather_facts: false
  vars:
    team_member:
      - Alph
      - Brittany
      - Charlie

  tasks:
    - name: Create
      template:
        src: ./templates/demo.jinja2
        dest: ./work/demo.txt

実行すると以下のように、期待していたファイルができあがりました.

❯❯❯ cat ./work/demo.txt
{ID: 1, Name: Alph}
{ID: 2, Name: Brittany}
{ID: 3, Name: Charlie}

その他

他にも便利なloop.xxx変数があるので利用する機会がありそうです
https://docs.ansible.com/ansible/latest/user_guide/playbooks_loops.html#extended-loop-variables

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?