When does ansible refresh the variables from the host_vars directory?

Hi all,

I have a play that adds a line to a file in the host_vars directory on
the host running the play. I have a very sporadic error, that the
contents of the file are not being re-read afterwards.

I'll explain with a mock-up playbook containing three plays:

- hosts: foo
  gather_facts: true
  tasks:
    - name: "do something on foo"
    ...

- hosts: localhost
  gather_facts: true
  tasks:
    - name: "Change the line in host_vars on the host running the play"
    ...

- hosts: localhost
  gather_facts: true
  tasks:
    - name: "Do something that involves using this variable"

The third task does see the variable defined in the change file in the
host_vars, but not always. And not reproducibly.

Is there a way to trigger re-reading the host_vars files?

I'll try using set_fact next, but as this is only valid til the end of
the play IIRC, I'll have to combine the plays 2 and 3 (which I only
separeted because I hoped this would trigger the re-read...). And I am
not sure if the syntax allows setting hostvars for another host...

Any ideas?

Johannes

With set_fact the facts is available for all subsequent plays in a playbook, it only get lost after the playbook is finished.

Good Evening Kai,

Hi guys,

Yeah, I just found out, too. But now I have to see how to set a
variable for a host, that can not be reached at this point in time.
Delegate_to with set_fact? I'll try...

I can't get the syntax right for setting a hostvar with set_fact.

The newly created file in the host_vars directory is apparently not
read during a playbook run, even if there are multiple plays inside it.

I tried to include the file with include_vars, but can't get the
namespace right, so the variable foobar inside the yml file is put
into the hostvars of host xyz.

Also, set_fact with delegate_to does not set the variable.

The background is that I am creating a new lxc container on a machine,
whose ssh host pubkey I want to have in my known_hosts to avoid
unknown-hostkey-prompt durinng an ansible run...

So my workflow is
- creating the container
- ssh-keyscan from the host
- write the results into a file in host_vars/xyz/
- update my known_hosts which uses a for-loop for all containers on
the lxc host
- connect to the container without prompt
- and bootstrap it

Maybe I am abusing ansible right now, but at the moment this seems to
be the easiest approach without blindly accepting ssh host keys...

Johannes

Hi guys,

Hi Johannes

Also, set_fact with delegate_to does not set the variable.

Have you tried setting "delegate_facts: true"?
https://docs.ansible.com/ansible/playbooks_delegation.html#delegated-facts

It might work on set_fact to.

Hi Kai,

Yay! This did the trick. Thanks Kai, I would not have thought of
trying that.

If I got some minutes I'll update the docs to include this.

Johannes