Ansible - how to evaluate role_path variable

Willem van Ketwich picture Willem van Ketwich · Jan 23, 2017 · Viewed 14.4k times · Source

I'm trying to evaluate the value of the role_path variable in order to use it in other roles as a reference point. The problem is, however, when my variable is used in another role, it has the value of the other role, and not of when it was declared.

I am getting around this by using an echo command of the current variable's value and registering the output as per below.

- name: get ansible base path from current role_path
  command: echo {{ role_path }}/../../
  register: ansible_base_path_out

- name: save ansible base path variable for future use
  set_fact:
    ansible_base_path: "{{ ansible_base_path_out.stdout }}"

Is this the best way to do this or is there a more eloquent solution?

Answer

Konstantin Suvorov picture Konstantin Suvorov · Jan 23, 2017

You can safely use set_fact. Variables (fact) assigned via set_fact are evaluated during task execution time. Shrink your code to only one task:

- name: save ansible base path variable for future use
  set_fact:
    ansible_base_path: "{{ role_path }}/../../"

Apply this role at first and you'll get ansible_base_path fact unchanged throughout entire playbook execution.