🖥
Ansible | loop処理の with_* 系ステートメント
with_list
名前の通りリストを展開できる。
- debug:
msg: "{{ item }}"
with_list:
- hello
- ansible
- world
出力内容
hello
ansible
world
with_indexed_items
要素の何番目かを得られる。
item.0
には要素順番が入り、
item.1
には要素が入る。
item.2
以降はない。
- debug:
msg: "{{ item.0 }} - {{ item.1 }}"
with_indexed_items: ["hello", "ansible", "world"]
出力内容
0 - hello
1 - ansible
2 - world
wifh_flattend
ネストされた配列でもフラットに扱ってくれる。
- debug:
msg: "{{ item }}"
with_flattened: ["hello", ["ansible", [["world"]]]]
出力内容
hello
ansible
world
with_together
複数配列を結合して扱える。
- debug:
msg: "{{ item.0 }} {{ item.1 }} {{ item.2 }}"
with_together:
- ["hello1", "hello2", "hello3"]
- ["ansible1", "ansible2", "ansible3"]
- ["world1", "world2", "world3"]
出力内容
hello1 ansible1 world1
hello2 ansible2 world2
hello3 ansible3 world3
with_dict
辞書 ( dicionary ) を扱える。
- debug:
msg: "{{ item.key }} {{ item.value}}"
with_dict: { a: "hello", b: "ansible", c: "world" }
出力内容
a hello
b ansible
c world
with_sequence
連続を扱える。 for
文のイメージ。
開始が3で、終了が9で、3ずつインクリメントする例。
- debug:
msg: "{{ item }}"
with_sequence: start=3 end=9 stride=3 format=%02x
出力内容
03
06
09
with_subelements
ちょっと分かりにくいが、 with_subelements
の1個目にはメインの要素を渡し、2個目にはそのサブ要素を指定できる。
- debug:
msg: "name : {{ item.0.name }} , like : {{ item.1 }}"
with_subelements:
-
- name: "Alice"
likes:
- Apple
- Banana
- Microsoft
- name: Bob
likes:
- Soccer
- Basket
- likes
出力内容
name : Alice , like : Apple
name : Alice , like : Banana
name : Alice , like : Microsoft
name : Bob , like : Soccer
name : Bob , like : Basket
with_nested
渡した要素同士の全組み合わせを全て展開する。
たとえば「要素二個の配列「を「三種類」渡すと、2の3乗で 計8回のループがおこなわれる。
- debug:
msg: "{{ item.0 }} {{ item.1 }} {{ item.2 }}"
with_nested:
- ["hello", "bye"]
- ["ansible", "world"]
- ["strong", "zero"]
出力内容
hello ansible strong
hello world zero
bye ansible strong
bye world zero
hello ansible strong
hello world zero
bye ansible strong
bye world zero
with_random_choice
その名の通り、ランダムに抽出する。
- debug:
msg: "{{ item }}"
with_random_choice: ["hello", "ansible", "world"]
tags: with_random_choice
出力内容
-
ansible
(ランダム抽出なので実行のたびに変わる)
環境
- ansible 2.5.4
参考
チャットメンバー募集
何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。
公開日時
2018-07-03
Discussion