我正在尝试在 ansible 中创建一个包含一些 docker 容器信息的列表。首先,我运行一个命令模块,该模块在 stdout 中返回以下内容:
"map[key1:value1 key2:value2 key3:value3]"
我如何进一步解析它以获取基于我提供的键的值?当我使用过滤器时map
,我得到以下信息:
"msg": "<generator object do_map at 0x7f3845b8a740>"
如果我运行list
过滤器,我只会得到映射中每个字符的输出,所以 [“m”,“a”,“p”,“[”,“k”,...]
我应该使用什么过滤器?
答案1
例如
- 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