Vagrantfile
# -*- mode: ruby -*-
# vi: set ft=ruby :
Vagrant.configure("2") do |config|
(1..2).each do |i|
config.vm.define "vm#{i}" do |node|
node.vm.box = "ubuntu/trusty64"
node.vm.network :private_network, ip: "192.168.0.1#{i}" # eth1
node.vm.network :private_network, ip: "10.0.0.1#{i}" # eth2
end
end
end
inventory
vm1 ansible_ssh_host=192.168.0.11 ansible_ssh_user=vagrant ansible_ssh_pass=vagrant if_control=eth1
vm2 ansible_ssh_host=192.168.0.12 ansible_ssh_user=vagrant ansible_ssh_pass=vagrant if_control=eth2
group_vars/all.yml
var_ip: "{{ hostvars[inventory_hostname]['ansible_' + if_control].ipv4.address }}"
debug-hostvars.yml
- hosts: all
gather_facts: yes
- hosts: vm1
tasks:
- name: I can use vars that are defined using hostvars
debug: msg="{{ var_ip }}"
- name: I can use hostvars directly
debug: msg="{{ hostvars['vm2']['ansible_' + hostvars['vm2'].if_control].ipv4.address }}"
- name: I can use vars from other hosts
debug: msg="{{ hostvars['vm2'].if_control }}"
- name: But I cannot use vars from other hosts that are defined using hostvars
debug: msg="{{ hostvars['vm2'].var_ip }}"
TASK [I can use vars that are defined using hostvars] **************************
ok: [vm1] => {
"msg": "192.168.0.11"
}
TASK [I can use hostvars directly] *********************************************
ok: [vm1] => {
"msg": "10.0.0.12"
}
TASK [I can use vars from other hosts] *****************************************
ok: [vm1] => {
"msg": "eth2"
}
TASK [But I cannot use vars from other hosts that are defined using hostvars] **
ok: [vm1] => {
"msg": "{{ hostvars[inventory_hostname]['ansible_' + if_control].ipv4.address }}"
}