Ansible,如何访问从文件导入的变量



我在我的剧本中生成了一个yml文件(cert_expiring.yml(,它由SSL证书即将过期的服务器的ID和服务器名称的字典组成。

例如:cert_expiring.yml

myDict:
705:node1.corp.com
670:node2.corp.com
1163:node3.corp.com
715:node4.corp.com

我有一个剧本,它正在读取这个文件,并将其存储在一个名为"的变量中;expired_certs":

- name: Store file contents into variable
include_vars:
file: cert_expiring.yml
name: expired_certs

";expired_certs";看起来像这样:

{
"msg": {
"changed": true,
"msg": "All items completed",
"results": [{
"ansible_loop_var": "item",
"backup": "",
"changed": true,
"diff": [{
"after": "",
"after_header": "./cert_expiring.txt (content)",
"before": "",
"before_header": "./cert_expiring.txt (content)"
},
{
"after_header": "./cert_expiring.txt (file attributes)",
"before_header": "./cert_expiring.txt (file attributes)"
}
],
"failed": false,
"invocation": {
"module_args": {
"attributes": null,
"backrefs": false,
"backup": false,
"content": null,
"create": true,
"delimiter": null,
"dest": "./cert_expiring.txt",
"directory_mode": null,
"firstmatch": false,
"follow": false,
"force": null,
"group": null,
"insertafter": null,
"insertbefore": null,
"line": "    705:node1.corp.com",
"mode": null,
"owner": null,
"path": "./cert_expiring.txt",
"regexp": null,
"remote_src": null,
"selevel": null,
"serole": null,
"setype": null,
"seuser": null,
"src": null,
"state": "present",
"unsafe_writes": null,
"validate": null
}
},
"item": {
"cn": "node1.corp.com",
"expires": "2020-11-05T15:20:18+00:00",
"id": 705,
"serial": "1111"
},
"msg": "line added"
}]
}
}

我试图遵循这里的相同程序来引用";cn"到期"id";,以及";串行";来自嵌套的json,但不确定为什么它不起作用。

这是我访问这些元素的游戏:

- name: Print expired_certs variable contents
debug:
msg: "{{ expired_certs | json_query('results.item[*].{expires: expires, cn: cn, serial: serial, id: id}') }}"

输出:

ok: [localhost] => {
"msg": ""
}

此外,尝试过这个:

msg: "{{ expired_certs | json_query('results.[*].{expires: item.expires, cn: item.cn, serial: item.serial, id: itme.id}') }}"

输出:

ok: [localhost] => {
"msg": {
"cn": null,
"expires": null,
"id": null,
"serial": null
}
}

需要帮助了解如何访问嵌套元素。

查看JSON,关键字results是一个列表,而不是字典:

{
"results": [{
"changed": true,
"...cut": "for brevity"
}]
}

在JSON中,方括号表示数组(或使用Ansible语言的列表(

密钥item是一个字典,而不是一个列表:

{
"item": {
"cn": "node1.corp.com",
"expires": "2020-11-05T15:20:18+00:00",
"id": 705,
"serial": "1111"
}
}

在JSON中,花括号表示对象(或说Ansible语言的字典(

所以,您的通配符表达式只是放错了键。

应该是:

results[*].item

与你的实际情况相反:

results.item[*]

而且,因为item密钥已经只包含了您需要的信息,所以您不需要付出额外的努力来重做对象。你可以住在results[*].item

最终结果:

- name: Print expired_certs variable contents
debug:
msg: "{{ expired_certs | json_query('results[*].item') }}"

最新更新