Ansible/Jinja2 如何将键附加到字典列表中 [英] Ansible/Jinja2 how to append key into list of dict

查看:28
本文介绍了Ansible/Jinja2 如何将键附加到字典列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想像这样用 ansible 定义字典

I would like to have dictionary defined in ansible like this

vhosts:
  git_branch_1:
    - { a: example.com, customer: a }
    - { a: example.com, customer: b }
    - { a: example.org, customer: a }
  git_branch_2:
    - { a: example.com, customer: x }
    - { a: example.org, customer: y }

有些任务我只需要遍历 dict 键,这很好用

Some tasks I need to loop only over dict keys, this works fine

- name: "just debug"
  debug: msg={{ item }}
  with_items: "{{ vhosts.keys() }}"

但是有些任务我想从每个键遍历列表,并将键附加为 dict 的另一个属性,所以我想从这个原始 dict 组合/创建新的 dict,看起来像这样:

But some tasks I would like to iterate over list from each key, and append the key as another property of dict, so I would like to combine/create new dict from this original dict, that will look like this:

combined_vhosts:
  - { a: example.com, customer: a, branch: git_branch_1 }
  - { a: example.com, customer: b, branch: git_branch_1 }
  ...
  - { a: example.com, customer: x, branch: git_branch_2 }

在某些任务中,我只需要获取顶级域:

And in some tasks I just need to get only the top level domain:

domains:
  - example.com
  - example.org

有没有办法,我怎样才能在 ansible set_facts/jinja2 符号中实现这一点,或者我是否必须在 python 中为 ansible 编写一个自定义插件?

Is there a way, how can I achive this in ansible set_facts / jinja2 notation or do I have to write a custom plugin for ansible in python?

推荐答案

您可以使用 set_fact 来实现:

You can achieve this with set_fact:

---
- hosts: localhost
  gather_facts: no
  vars:
    vhosts:
      git_branch_1:
        - { a: example.com, customer: a }
        - { a: example.com, customer: b }
        - { a: example.org, customer: a }
      git_branch_2:
        - { a: example.com, customer: x }
        - { a: example.org, customer: y }
  tasks:
    - set_fact:
        tmp_vhosts: "{{ item.value | map('combine',dict(branch=item.key)) | list }}"
      with_dict: "{{ vhosts }}"
      register: combined_vhosts
    - set_fact:
        combined_vhosts: "{{ combined_vhosts.results | map(attribute='ansible_facts.tmp_vhosts') | sum(start=[]) }}"
    - debug:
        msg: "{{ combined_vhosts }}"

这篇文章.

More details about this trick with set_fact and with_ in this post.

要获取所有域,您可以使用json_query('*[].a').

To fetch all domains, you can use json_query('*[].a').

这篇关于Ansible/Jinja2 如何将键附加到字典列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆