使用来自一个主机组的事实通过 Ansible 配置另一个主机组

Using facts from one host group to configure another host group with Ansible

我正在尝试使用来自另一组主机 [etcd] 的事实配置一组主机 [节点]。这是我的主机文件

[master]
kubernetes ansible_ssh_host=10.2.23.108

[nodes]
n1 ansible_ssh_host=10.2.23.192
n2 ansible_ssh_host=10.2.23.47

[etcd]
etcd01 ansible_ssh_host=10.2.23.11
etcd02 ansible_ssh_host=10.2.23.10
etcd03 ansible_ssh_host=10.2.23.9

请注意,组 [etcd] 不是供应的目标 - [nodes] 是。但是配置 [nodes] 需要了解 [etcd].

的事实

这是我的剧本:

---
- name: Configure common
  hosts: nodes
  sudo: True
  tasks:
    - name: etcd endpoints
      file: dest=/etc/kubernetes state=directory

    - name: etcd endpoints
      template: src=files/k.j2 dest=/etc/kubernetes/apiserver

最后,这是 files/k.j2

的模板
KUBE_ETCD_SERVERS="--etcd_servers="{% for host in groups['etcd'] %}https://{{hostvars[host]['ansible_eth0']["ipv4"]["address"]}}:2380{% if not loop.last %},{% endif %}{% endfor %}"

目标是生成一个 KUBE_ETCD_SERVERS 看起来像

的值
--etcd_servers=https://10.2.23.11:2380,https://10.2.23.10:2380,https://10.2.23.10:2380

当我运行这个剧本时,我得到控制台输出

TASK [etcd endpoints] **********************************************************
fatal: [n1]: FAILED! => {"changed": false, "failed": true, "msg": "AnsibleUndefinedVariable: 'dict object' has no attribute 'ansible_eth0'"}
fatal: [n2]: FAILED! => {"changed": false, "failed": true, "msg": "AnsibleUndefinedVariable: 'dict object' has no attribute 'ansible_eth0'"}

使 etcd 事实可用于节点播放的惯用 Ansible 方法是什么?

如果你想使用一些主机的事实,你应该先收集它们。
运行 setup [etcd] 主机上的任务以填充 hostvars.

---
- name: Gather etcd facts
  hosts: etcd
  tasks:
    - setup:

- name: Configure common
  hosts: nodes
  sudo: True
  tasks:
    - name: etcd endpoints
      file: dest=/etc/kubernetes state=directory

    - name: etcd endpoints
      template: src=files/k.j2 dest=/etc/kubernetes/apiserver