How can I persist an ansible variable across ansible roles?


I’ve registered a variable in a play.

I can access that variable fine, until I make the request inside a role.

For example, in a separate role in the same run, I want to access that registered variable:

I get the following output:

How can I access variables registered in a separate role, within the same play?

Edit for clarity of how things piece together:


NB: This was written referring to Ansible 1.X. I suspect variable parsing and scoping has changed considerably with Ansible 2.0, so bear that in mind. I’ll try to update the answer if I get time (or maybe someone else will answer for v2.0!)

There are two options here. The simplest is to define the variables in your top-level playbook, then propagate them down into your various roles. You can either set these as simple vars, or use pre_tasks to lookup / calculate values dynamically, e.g.

The second option requires that you add a task to whichever role you need to extract a variable from (though since all ansible roles are open-source, that should be easy enough). The trick is to use set_fact to export a variable as a ‘host_fact’, e.g.

Which can then be accessed later like so:

As described in this bit of the ansible docs.

Note that if you always want to lookup the hostvars of the current machine you’re running commands on (without knowing what it’s actually called in the ansible hosts file), you can use the variable inventory_hostname like so:

(Note lack of quote-marks, since it’s a variable, not a string-literal.)

Slightly awkward, but those combinations have met all my needs so far.

Leave a Reply