I have an Ansible playbook, this playbook has a role on it, this role is configured to run only on 2 hosts:

- hosts: node1,orchestrator1
  gather_facts: True
  any_errors_fatal: True
  remote_user: root
    - role: configure_vault_backups
      when: "add_vault_ds|bool == True"

Inside the role there are some tasks that saves on some variables the output of some shell commands, BUT these tasks run only to one host (node1) OR the other host (orchestrator1), as an example:

- name: Check if nfs_mount is online
  shell: mount | grep "/var/lib/hypercx/datastores/nfs_mount"
  register: nfs_mount_output
  ignore_errors: yes
  changed_when: false
  when: "'orchestrator' in ansible_hostname and one_ip in ansible_all_ipv4_addresses"

Now, I do have the variable with some values, BUT if I try to use this variable (in this case the variable es nfs_mount_output) in a task that will run on both hosts, when the role runs the role in the host that has NOT the variable defined in the previous tasks ansible complains telling me that the variable is not defined.

What I did was to create another task that set the a new variable with the previous variable, something like:

- set_fact:
    nfs_mount_output_globlar: "{{ nfs_mount_output }}"

But I guess there is a better way to achieve it...

So the question is: can I make those variables somehow global(?) inside the task?

1 Answer 1


It is a little bit tricky with Ansible. And also depends on the version you use. But I suppose you use relatively newest one.

I hope my answer helps, and if not, it gives you new ideas to explore :) And that I get your issue properly.

You can define global variable, however Ansible understoods it in specific way. If you declare it through configuration or environment vars, then it will be seen as "global".

For example, you can define it in your inventory file:



You can define variable in host section of your play:

- name: my play
  hosts: myservers
    foo: bar

And also, you can work with facts, but as you already said, sometimes it doesn't look like the "right" option.

You can find some best practices for variables on Spacelift blog post (disclaimer: I am Developer Advocate there).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.