M
M
maxgood2020-07-07 16:40:48
Ansible
maxgood, 2020-07-07 16:40:48

How do I fix this "msg": "AnsibleUndefinedVariable: 'hosts' is undefined"} error?

To run the playbook, I use two files .
First inventory file where I list ip addresses of virtual machines
[k8s:children]
haproxy
masters
worker
ansible
# Set variables common for all k8shosts
[k8s:vars]
ansible_ssh_user=root
ansible_become=true

[haproxy]
172.168.10.100
[masters]
172.168.10.101
172.168.10.102
172.168.10.103
[ansible]
172.168.50.11
[leader]
172.168.10.101
[member]
172.168.10.102
172.168.10.103
[worker]
172.168.10.104
Second file hosts.j2 -
127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
{% for host in groups.k8s %}
{{ hostvars[host].ansible_eth1.ipv4.address }} {{ hostvars[ host].ansible_fqdn }} {{ hostvars[host].ansible_hostname }}
{% endfor %}
And here is the playbook itself:

---
- name: Generate Hosts File
hosts: k8s
become: true
gather_facts: true
vars:
my_file: /etc /hosts
my_template: templates/hosts.j2
tasks:
- name: Create "{{ my_file }}"
template:
src: "{{ my_template }}"
dest: "{{ my_file }}"
owner: root
group: root
mode: "0644"

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
MaxKozlov, 2020-07-07
@MaxKozlov

You should send the error message in full - with the line number and the moment of occurrence.
But I can assume that something is wrong with the line near
hosts: k8s
, maybe spaces, maybe spelling. as far as I can see, the hosts variable is only in it

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question