Skip to content

Instantly share code, notes, and snippets.

@jan-warchol
Created June 17, 2016 18:35
Show Gist options
  • Save jan-warchol/726c57042b13ab7729b1ad740ee0b534 to your computer and use it in GitHub Desktop.
Save jan-warchol/726c57042b13ab7729b1ad740ee0b534 to your computer and use it in GitHub Desktop.
Ansible hostvars evaluation problem

Setup

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 }}"

Output

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 }}"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment