Last active
January 13, 2021 12:44
-
-
Save officel/959ae82a2df95088f90dfad0a1c3d46f to your computer and use it in GitHub Desktop.
[Q] [ansible] [how to set default value in list of dict] [GOAL]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--- | |
- name: test | |
hosts: localhost | |
become: no | |
gather_facts: no | |
vars: | |
list1_default_dict: | |
name: "unknown" | |
k1: "x" | |
k2: "x" | |
list1: | |
- name: li_1_1 | |
k1: li_1_1_k1 | |
k2: li_1_1_k2 | |
- name: li_1_2 | |
k1: li_1_2_k1 | |
- name: li_1_3 | |
list2_default_dict: | |
name: "unknown" | |
k1: "o" | |
k2: "o" | |
list2: | |
- name: li_2_1 | |
- name: li_2_2 | |
k2: li_2_2_k2 | |
- name: li_2_3 | |
tasks: | |
- debug: | |
# task を分割して、リスト毎ならこの辺り自由にデフォルト設定できるんだけれども。 | |
# msg: "{{ item.name + ' is ' + (item.k1 | default('x')) }}" | |
msg: "{{ item }}" | |
with_items: | |
# こんな感じで同じタスクを複数のリストに対して実行したい。 | |
# その際にリスト毎にデフォルトのキーと値を持たせたい。 | |
- "{{ list1 }}" | |
- "{{ list2 }}" | |
# map を使うと対象の attr だけになってしまう | |
# - "{{ list1 | map(attribute='k1', default='x') | list }}" | |
# combine でリスト1件ずつ処理できればいい気がするけど。。。 | |
# - "{{ list1 | combine(list1_default_dict, list_merge='keep') }}" | |
- name: ansible-jp で教えてもらったもの | |
debug: | |
msg: "{{ item[1] | combine(item[0]) }}" | |
with_items: | |
- '{{ list1 | zip_longest([],fillvalue=list1_default_dict) | list }}' | |
- '{{ list2 | zip_longest([],fillvalue=list2_default_dict) | list }}' | |
- name: ansible-jp で教えてもらったもの2 | |
debug: | |
msg: "{{ x.name + ' is ' + x.k1 }}" | |
vars: | |
x: "{{ item[1] | combine(item[0]) }}" | |
with_items: | |
- '{{ list1 | zip_longest([],fillvalue=list1_default_dict) | list }}' | |
- '{{ list2 | zip_longest([],fillvalue=list2_default_dict) | list }}' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ansible-jp で質問してみたら教えてもらえたのでアップデート。
https://ansiblejp.slack.com/archives/CBV59MFV0/p1610516837077200