无法使用模板在ansible中获取组ipv4地址

Unable to get group ipv4 address in ansible with template

我正在尝试枚举我的 eth0 地址(设置为默认地址,因为我在某处读到 eth0 并不总是可用..)。在我的模板中,我尝试像这样从组中调用它...

[Unit]
Description=Kubernetes Kube Proxy
Documentation=https://github.com/GoogleCloudPlatform/kubernetes

[Service]
ExecStart=/usr/bin/kube-proxy \
  --master=https://{{ groups[controller][0]['ansible_default_ipv4']['address'] }}:6443 \
  --kubeconfig=/var/lib/kubelet/kubeconfig \
  --proxy-mode=iptables \
  --v=2

Restart=on-failure
RestartSec=5

[Install]
WantedBy=multi-user.target

这似乎应该可用,因为当我用 -debug var=groups 转储时我得到....

[18.234.92.196] => {
    "groups": {

      ......

        "controller": [
            "54.86.253.135",
            "52.205.43.24",
            "54.210.213.10"
        ],
        "controller.0": [
            "54.86.253.135"
        ],
        "controller.1": [
            "52.205.43.24"
        ],
        "controller.2": [
            "54.210.213.10"
        ],

        ......

        "name_controller-0": [
            "54.86.253.135"
        ],
        "name_controller-1": [
            "52.205.43.24"
        ],
        "name_controller-2": [
            "54.210.213.10"
        ],

        ......

    }
}

奇怪的是,当我尝试使用 var=groups[controller] 进行调试时,我得到...

TASK [worker : debug] *******************************************************************************************************************************************
ok: [34.207.172.100] => {
    "groups[controller]": "VARIABLE IS NOT DEFINED!: 'controller' is undefined"
}

.....

TASK [worker : Add Kubelet configuration] ***********************************************************************************************************************
fatal: [34.207.172.100]: FAILED! => {"changed": false, "msg": "AnsibleUndefinedVariable: 'controller' is undefined"}

我在这里错过了什么?

想通了,需要先通过组指定IP并将其用作索引。

此外,ansible_default_ipv4 似乎不存在,所以换成 public_ip 是一样的。

- name: Print hostvars
  debug:
    msg: "{{ hostvars[groups.controller.0].public_ip }}"