简体   繁体   English

如何使用 jinja2 解析 ansible vars dict

[英]How to parse ansible vars dict with jinja2

Let's say i have hosts specific variables like this:假设我有这样的主机特定变量:

projects:
  - project1:
    urls:
    - "https://foo.bar"
    - "https://foo2.bar2"
    names:
    - "some_name"
    address: 
      city1:
      - "street1"
      - "street2"
      city2:
      - "streetX"

And I have to generate files (per project) with jinja2 templating.而且我必须使用 jinja2 模板生成文件(每个项目)。 I will be using all nested variables...我将使用所有嵌套变量...

Should I change my vars dict structure or is this one ok..?我应该改变我的 vars dict 结构还是这个可以..? How can I get all these nested variables?我怎样才能得到所有这些嵌套变量?

I tried:我试过了:

  - name: Create projects
    ansible.builtin.template:
      src: project.yml.j2
      dest: "/client/projects/{{ item | dict2items| json_query('[0].key') }}.yaml"
    loop: "{{ projects }}"

And then, Im getting lost in template file with all loops and lenght of vars with these json_queries...然后,我在模板文件中迷失了所有循环和这些 json_queries 的 vars 长度......

  1. Is this a good way or is there any better?这是一个好方法还是有更好的方法?
  2. Can you help me with definition of all nested keys/values?你能帮我定义所有嵌套的键/值吗? Or is there any easy way how to get them?或者有什么简单的方法可以得到它们?

Your actual structure does not make much sense.您的实际结构没有多大意义。 You either want to use a list or a dict, not something in between using a key with a null value您要么想要使用列表或字典,而不是使用具有 null 值的键之间的东西

I suspect you are looking for a dictionary:我怀疑您正在寻找字典:

projects:
  project1:
    urls:
      - "https://foo.bar"
      - "https://foo2.bar2"
    names:
      - "some_name"
    address: 
      city1:
        - "street1"
        - "street2"
      city2:
        - "streetX"
  project2:
    # etc.

From there, given your file extension as yaml, I guess you want a template that looks like this project.yml.j2 file:从那里,鉴于您的文件扩展名为 yaml,我猜您想要一个看起来像这个project.yml.j2文件的模板:

---
{{ item.value | to_yaml }}

Which you will call like this to create one file named after each project您将像这样调用它来创建一个以每个项目命名的文件

  - name: Create projects
    template:
      src: project.yml.j2
      dest: "/client/projects/{{ item.key') }}.yaml"
    loop: "{{ projects | dict2items }}"

Note that for something as simple, you can remove the burden of an external template file by using copy and streaming the content directly inside the content option:请注意,对于简单的事情,您可以通过直接在content选项中使用copy和流式传输内容来消除外部模板文件的负担:

  - name: Create projects
    copy:
      dest: "/client/projects/{{ item.key') }}.yaml"
      content: "{{ item.value | to_yaml }}"
    loop: "{{ projects | dict2items }}"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM