我有一个 Ansible 任务,它向网站发出 URI 请求以获取 JSON 响应。如果定义了嵌套的 JSON 变量,我希望 Ansible 执行某些操作,如果未定义,则执行其他操作。
- name: Get JSON from the Interwebs
uri: url="http://whatever.com/jsonresponse" return_content=yes
register: json_response
- name: Write nested JSON variable to disk
copy: content={{json_response.json.nested1.nested2}} dest="/tmp/foo.txt"
Run Code Online (Sandbox Code Playgroud)
请注意, usingignore_errors仅适用于任务的命令失败,不适用于检查 Jinja 模板中嵌套数据结构中的未定义值。因此,如果json_response.json.nested1.nested2未定义,即使ignore_errors=yes设置了该任务仍然会失败。
/tmp/foo.txt如果请求失败,或者请求没有定义正确的嵌套值,我如何让这个剧本存储一些默认值?
alf*_*era 20
您需要使用 jinja2 过滤器 ( http://docs.ansible.com/ansible/playbooks_filters.html )。在这种情况下,过滤器的名称是from_json。在下面的示例中,我将在找到密钥时采取行动,在找不到密钥时采取其他行动:
---
- hosts: somehost
sudo: yes
tasks:
- name: Get JSON from the Interwebs
uri: url="https://raw.githubusercontent.com/ljharb/node-json-file/master/package.json" return_content=yes
register: json_response
- debug: msg="Error - undefined tag"
when: json_response["non_existent_tag"] is not defined
- debug: msg="Success - tag defined =>{{ (json_response.content|from_json)['scripts']['test'] }}<="
when: (json_response.content|from_json)['scripts']['test'] is defined
Run Code Online (Sandbox Code Playgroud)
现在替换适当的调试以采取所需的操作。
希望能帮助到你,
| 归档时间: |
|
| 查看次数: |
58438 次 |
| 最近记录: |