Ansible:使用列表及其内容作为变量值
Ansible: use both lists and their contents as variable values
我有以下形式的键-值对关联:
- mykey1:
myvalues1: ['a', 'b', 'c']
- mykey2:
myvalues2: ['d', 'e']
- mykey3:
myvalues3: ['f']
我知道使用 with_dict
构造我可以遍历键和值(它们是列表)。
我的问题是我怎样才能有一个循环遍历列表的(值)元素?
我希望能够实现的输出是:
a', 'b', 'c', 'd', 'e', 'f'
问题是我需要维护上面的关联。
有没有办法避免重复列表声明?
我不太确定是否可以使用动态键。但假设以下 vars 文件没有 1,2 和 3:
rootitem:
- mykey:
myvalues: ['a', 'b', 'c']
- mykey:
myvalues: ['d', 'e']
- mykey:
myvalues: ['f']
可以使用 "with_subelements" 和以下示例:
- name: iterate over list
debug:
msg: "the current item is{{ item.0 }} and all subitems are {{ item.1 }}"
with_subelements:
- "{{ rootitem }}"
- mykey.myvalues
这导致 6 次迭代,每次迭代一次 "a,b,c,d,e,f"。
这是我想出的结构:
associations:
- { key: mykey1, myvalues: ['a', 'b', 'c', ] }
- { key: mykey2, myvalues: ['d', 'e'] }
- { key: mykey3, myvalues: ['f'] }
当有人想要将值迭代为单个值
- name: List single items
debug:
msg: "{{ item.1 }}"
with_subelements:
- associations
- myvalues
当有人想要迭代值时 作为列表
- name: List lists (no pun intended)
debug:
msg: "{{ item.myvalues }}"
with_items: associations
我有以下形式的键-值对关联:
- mykey1:
myvalues1: ['a', 'b', 'c']
- mykey2:
myvalues2: ['d', 'e']
- mykey3:
myvalues3: ['f']
我知道使用 with_dict
构造我可以遍历键和值(它们是列表)。
我的问题是我怎样才能有一个循环遍历列表的(值)元素?
我希望能够实现的输出是:
a', 'b', 'c', 'd', 'e', 'f'
问题是我需要维护上面的关联。 有没有办法避免重复列表声明?
我不太确定是否可以使用动态键。但假设以下 vars 文件没有 1,2 和 3:
rootitem:
- mykey:
myvalues: ['a', 'b', 'c']
- mykey:
myvalues: ['d', 'e']
- mykey:
myvalues: ['f']
可以使用 "with_subelements" 和以下示例:
- name: iterate over list
debug:
msg: "the current item is{{ item.0 }} and all subitems are {{ item.1 }}"
with_subelements:
- "{{ rootitem }}"
- mykey.myvalues
这导致 6 次迭代,每次迭代一次 "a,b,c,d,e,f"。
这是我想出的结构:
associations:
- { key: mykey1, myvalues: ['a', 'b', 'c', ] }
- { key: mykey2, myvalues: ['d', 'e'] }
- { key: mykey3, myvalues: ['f'] }
当有人想要将值迭代为单个值
- name: List single items
debug:
msg: "{{ item.1 }}"
with_subelements:
- associations
- myvalues
当有人想要迭代值时 作为列表
- name: List lists (no pun intended)
debug:
msg: "{{ item.myvalues }}"
with_items: associations