Having troubles accessing hostvars for new host

I have some tasks like:

`

  • debug: var=hostvars[item]
    with_items: groups.rabbitmq_server

  • name: Update /etc/hosts with rabbitmq-server hostnames
    lineinfile:
    dest: /etc/hosts
    regexp: “^{{hostvars[item][‘ansible_default_ipv4’][‘address’]}} {{hostvars[item][‘ansible_hostname’]}}$”
    line: “{{hostvars[item][‘ansible_default_ipv4’][‘address’]}} {{hostvars[item][‘ansible_hostname’]}}”
    state: present
    with_items: groups.rabbitmq_server

`

When the second runs I get:

TASK: [Update /etc/hosts with rabbitmq-server hostnames] **********************
fatal: [10.0.136.70] => One or more undefined variables: ‘dict object’ has no attribute ‘ansible_default_ipv4’
fatal: [10.0.137.195] => One or more undefined variables: ‘dict object’ has no attribute ‘ansible_default_ipv4’

But just in the debug above I have:

`
“ansible_default_ipv4”: {
“address”: “10.0.137.195”,
“alias”: “eth0”,
“gateway”: “10.0.137.1”,
“interface”: “eth0”,
“macaddress”: “0e:ab:ba:38:c4:a1”,
“mtu”: 9001,
“netmask”: “255.255.255.0”,
“network”: “10.0.137.0”,
“type”: “ether”
},

`

( I used to reference the hostvars like hostvars[item].ansible_default_ipv4.address but tried using just out of frustration. )

Oh, I should have mentioned, this only happens when I have created the ec2 instances in the same play run. On a second run I don’t ever seem to get this error.

And this is on 1.9.2

did you gather facts after creating the instances?

Yes, the play explicitly has gather_facts:true. The debug just above the failure clearly shows the attribute is present, that’s what is confusing.

gather_facts happens before other tasks, my question was if you
gathered facts AFTER creating the new hosts

The flow is:

provision.yml:------------------

`

  • name: Provision rabbitmq cluster
    hosts: localhost
    connection: local
    gather_facts: yes
    tags: [provision, rabbitmq_cluster]

tasks:

  • name: Create rabbitmq-server instance
    ec2:

  • include: …/…/configure/rabbitmq-server.yml
    tags: [configure, rabbitmq_cluster]
    `

rabbitmq-server.yml

So the new hosts don't get added to the rabbitmq_server group?

I assume this will happen automatically next time the inventory script
runs (if tagged), but that won't happen until you run ansible again,
normally you use add_hosts to temporarily add them for the 'current
run'.