I'm having trouble using hostvars to pass a variable to another host in a vagrant environment, the code I did:
Vagrant.configure("2") do |config|
config.vm.define "server_1" do |server_1|
server_1.vm.hostname = "n1"
server_1.vm.box = "centos/7"
server_1.vm.network "public_network", bridge: "wlp1s0", ip: "192.168.0.50"
end
config.vm.define "worker_1" do |worker_1|
worker_1.vm.hostname = "n2"
worker_1.vm.box = "centos/7"
worker_1.vm.network "public_network", bridge: "wlp1s0", ip: "192.168.0.51"
end
config.vm.provider "virtualbox" do |vb|
vb.memory = 1024
end
config.vm.provision "ansible" do |ansible|
ansible.playbook = "t0a.yml"
end
end
---
- hosts: server*
tasks:
- set_fact: hello=world
- hosts: worker*
tasks:
- debug:
msg: "{{ hostvars['server_1']['hello'] }}"
expected:
TASK [show] *******************************************************************
ok: [worker_1] => {
"msg": [
"works"
]
}
actual:
TASK [debug] ******************************************************************** fatal: [worker_1]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'ansible.vars.hostvars.HostVarsVars object' has no attribute 'hello'\n\nThe error appears to have been in '/home/kayke/Documentos/vm-vagrant/provision-ansible/centos/t0_tests/t0a.yml': line 8, column 5, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n tasks:\n - debug:\n ^ here\n"}
答案 0 :(得分:0)
您想要的是一本同时针对服务器和工作者的剧本,并根据其主机模式进行匹配,因为那样就只有一个单次运行,而现在发生的是ansible正在运行运行两次,每个主机一次。因此:
- hosts: server*
tasks:
- set_fact: hello=world
- hosts: worker*
tasks:
- debug:
msg: "{{ hostvars["server_1"]["hello"] }}"
并在最后调用,就像您在此处看到的:https://github.com/kubernetes-sigs/kubespray/blob/v2.8.3/Vagrantfile#L177-L193
我对Vagrant的研究还不足以知道它是否会为您写出清单文件,或者是什么,但是如果您需要一个示例,kubespray也会从所有已知的vms中生成清单文件:{{3 }}
如果您不喜欢这种方法,还可以使用https://github.com/kubernetes-sigs/kubespray/blob/v2.8.3/Vagrantfile#L69-L75来使ansible以可读取工作簿的方式写出主机的事实缓存,但是您可能会怀疑,这是吨的工作。