2017-04-04 4 views
0

のリストにキーを追加する方法を、私は辞書は私だけのdictのキーをループする必要があり、このAnsible/Jinja2のdictの

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 } 

一部のタスクのようにansibleで定義されているしたいと思い、これが正常に動作します

- 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の表記でこれをachiveすることができますか私はカスタムを記述する必要があります方法はありますPythonで実行するためのプラグイン?

答えて

3

あなたはset_factでこれを達成することができます:this postset_factwith_と、このトリックについて

--- 
- 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 }}" 

詳細を。

すべてのドメインを取得するには、json_query('*[].a')を使用します。