How do I set register a variable to persist between plays in ansible?


I have an ansible playbook, where I’d like a variable I register on one machine to be available on another.

In my case, I’d like to run a command on localhost, in this case git rev-parse --abbrev-ref HEAD, so I can make a note of the current git branch, and sha1, and register this output, so I can refer to it later when working any machine in the main group, in the second play.

However, it’s not clear to me how I register a variable on localhost, so I can access it from main. When I try to access the variable in the second play I get this message:

Here’s the play I’m using. Is there anything obvious I should be doing?


The problem you’re running into is that you’re trying to reference facts/variables of one host from those of another host. You need to keep in mind that in Ansible, the variable app_git_sha1 assigned to the host localhost is distinct from the variable app_git_sha1 assigned to the host main or any other host. If you want to access one hosts facts/variables from another host then you need to explicitly reference it via the hostvars variable.

Suppose you have a playbook like this:

This will work because you’re referencing the host localhost and localhosts‘s instance of the variable foo in both plays. The output of this playbook is something like this:

If you modify this playbook slightly to run the first play on one host and the second play on a different host, you’ll get the error that you encountered. The solution is to use Ansible’s built-in hostvars variable to have the second host explicitly reference the first hosts variable. So modify the first example like this:

The output of this playbook shows that the first task is skipped because foo is not defined by the host anotherhost. But the second task succeeds because it’s explicitly referencing localhosts‘s instance of the variable foo:

So, in a nutshell, you want to modify the variable references in your main playbook to reference the localhost variables in this manner:

Leave a Reply