Ansible 解析 JSON 输出

Ansible 解析 JSON 输出

我正在使用 URI 将 JSOn 输出到名为“vchosts”的寄存器

TASK [debug] *************************************************************************************************************************************************************************************************
ok: [localhost] => {
    "vchosts": {
        "changed": false,
        "msg": "All items completed",
        "results": [
            {
                "_ansible_ignore_errors": null,
                "_ansible_item_result": true,
                "_ansible_no_log": false,
                "_ansible_parsed": true,
                "changed": false,
                "connection": "close",
                "content_type": "application/json",
                "cookies": {},
                "date": "Mon, 11 Jun 2018 09:50:45 GMT",
                "failed": false,
                "invocation": {
                    "module_args": {
                        "attributes": null,
                        "backup": null,
                        "body": null,
                        "body_format": "raw",
                        "client_cert": null,
                        "client_key": null,
                        "content": null,
                        "creates": null,
                        "delimiter": null,
                        "dest": null,
                        "directory_mode": null,
                        "follow": false,
                        "follow_redirects": "safe",
                        "force": false,
                        "force_basic_auth": true,
                        "group": null,
                        "headers": {
                            "Cookie": "vmware-api-session-id=56fa6d3015150212b086917d15165bee;Path=/rest;Secure;HttpOnly"
                        },
                        "http_agent": "ansible-httpget",
                        "method": "GET",
                        "mode": null,
                        "owner": null,
                        "regexp": null,
                        "remote_src": null,
                        "removes": null,
                        "return_content": false,
                        "selevel": null,
                        "serole": null,
                        "setype": null,
                        "seuser": null,
                        "src": null,
                        "status_code": [
                            200
                        ],
                        "timeout": 30,
                        "unsafe_writes": null,
                        "url": "https://vcenter01.lab.test/rest/vcenter/host?filter.clusters=domain-c310",
                        "url_password": null,
                        "url_username": null,
                        "use_proxy": true,
                        "validate_certs": false
                    }
                },
                "item": {
                    "cluster": "domain-c310",
                    "drs_enabled": true,
                    "ha_enabled": false,
                    "name": "DB-CLUSTER"
                },
                "json": {
                    "value": [
                        {
                            "connection_state": "CONNECTED",
                            "host": "host-312",
                            "name": "vmh19.lab.test",
                            "power_state": "POWERED_ON"
                        },
                        {
                            "connection_state": "CONNECTED",
                            "host": "host-313",
                            "name": "vmh20.lab.test",
                            "power_state": "POWERED_ON"
                        }
                    ]
                },
                "msg": "OK (unknown bytes)",
                "redirected": false,
                "status": 200,
                "url": "https://vcenter01.lab.test/rest/vcenter/host?filter.clusters=domain-c310"
            }
        ]
    }
}

从完整的 JSON 中我只需要以下值:

“名称”:“vmh20.lab.test” “名称”:“vmh19.lab.test”

根据集群大小,此输出可以提供集群中的任意数量的主机。

我想使用这些值作为任务中主机名的条目:

 - name: Modify root local user to ESXi
    vmware_local_user_manager:
      hostname: '{{ item.results.json.value.name }}'
      username: root
      password: '{{ esxi_pass }}'
      local_user_name: root
      local_user_password: '{{ esxi_new_pass }}'
      validate_certs: False
    with_items:
    -  "{{ vchosts }}"

但它不起作用,因为出现错误:

TASK [Modify root local user to ESXi] **********************************************************************************************************************************************************************
fatal: [localhost]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'list object' has no attribute 'json'\n\nThe error appears to have been in '/Users/jv/Workspace/vmware-powershell/ansible/site.yml': line 90, column 5, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n  - name: Modify root local user to ESXi\n    ^ here\n"}

我尝试使用调试进行进一步调查

  - debug:
    var: item.json.value.name
    with_items:
    -  "{{ vchosts.results }}"

但输出是

TASK [debug] ***********************************************************************************************************************************************************************************************
ok: [localhost] => (item=None) => {
    "msg": "Hello world!"
}

我也尝试过:

 - debug:
    var: item.vchosts.results.json.value[*].name
    with_items:
    -  "{{ vchosts }}"

  - debug:
    var: item
    with_items:
    -  "{{ vchosts | json_query('[*].value[*].{name: name}') }}"

我得到了和以前一样的 Hello world。我最后一次尝试的是

  - debug:
    var: item.name
    with_items:
    -  "{{ vchosts | json_query('*.value') }}"

我在任务中得到的不是 Hello world,而是空输出

TASK [debug] ***********************************************************************************************************************************************************************************************

我正在使用 ansible 2.5.4

答案1

如果您只需要值“vmh20.lab.test”和“vmh19.lab.test”,这不是您要查找的代码吗?

- name: Modify root local user to ESXi
  vmware_local_user_manager:
    hostname: '{{ item }}'
    username: root
    password: '{{ esxi_pass }}'
    local_user_name: root
    local_user_password: '{{ esxi_new_pass }}'
    validate_certs: False
  with_items:
    - vmh20.lab.test
    - vmh19.lab.test

答案2

我不知道为什么

- debug: var=item.name
    with_items:
    -  "{{ vchosts.json.value }}"

不同于

- debug: 
    var: item.name
    with_items:
    -  "{{ vchosts.json.value }}"

这确实让我抓狂,这肯定是这个版本的 ansible 的一个 bug

问题在于它将我的第一个请求中的元素作为 Json 中的列表,并且您需要枚举它们。

为了不得到肮脏的“vchosts”JSON,您需要只使用“vcclust”中的一个元素,因此代码结束如下:

 - name: Get vCenter cluster ID for {{ cluster_touched }}
    uri:
      url: "https://{{ vcenter_hostname }}/rest/vcenter/cluster?filter.names={{ cluster_touched }}"
      force_basic_auth: yes
      validate_certs: no
      headers:
        Cookie: '{{ login.set_cookie }}'
    register: vcclust

  - name: Get ESXi nodes from cluster ID for {{ cluster_touched }}
    uri:
      url: "https://{{ vcenter_hostname }}/rest/vcenter/host?filter.clusters={{ vcclust.json.value[0].cluster }}"
      force_basic_auth: yes
      validate_certs: no
      headers:
        Cookie: '{{ login.set_cookie }}'
    register: vchosts

  - name: Modify root local user to ESXi
    vmware_local_user_manager:
      hostname: '{{ item.name }}'
      username: root
      password: '{{ esxi_pass }}'
      local_user_name: root
      local_user_password: '{{ esxi_new_pass }}'
      validate_certs: False
    with_items:
    -  "{{ vchosts.json.value }}"

相关内容