Ansible "The task includes an option with an undefined variable" when using set fact across hosts

Viewed 29

Getting undefined variable, even though debug is printing it out when using vars across hosts.

Inventory:

[host-group1]
10.X.Y.Z node_name=host1

[host-group2]
10.A.B.C node_name=host2

[all:vars]
host1_ip="10.X.Y.Z"

Host1:

- name: Get the token
  shell: kubeadm token create --print-join-command
  register: tmp_kubeadm_join_token

- name: Store the token
  set_fact:
    kubeadm_join_token: "{{ tmp_kubeadm_join_token.stdout  }}"

Host2:

- debug: var=hostvars['{{ host1_ip }}']['kubeadm_join_token']
  run_once: true

- name: Join the cluster
  shell: "{{ hostvars['{{ host1_ip }}']['kubeadm_join_token'] }} --control-plane"

Result:

ok: [10.A.B.C] => {
    "hostvars['10.X.Y.Z']['kubeadm_join_token']": "kubeadm join kube-lb:6443 --token XXXXXXXX.XXXXXXXXXXXXXXXXXXXXX --discovery-token-ca-cert-hash sha256:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
}
fatal: [10.A.B.C]: FAILED! => {
    "msg": "The task includes an option with an undefined variable. The error was: \"hostvars['{{ host1_ip }}']\" is undefined\n\nThe error appears to be in '/home/myuser/k8s/path/to/main.yml': line XX, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n- name: Join the cluster\n  ^ here\n"
}
1 Answers

Solved with this workaround:

  shell: "{{ hostvars[item]['kubeadm_join_token'] }} --control-plane"
  with_items: "{{ groups['host-group1'] }}"
Related