首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >从任务循环将字典传递给jinja2模板

从任务循环将字典传递给jinja2模板
EN

Stack Overflow用户
提问于 2019-08-01 09:59:49
回答 1查看 441关注 0票数 0

我把字典从玩转到任务。我使用循环从单独的yml文件调用另一个任务,再次传递字典。在那里,我调用Jinja2模板并再次传递字典。我无法从Jinja2访问字典值。

我试着把字典传递给模板with_items和with_dict。还是同样的问题。

演奏:

代码语言:javascript
运行
复制
- role: example
      vars:
        brands:
          brand_1:
            name: "brand1"

          brand_2:
            name: "brand2"

          brand_3:
            name: "brand_3"        

任务在角色中循环:

代码语言:javascript
运行
复制
    - 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

代码语言:javascript
运行
复制
    - 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

代码语言:javascript
运行
复制
{% for item in outer_item %}
    Name: "{{ item.name }}"
{% endfor %}

我希望访问模板中的字典值,并根据字典中品牌的数量生成具有不同值的相同文件。因此,如果有3个品牌,我希望生成3个文件的不同名称:内部。

不幸的是,我得到了:

代码语言:javascript
运行
复制
"msg": "AnsibleUndefinedVariable: 'str object' has no attribute 'name'"

有什么想法吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-08-01 12:41:41

1) vars:的压痕是错误的。

2)单回路完成工作。

3)模板中的迭代是不必要的。

4)数字模式必须引用mode: '0644'

下面的剧本

代码语言:javascript
运行
复制
- 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"

带着任务

代码语言:javascript
运行
复制
$ cat roles/example/tasks/main.yml
- include_tasks: generate_config_files.yml

,具有包含的任务

代码语言:javascript
运行
复制
$ 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 }}"

,并使用模板

代码语言:javascript
运行
复制
$ cat roles/example/templates/consumer.properties.j2 
Name: "{{ item.value.name }}"

给出

代码语言:javascript
运行
复制
$ 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"

这就是你要找的吗?

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57306489

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档