#ansible #iac

Ansible and temporary dynamic hosts

Ansible has a task called add_host. It adds extra hosts to the inventory at play execution time. It has two non obvious properties, though.

First, such a host is not automatically selected as execution target during current play. Only subsequent plays, that run in the same execution context, can match such new host with host selectors. The other is that such added hosts will stay in the inventory to the end of execution context.

This second property can sometimes be particularly tricky, because you may be writing your play and, at first, thinking about it in isolation. But later on you may want to include it as part of a bigger playbook containing other plays.

In such a situation, any subsequent plays, if they match this new host, e.g. via all selector, will execute on it.

Now, this may be something that you want. Or maybe you have used add_host as a temporary target that does not make sense to be modified by other plays. In this second scenario you have a problem.

Before Ansible 2.14 it was possible to clear inventory from such added hosts with meta: refresh_inventory. I believe it was not documented, though. Then this behavior became classified as a bug (2019) and later ultimately fixed (2022), meaning it has stopped being a way to drop temporary, playbook specific hosts from the inventory.

This proposal on the other hand is open and discusses option to add remove_host task, that would be a proper and explicit way of removing dynamic hosts from the inventory at run time. This would be a very useful addition.