add_host module doesn't modify hostvars or groups magic variables

I am writing a playbook that adds hosts to the inventory and then writes a host inventory file based on the hosts defined. The host added with add_host isn’t reflected in the hostvars or groups variable. I would have expected the added host to be added to the group and any parent groups, but it doesn’t seem to be the case. If I try to connect to the host in the next play, it will connect, but the “magic” variables don’t pick it up. Seen in ansible 1.2.2 and 1.3.2.

Playbook: (test_group_add.yml)

I have tested this without turning gather_facts off as well - same result.

"and then writes a host inventory file based on the hosts defined. "

This is a bit of a non-standard pattern.

add_host is fine for adding a host temporarily before re-running the inventory script, like if you need to do things all in the same play.

Would be better to have an inventory script that just dynamically loads inventory from your virtualization system.

Can I hear a bit more about your use case?

Our dev/test uses a cloud provider, skytap, for which we have built an ansible module (cleaning up for contribution to ansible core) to create instances with. We create instances, install our applications and would like to save off a host file so we can interact with the instance again to redeploy or run other tasks.

Loading inventory from our provider would be possible, but pulling raw ip addresses doesn’t lend itself to putting machines in groups and isolating environments will be difficult because we have multiple developers using multiple isolated environments for test. It could be done, obviously, but it isn’t trivial. It is cleaner to write our set of loaded hosts to a local file for use downstream, especially for automated tests.

We have static inventory files for our long-standing machines in our staging and production environments.

Regardless, it looks like the hostvars and groups variables don’t get updated when add_host is used, doesn’t seem like correct behavior.

I looked at where I could make the change, might submit a pull request tomorrow if I can figure out how to reinject those variables, looks like they are just added at runtime. One thing I found was that if the group is a new group, it does get updated. Odd.

Thanks,

  • Matt Ferrante

“Regardless, it looks like the hostvars and groups variables don’t get updated when add_host is used, doesn’t seem like correct behavior.”

If you mean you can’t set them dynamically (in RAM) yes, they should be settable. I think there’s already a bug in github about this as James Tanner was looking at this earlier today.

It’s totally expected though that it would not update the files on disk, and they should not.

If you’d like to take a crack at it of course, that would be appreciated!

This is the bug I was looking at earlier: https://github.com/ansible/ansible/issues/3848

It seems related at first glance, but I still need to do more testing.