Ansible
如何解析地圖?
我正在嘗試在 ansible 中創建一個列表,其中包含一些 docker 容器資訊。首先,我正在執行一個命令模組,它在標準輸出中返回:
"map[key1:value1 key2:value2 key3:value3]"
如何進一步解析它以根據我提供的鍵獲取值?當我使用
map
過濾器時,我得到了這個:
"msg": "<generator object do_map at 0x7f3845b8a740>"
如果我執行
list
過濾器,我只會得到地圖中每個字元的輸出,所以$$ “m”, “a”, “p”, “[”, “k”, … $$ 我應該使用什麼過濾器?
例如
- set_fact: x: "{{ _dict|from_yaml }}" vars: _regex: '^(.*)\[(.*)\](.*)$' _key: "{{ stdout|regex_replace(_regex, '\\1') }}" _val: "{{ stdout|regex_replace(_regex, '\\2') }}" _dict: | {{ _key }}: {% for i in _val.split() %} {{ i|regex_replace(':', ': ') }} {% endfor %}
給
x: map: key1: value1 key2: value2 key3: value3
如果有更多行,例如
stdout_lines: - "map1[key1:value1 key2:value2 key3:value3]" - "map2[key1:value1 key2:value2 key3:value3]" - "map3[key1:value1 key2:value2 key3:value3]"
可以結合字典,例如
- set_fact: x: "{{ x|d({})|combine(_dict|from_yaml) }}" loop: "{{ stdout_lines }}" vars: _regex: '^(.*)\[(.*)\](.*)$' _key: "{{ item|regex_replace(_regex, '\\1') }}" _val: "{{ item|regex_replace(_regex, '\\2') }}" _dict: | {{ _key }}: {% for i in _val.split() %} {{ i|regex_replace(':', ': ') }} {% endfor %}
給
x: map1: key1: value1 key2: value2 key3: value3 map2: key1: value1 key2: value2 key3: value3 map3: key1: value1 key2: value2 key3: value3
如果鍵重複,例如
stdout_lines: - "map[key1:value1 key2:value2 key3:value3]" - "map[key1:value1 key2:value2 key3:value3]" - "map[key1:value1 key2:value2 key3:value3]"
可以連接一個列表,例如
- set_fact: x: "{{ x|d([]) + [_dict|from_yaml] }}" loop: "{{ stdout_lines }}" vars: _regex: '^(.*)\[(.*)\](.*)$' _key: "{{ item|regex_replace(_regex, '\\1') }}" _val: "{{ item|regex_replace(_regex, '\\2') }}" _dict: | {{ _key }}: {% for i in _val.split() %} {{ i|regex_replace(':', ': ') }} {% endfor %}
給
x: - map: key1: value1 key2: value2 key3: value3 - map: key1: value1 key2: value2 key3: value3 - map: key1: value1 key2: value2 key3: value3