2017-04-04 48 views
0

的名单,我想在ansible像这样定义Ansible/Jinja2的如何追加钥匙插入字典

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 } 

我需要仅环比字典键有些任务的字典,这工作正常

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

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

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中是否可靠?

回答

3

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

更多关于这一招在this postset_factwith_细节。

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