【问题标题】:Ansible/Jinja2 how to append key into list of dictAnsible/Jinja2 如何将密钥附加到字典列表中
【发布时间】:2017-04-04 09:09:12
【问题描述】:

我想像这样在 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 编写一个自定义插件?

【问题讨论】:

    标签: ansible jinja2


    【解决方案1】:

    您可以通过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 post 中使用set_factwith_ 了解有关此技巧的更多详细信息。

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

    【讨论】:

    • 这太天才了!谢谢。 Постоянно натыкаюсь на твои ответы)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-06
    • 2016-01-28
    • 1970-01-01
    • 1970-01-01
    • 2020-04-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多