我正在剧本中运行 shell 命令来提取命令的结果。输出
- debug: msg="{{ dblist.stdout_lines }}"
是
ok: [host] => {
"msg": [
"inst1:db1"
"inst1:db2"
"inst1:db3"
"inst2:db4"
"inst2:db3"
]
}
我需要以某种格式存储这个值,以便我能够运行我的下一个剧本,将 item.0 的值视为 inst1,将 item.1 的值视为 db2 等等。
现在
- debug: msg="{{ item.0 }} has a value {{ item.1 }}"
with_items: "{{ dblist.stdout_lines }}"
给出像这样的值
ok: [host] => (item=inst1:db1) => {
"msg": "i has a value n"
}
ok: [host] => (item=inst1:db2) => {
"msg": "i has a value n"
谢谢。
答案1
例如
- debug:
msg: "{{ _key }} has a value {{ _val }}"
loop: "{{ dblist.stdout_lines }}"
vars:
_arr: "{{ item.split(':') }}"
_key: "{{ _arr.0 }}"
_val: "{{ _arr.1 }}"
给出
msg: inst1 has a value db1
msg: inst1 has a value db2
msg: inst1 has a value db3
msg: inst2 has a value db4
msg: inst2 has a value db3
答案2
如果您使用的是足够新的版本(ansible-core> = 2.11),则可以使用split
过滤器:
- debug:
msg: "{{ item.0 }} has a value {{ item.1 }}"
loop: "{{ dblist.stdout_lines | map('split', ':') }}"
在旧版本上也可以实现类似的结果,但是比较丑陋:
- debug:
msg: "{{ item.0 }} has a value {{ item.1 }}"
loop: "{{ dblist.stdout_lines }}"
loop_control:
loop_var: _item
vars:
item: "{{ _item.split(':') }}"