【问题标题】:Ansible using values of an array as a key to loop through a dictionary that contains multiple valuesAnsible 使用数组的值作为键来遍历包含多个值的字典
【发布时间】:2021-03-03 23:56:54
【问题描述】:

我正在尝试根据它们所属的组以及用户在变量中定义的内容来创建目录。

[web20int]
server1
server2

[web20ext]
server3

[app01dev]
server1


certdir:
    
  web20int:
    - intwiki
    - intblogs

  web20ext:
    - wiki
    - xblogs

  app01dev:
    - app01dev


---
  - name: Set App Name Key List
    set_fact:
      ckeys: "{{ certdir.keys()|list }}"

  - name: Get Group Names
    debug:
      msg: "{{ group_names }} "

  - name: Get Cert App Names
    debug:
      msg: item
    loop: "{{ ckeys }}"

  - name: Setting Union between Group Names and Cert App Names
    set_fact:
      union_key: "{{ ckeys | intersect(group_names) }}"

  - name: Result of union
    debug:
       var: union_key

这是我不明白如何进行嵌套循环或使用 jini2 模板的地方。 我想遍历 union_key 数组,然后遍历 certdir 并获取要放入另一个数组的值列表

  - name: create cert directory for app
    file:
      path: "{{ item }}"
      state: directory
      owner: root
      group: root
      mode: 0755
    loop: "{{ <SOME ARRAY THAT CONTAINS THE DIRECTORY NAMES }}"

例如,server1 属于组: [web20int] [app01dev]

因此我希望数组包含: intwiki intblogs app01dev

谢谢

【问题讨论】:

    标签: ansible ansible-facts ansible-template


    【解决方案1】:

    你可以map the extract filter:

    union_key | map('extract', certdir)
    

    但这会给你一个列表列表,所以你需要应用flatten过滤器:

    loop: "{{ union_key | map('extract', certdir) | flatten }}"
    

    (如果flatten 给出的是可迭代的而不是列表,您可能还需要使用list 过滤器)

    顺便说一句,变量名和任务名都在谈论“联合”,但你正在做一个“交集”。

    【讨论】:

    • 谢谢,它就像一个魅力。谢谢,我想我是先尝试联合,然后切换到相交。
    • 我也不需要使用列表过滤器,你写的就行了
    • 如果它解决了您的问题,请考虑接受答案。
    猜你喜欢
    • 1970-01-01
    • 2016-08-19
    • 1970-01-01
    • 1970-01-01
    • 2023-02-10
    • 1970-01-01
    • 2011-02-10
    • 2020-11-04
    • 2015-07-25
    相关资源
    最近更新 更多