首页 > 解决方案 > 该任务包括一个带有未定义变量的选项。错误是:“ansible.utils.unsafe_proxy.AnsibleUnsafeText 对象”没有属性“数据”\n

问题描述

我有一个简单的剧本,其中使用 curl 从 Vault 服务器获取一些数据。

tasks:
    - name: role_id
      shell: 'curl \
             --header "X-Vault-Token: s.ddDblh8DpHkOu3IMGbwrM6Je" \
             --cacert vault-ssl-cert.chained \
             https://active.vault.service.consul:8200/v1/auth/approle/role/cpanel/role-id'
      register: 'vault_role_id'
    - name: test1
      debug:
        msg: "{{ vault_role_id.stdout }}"

输出是这样的:

TASK [test1] *********************************************************************************************************************************************************************
ok: [localhost] => {
    "msg": {
        "auth": null,
        "data": {
            "role_id": "65d02c93-689c-eab1-31ca-9efb1c3e090e"
        },
        "lease_duration": 0,
        "lease_id": "",
        "renewable": false,
        "request_id": "8bc03205-dcc2-e388-57ff-cdcaef84ef69",
        "warnings": null,
        "wrap_info": null
    }
}

如果我正在访问第一级属性,一切都很好,例如前面示例中的 .stdout。我需要更深层次的属性才能达到,比如vault_role_id.stdout.data.role_id. 当我尝试这个时,它失败并出现以下错误:

"The task includes an option with an undefined variable. The error was: 'ansible.utils.unsafe_proxy.AnsibleUnsafeText object' has no attribute 'data'\n\n

你有什么建议我可以做些什么来从这个对象层次结构的更深层次获取正确的属性值吗?

标签: dictionaryansible

解决方案


“该任务包括一个带有未定义变量的选项。错误是:'ansible.utils.unsafe_proxy.AnsibleUnsafeText object' has no attribute 'data'\n\n

是的,因为正在发生的事情是将其渲染为msg:with{{将JSON文本强制转换为 python ;如果您确实希望它是 a ,则使用其中之一,或者您可以使用and then will be a ,原因与它被您强制的相同dictdictmsg: "{{ (vault_role_id.stdout | from_json).data.role_id }}"set_fact: {vault_role_data: "{{vault_role_id.stdout}}"}vault_role_datadictmsg

您可以通过在 msg 前加上任何字符来查看相反的过程:

- name: this one is text
  debug:
    msg: vault_role_id is {{ vault_role_id.stdout }}
- name: this one is coerced
  debug:
    msg: '{{ vault_role_id.stdout }}'

虽然这不是您所要求的,但如果请求返回非 200-OK,您还应该添加--fail到您的curl,因此它以非零返回码存在,或者您可以使用更 ansible-y 的方式通过- uri:并设置return_content: yes参数


推荐阅读