如何根据密钥隔离 ansible 输出

如何根据密钥隔离 ansible 输出

我试图隔离 ansible playbook 的输出,但它说"output.stdout": "VARIABLE IS NOT DEFINED!"

我的剧本代码是: --- - hosts: localhost tasks: - name: Register variable shell: "echo {{ item }}" loop: - "one" - "two" register: output - debug: var: output.stdout

有趣的是,如果我不利用密钥隔离它,调试输出就能正常工作stdout

TASK [Register variable] ***********************************************************************************************************************************************
changed: [localhost] => (item=one)
changed: [localhost] => (item=two)

TASK [debug] ***********************************************************************************************************************************************************
ok: [localhost] => {
    "output": {
        "changed": true,
        "msg": "All items completed",
        "results": [
            {
                "ansible_loop_var": "item",
                "changed": true,
                "cmd": "echo one",
                "delta": "0:00:00.002986",
                "end": "2020-01-24 00:20:57.226744",
                "failed": false,
                "invocation": {
                    "module_args": {
                        "_raw_params": "echo one",
                        "_uses_shell": true,
                        "argv": null,
                        "chdir": null,
                        "creates": null,

我究竟做错了什么 ?

答案1

https://docs.ansible.com/ansible/latest/user_guide/playbooks_loops.html#registering-variables-with-a-loop

当您使用循环寄存器时,放置在变量中的数据结构将包含一个结果属性,该属性是来自模块的所有响应的列表

因此:

output.results[0].stdout
output.results[1].stdout

答案2

一种更简单的方法是循环到单独的 .yml 文件(通过 include),它将执行温和的操作 + 输出。例如:

主要.yml:

- name: RUN start.yml
  include: start.yml
  vars:
    app: "{{ item.name }}"
  static: false
  with_items: "{{ list_items }}"

start.yml 的作用相同:

- name: "Run {{ app }}"
  command: './runapp.sh {{ app }}'
  register: start_app_register
  no_log: True

- debug:
    msg: '{{ start_app_register.stdout }}'

相关内容