【发布时间】:2021-04-27 04:51:58
【问题描述】:
在 ansible playbook 中,我必须读取一个包含以下数据的 yaml 文件:
john: stu001
bob: stu002
william: stu003
此数据是动态的,可以有多个学生的 ID。我想在我的 ansible 游戏中阅读这个 yaml,并且需要像这样的输出:
---
- name: Students Data
hosts: localhost
tasks:
- include_vars:
file: tmp/stuData.yml
name: stuName
- name: "Students Details"
uri:
url: "{{ some_api_server }}"
return_content: yes
body_format: json
method: POST
body:
matchers:
- name: john
id: stu001
age: NA
- name: bob
id: stu002
age: NA
- name: william
id: stu003
age: NA
startsAt: "{{ st_time }}"
endsAt: "{{ en_time }}"
createdBy: abc@example.com
我已经尝试了以下代码:
---
- name: Students Data
hosts: localhost
tasks:
- include_vars:
file: tmp/stuData.yml
stuName: stuName
- name: "Students Details"
uri:
url: "{{ some_api_server }}"
return_content: yes
body_format: json
method: POST
body:
matchers:
{% for k,v in stuName.items() %}
- name: {{ k }}
id: {{ v }}
age: "NA"
{% endfor %}
startsAt: "{{ st_time }}"
endsAt: "{{ en_time }}"
createdBy: abc@example.com
这在匹配器之后给了我语法错误。谁能帮我写正确的代码。
【问题讨论】:
-
你能描述一下应用
animals变量后的yaml文件吗? -
对不起,我的代码有错误。现在我已经纠正了。那么你现在可以检查如何循环这个动物变量来动态创建这个匹配器集合。
-
YAML 本身没有变量,但您可以在 bash 级别处理此问题,方法是将您的 YAML 代码定义为 Here-Document 并使用 bash 变量。因此,在 bash 循环的每次迭代中,您都拥有该特定动物的 YAML 代码版本,并且可以将其写入文件。
-
你能添加例子吗?