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

╄→гoц情女王★ 提交于 2019-11-28 05:15:19

问题


I am trying to configure one set of hosts [nodes] using facts from another set of hosts [etcd]. Here is my hosts file

[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

Note that the group [etcd] is not the target of provisioning - [nodes] is. But provisioning [nodes] requires knowledge of the facts of [etcd].

Here is my playbook:

---
- 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

Finally, here is the template for 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 %}"

The goal is to produce a KUBE_ETCD_SERVERS value that looks like

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

When I run this playbook I get console output

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'"}

What is the idiomatic Ansible way to make the etcd facts available to the node play?


回答1:


If you want to use facts of some host, you should gather them first.
Run setup task on [etcd] hosts to populate 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


来源:https://stackoverflow.com/questions/39127514/using-facts-from-one-host-group-to-configure-another-host-group-with-ansible

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!