对于Ansible剧本,我需要从API调用中获取一些结果,以检查ID是否已经存在。
这应该是程序:
- 如果ID存在,则任务应使用API放置请求更新配置
- 如果ID不存在,则应使用API发布请求创建配置
我的解决方案是检查变量result
中的JSON是否包含字段"ID:" "output-1"
。如果包含,则将变量id_exists
的值设置为true
,然后将其用作以下任务中的条件。
不幸的是,我不知道使用哪个Ansible模块在JSON中搜索和注册变量。也许有人可以帮助我找到一个解决方案?
可行示例:
- name: "Call API to get JSON data"
ansible.builtin.uri:
url: https://example.com/api/outputs
method: get
register: result
- name: "Debug: Print all IDs"
ansible.builtin.debug:
msg: "{{ result.json | json_query(jmesquery) }}"
vars:
jmesquery: "items[*].{ID: id}"
## Task: Check if JSON result contains the ID output-1
## DON'T KNOW HOW :(
- name: "Create new config"
url: https://example.com/api/outputs
method: post
headers:
Content-Type: application/json
Authorization: "ApiKey {{ api_key }}"
body_format: json
body: |
{
"id": "output-1",
"name": "Name",
"is_default": false,
"type": "testtype",
"config_yaml": "verification_mode: advanced"
}
when: id_exists == false
- name: "Update existing config"
ansible.builtin.uri:
url: https://example.com/api/outputs/output-1
method: put
headers:
Content-Type: application/json
Authorization: "ApiKey {{ api_key }}"
body_format: json
body: |
{
"name": "New Name",
"is_default": false,
"type": "testtype",
"config_yaml": "verification_mode: advanced"
}
when: id_exists == true
JSON示例:
{
"items": [
{
"id": "output-1",
"name": "Output 1",
"is_default": true,
"type": "testtype",
"config_yaml": "verification_mode: basic"
},
{
"id": "output-2",
"name": "Output 2",
"is_default": false,
"type": "testtype",
"config_yaml": "verification_mode: basic"
},
{
"id": "output-3",
"name": "Output 3",
"is_default": false,
"type": "testtype",
"config_yaml": "verification_mode: basic"
}
]
}
非常感谢!
1条答案
按热度按时间h4cxqtbf1#
如果我没理解错的话,下面的内容应该能满足你的期望。我添加了几个例子作为调试任务,让你玩结果,并对如何调用你的API做出自己的决定(我自己不能运行一个例子)
以下行动手册
提供: