我把字典从玩转到任务。我使用循环从单独的yml文件调用另一个任务,再次传递字典。在那里,我调用Jinja2模板并再次传递字典。我无法从Jinja2访问字典值。
我试着把字典传递给模板with_items和with_dict。还是同样的问题。
演奏:
- role: example
vars:
brands:
brand_1:
name: "brand1"
brand_2:
name: "brand2"
brand_3:
name: "brand_3"
任务在角色中循环:
- name: Loop through configuration files
include_tasks: generate_config_files.yml
loop: "{{ lookup('dict', brands) }}"
loop_control:
loop_var: outer_item
generate_config_files.yml
- name: Generate the configuration files
template:
src: "consumer.properties.j2"
dest: "{{ kafka_location }}/{{ item.key }}/consumer.properties"
owner: "{{ kafka_user }}"
group: "{{ kafka_group }}"
mode: 0644
with_dict: "{{ outer_item }}"
consumer.properties.j2
{% for item in outer_item %}
Name: "{{ item.name }}"
{% endfor %}
我希望访问模板中的字典值,并根据字典中品牌的数量生成具有不同值的相同文件。因此,如果有3个品牌,我希望生成3个文件的不同名称:内部。
不幸的是,我得到了:
"msg": "AnsibleUndefinedVariable: 'str object' has no attribute 'name'"
有什么想法吗?
发布于 2019-08-01 12:41:41
1) vars:
的压痕是错误的。
2)单回路完成工作。
3)模板中的迭代是不必要的。
4)数字模式必须引用mode: '0644'
。
下面的剧本
- hosts: localhost
roles:
- role: example
vars:
kafka_user: admin
kafka_group: admin
kafka_location: /scratch
brands:
brand_1:
name: "brand1"
brand_2:
name: "brand2"
brand_3:
name: "brand_3"
带着任务
$ cat roles/example/tasks/main.yml
- include_tasks: generate_config_files.yml
,具有包含的任务
$ cat roles/example/tasks/generate_config_files.yml
- name: Generate the configuration files
template:
src: "consumer.properties.j2"
dest: "{{ kafka_location }}/{{ item.key }}/consumer.properties"
owner: "{{ kafka_user }}"
group: "{{ kafka_group }}"
mode: '0644'
loop: "{{ brands|dict2items }}"
,并使用模板
$ cat roles/example/templates/consumer.properties.j2
Name: "{{ item.value.name }}"
给出
$ tree /scratch/brand_*
/scratch/brand_1
└── consumer.properties
/scratch/brand_2
└── consumer.properties
/scratch/brand_3
└── consumer.properties
$ cat /scratch/brand_*/consumer.properties
Name: "brand1"
Name: "brand2"
Name: "brand_3"
这就是你要找的吗?
https://stackoverflow.com/questions/57306489
复制相似问题