【问题标题】:ansible hash to json to jinja templateansible hash to json to jinja template
【发布时间】:2019-07-15 02:11:03
【问题描述】:

我得到了以下内容,并坚持得到正确的答案。我有一个字典,我想用文件名中的 item.key 和模板中的所有值作为模板。

my_dict:
  name1:
    { path=/x/y/z, action=all, filter=no },
    { path=/a/b/c, action=some, filter=yes }
  name2:
    { path=/z/y/x, action=nothing, filter=no },
    { path=/c/b/a, action=all, filter=yes }

 tasks:
   - name: generate check config
     template:
       src: check.j2
       dest: "{{ config_dir }}/{{ item.key }}-directories.json"
       owner: Own
       group: Wheel
       mode: 0644
     with_dict:
       - "{{ my_dict }}"
     when:
       - my_dict is defined
     become: true

我的模板看起来像

{
"configs": [

{% for value in my_dict %}
{
"path": "{{ value.path }}",
"action": "{{ value.action }}",
{% if value.filter is defined %}
"filter": "{{ value.filter }}"
{% endif %}
}{% if !loop.last %},{% endif %}
{% endfor %}
]
}

所以我测试了这么多,现在我没有看到太多树木的任何森林原因。

上面应该会产生 2 个文件。 文件名 = name1-directories.json 内容:

{
"configs": [
{
"path": /x/y/z,
"action": all,
"filter": no
},
{
"path": /a/b/c,
"action": some,
"filter": yes
}
]
}

提前致谢

【问题讨论】:

  • 您能否简化您的问题并添加您想要达到的结果。
  • @gentux 你的问题回答了吗?您还有其他问题吗?

标签: json dictionary templates hash ansible


【解决方案1】:

让我从以下内容开始。我发现您当前的解决方案存在一些问题。

  1. 您的模板使用value.<key> 引用了数组项的值,而它应该改为item.value.<key>
  2. with_dict 需要一个字典,但您传递的数组包含一个字典作为唯一元素。在 yaml 中,- 表示数组元素。要正确使用它,您只需编写:with_dict: "{{ my_dict }}"
  3. 不鼓励在 ansible 中使用简写的 yaml 语法,因为这会使 playbook 更难阅读。

我建议您执行以下操作:

有一个 jinja2 过滤器可以将你的 dict 转换为 json:

{{ dict_variable | to_json }} # or
{{ dict_variable | to_nice_json }}

第二个使它易于阅读。您目前正在尝试做的事情可能会奏效(还没有仔细研究过),但它并不美观且容易出错。

要使其与 jinja2 过滤器一起使用,请按以下方式在顶部重构变量:

    my_dict:
      - name1:
          configs:
            - path: /x/y/z
              action: all
              filter: no
            - path: /a/b/c
              action: some
              filter: yes
      - name2:
          configs:...

当变量被这样格式化时,你可以使用copy 模块将配置打印到这样的文件中:

    - name: Print the configs to the files
      copy:
        content: "{{ item.value | to_nice_json }}"
        dest: "{{ config_dir }}/{{ item.key }}-directories.json"
      with_dict: "{{ my_dict }}"

【讨论】:

    猜你喜欢
    • 2021-10-14
    • 1970-01-01
    • 2013-10-10
    • 2015-12-07
    • 1970-01-01
    • 2018-08-31
    • 1970-01-01
    • 1970-01-01
    • 2015-01-07
    相关资源
    最近更新 更多