目次
6. with_indexed_items の代わりにループ
序章
ansible 2.5 以前のバージョンでは、すべてのループで with_X スタイルが使用されます。しかし、バージョン 2.6 以降では、 with_X スタイル キーワードの代わりに loop キーワードを使用することが公式に推奨されています。Playbook でループを使用するには、loop キーワードを直接使用します。実際、対応する with_x 関数は、ループのさまざまな使用方法によって実現されます。
ループの使い方
1. with_list の代わりにループする
loop は with_list を置き換えることができます。ネストされたリストを処理する場合、リストはフラット化されません。
- hosts: mdb
gather_facts: no
vars:
testlist:
- a
- [b,c, [1,2]]
- d
tasks:
- name: debug groups all
debug:
msg: "{
{ item }}"
loop: "{
{ testlist }}"
2. with_flattened の代わりにループする
すべてのネストを平坦化します。
- hosts: mdb
gather_facts: no
vars:
testlist:
- a
- [b,c, [1,2]]
- d
tasks:
- name: debug groups all
debug:
msg: "{
{ item }}"
loop: "{
{ testlist | flatten }}"
3. with_items の代わりにループ
1つだけを平らにして巣に入れます。
- hosts: mdb
gather_facts: no
vars:
testlist:
- a
- [b,c, [1,2]]
- d
tasks:
- name: debug groups all
debug:
msg: "{
{ item }}"
loop: "{
{ testlist | flatten(levels=1) }}"
· レベルは 2、3、4 のいずれかです。これは、レベル 2、3、および 4 のネスティング レベルを意味します。
5. loop代替 with_dict
with_dict 関数は、dict2items フィルターで loop を使用して実現できます。
- hosts: mdb
gather_facts: no
vars:
users:
xhz:
name: xiaohaizhou
iphone: 185xxx
flf:
name: fulifang
iphone: 132xxx
tasks:
- name: debug groups all
debug:
msg: "user is {
{ item['key'] }} name is {
{ item['value']['name'] }} iphone is {
{ item['value']['iphone'] }}"
loop: "{
{ users | dict2items }}"
6. with_indexed_items の代わりにループ
loop_control キーワードと組み合わせたフラット化フィルター (およびパラメーター) を介して、with_indexed_items を置き換えることができます. 複数層のネストされたリストを扱う場合、リストの最初の層のみがフラット化されます.
- hosts: mdb
gather_facts: no
vars:
testlist:
- a
- [b,c, [1,2]]
- d
tasks:
- name: debug groups all
debug:
msg: " {
{ index }} and {
{ item }}"
loop: "{
{ testlist | flatten(levels=1) }}"
loop_control:
index_var: index
· loop_control: ループ中に要素のインデックス index_var を取得するなど、ループの動作を制御するために使用されます。
loop_control のオプションで変数を指定すると、loop_control は指定された変数にリスト要素のインデックス値を格納します。