簡體   English   中英

Ansible / Jinja2如何將密鑰附加到字典列表中

[英]Ansible/Jinja2 how to append key into list of dict

我想像這樣在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 }

我只需要在字典鍵上循環一些任務,就可以了

- 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編寫自定義插件?

您可以使用set_fact實現此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_factwith_這篇文章

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM