ansible - 在 Ansible 的 API 调用中使用子元素
问题描述
我尝试在同一任务中使用不同的 URI 和不同的 JSON 进行 API 调用。
这些是我的变量:
api_templates:
- name :
- 'template1'
- 'template2'
url :
- 'http://localhost:80/template1'
- 'http://localhost:80/template2'
file :
- '../files/template1.json'
- '../files/template2.json'
我正在使用这段代码:
- name: Inserting templates
uri:
url: "{{ item.0.url }}"
method: PUT
body: "{{ lookup('file', '{{ item.1 }}') }}"
body_format: json
with_subelements:
- "{{ api_templates }}"
- file
但它不能正常工作。
我需要任务的第一次迭代执行 API 调用,使用 template1、第一个 URL 并使用第一个文件等等。
解决方案
简单的解决方案是循环include_tasks。下面的戏
- include_tasks: uri-put.yml
loop: "{{ api_templates }}"
loop_control:
loop_var: uri
与包含的文件
> cat uri-put.yml
- debug: msg="{{ item.0 }} {{ item.1 }} {{ item.2 }}"
with_together:
- "{{ uri.name }}"
- "{{ uri.url }}"
- "{{ uri.file }}"
给出(猫味精):
"msg": "template1 http://localhost:80/template1 ../files/template1.json"
"msg": "template2 http://localhost:80/template2 ../files/template2.json"