在继续执行 Runbook 的其余部分之前,如何汇总存储有关远程主机的自定义事实?

How can I store custom facts about remote hosts in aggregate before proceeding with rest of the runbook?

我正在 Ansible 中编写集群配置手册,要求在安装时为每个节点配置其他节点的 public 证书。我想不出一个简单的方法来告诉 ansible 到:

  1. 去获取远程证书
  2. 将它们推入列表
  3. 使这些证书摘要可供每个 远程节点使用,以生成授权的节点列表

目前,鉴于集群节点数量较少,我将手动执行此操作(将第一个剧本的输出复制到第二个剧本的变量中),但如果有的话,这将是最有帮助的是在单个剧本中执行此操作的一种方法。

我的回答将尽可能笼统:将一个事实存储在一组特定机器上,然后从另一台机器读取该组中所有机器的事实。

  1. 我想当然地认为你的剧本实际上是针对一个包含你所有集群节点的组 my_node_group
  2. 将来自远程节点的信息存储在它自己的事实中(或直接从您的库存中获取...)。

    # This one should be replaced with getting certs in your context
    # with whatever solution is best suited for you.
    - name: Get an info from current machine
      shell: echo "I'm a dummy task running on {{ inventory_hostname }}" 
      register: my_info_cmd
    
    - name: Push info in a fact for current node
      set_fact:
        my_info: "{{ my_info_cmd.stdout }}"
    
  3. 这是真正有用的部分:在别处使用存储的信息
    - name: example loop to access 'my_info` on each machines of group `my_node_group`
      debug:
        var: item
      loop: >-
        {{
          groups['my_node_group']
          | map('extract', hostvars, 'my_info')
          | list 
        }}
    

最后一步的解释

  • 获取群组中的机器my_node_group
  • hostvars 上将这些名称用于 map the extract filter 并获取相应事实哈希的列表,其中您只保留 my_info 属性
  • 将返回的地图对象转换为一个循环列表。