我有一个看起来像这样的剧本:
- hosts: host1
gather_facts: false
tasks:
- name: "Loop"
command: "echo {{ item }}"
with_items: [ 0, 2, 4, 6, 8, 10 ]
register: hello
- debug: "msg={{ hello.results }}"
一切正常,输出返回,但有大量的吨输出。原来这个:
- debug: "msg={{ hello.results.1.stdout }}"
正是我想要的 - 只需从命令中获取stdout - 但只能通过循环六次中的一次。
我真正想要/需要做的是:
- debug: "msg={{ hello.results.*.stdout }}"
它进入hello
结构,访问results
条目,转到该数组的每个成员,并拉出stdout
值。
这可能吗?
- hosts: host1
gather_facts: false
tasks:
- name: "Loop"
command: "echo {{ item }}"
with_items: [ 0, 2, 4, 6, 8, 10 ]
register: hello
- debug:
msg: "{{item.stdout}}"
with_items: "{{hello.results}}"
并不比我原来的例子详细。
TASK [debug] *******************************************************************
ok: [host1] => (item={'_ansible_parsed': True, 'stderr_lines': [], u'cmd': [
u'echo', u'0'], u'end': u'2018-01-02 20:53:08.916774', '_ansible_no_log': False
, u'stdout': u'0', '_ansible_item_result': True, u'changed': True, 'item': 0,
u'delta': u'0:00:00.002137', u'stderr': u'', u'rc': 0, u'invocation': {u'module_
args': {u'warn': True, u'executable': None, u'_uses_shell': False, u'_raw_params
': u'echo 0', u'removes': None, u'creates': None, u'chdir': None, u'stdin': Non
e}}, 'stdout_lines': [u'0'], u'start': u'2018-01-02 20:53:08.914637', 'failed':
False}) => {
"item": {
"changed": true,
"cmd": [
"echo",
"0"
],
"delta": "0:00:00.002137",
"end": "2018-01-02 20:53:08.916774",
"failed": false,
"invocation": {
"module_args": {
"_raw_params": "echo 0",
"_uses_shell": false,
"chdir": null,
"creates": null,
"executable": null,
"removes": null,
"stdin": null,
"warn": true
}
},
"item": 0,
"rc": 0,
"start": "2018-01-02 20:53:08.914637",
"stderr": "",
"stderr_lines": [],
"stdout": "0",
"stdout_lines": [
"0"
]
},
"msg": "0"
}
我得到了上述结构的6份副本。
我觉得我很接近,但我仍然做错了什么。我在底部看到"msg": "0"
,这就是我想要的。我只是不想要其余部分。
当然。 ansible网站上有解释how to use register
in a loop的文档。您只需要迭代hello.results
数组,如:
- debug:
msg: "{{item.stdout}}"
with_items: "{{hello.results}}"
关于什么:
- debug: "msg={{ item.stdout }}"
with_items: "{{ hello.results }}"
解:
- debug: "msg={{ hello.results | map(attribute='stdout') | join('\n') }}"
备注:
默认情况下,Ansible将打印可见的\n
双字符序列而不是包装行,因此要么使用回调插件来获取人类可读输出(example),要么使用以下方法验证方法:
- copy:
content: "{{ hello.results | map(attribute='stdout') | join('\n') }}"
dest: ./result.txt
并检查result.txt
的内容。
我认为这种结构足以满足我的需求。
- hosts: localhost
gather_facts: false
vars:
stuff: [ 0,2,4,6,8,10 ]
tasks:
- name: "Loop"
command: "echo {{ item }}"
with_items: "{{ stuff }}"
register: hello
- debug: "var=hello.results.{{item}}.stdout"
with_sequence: "0-{{stuff|length - 1}}"