Ansible / Jinja2如何将密钥附加到字典列表中

时间:2017-04-04 09:09:13

标签: ansible jinja2

我想在这样的ansible中定义字典

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键上循环一些任务,这很好用

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

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

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 }

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

domains:
  - example.com
  - example.org

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

1 个答案:

答案 0 :(得分:6)

您可以使用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 }}"

set_fact中有with_json_query('*[].a')的详细信息。

要获取所有域名,您可以使用{{1}}。

相关问题