Ansible - how to evaluate role_path variable

16,561

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.

Share:
16,561
Willem van Ketwich
Author by

Willem van Ketwich

I code and administrate using a variety of languages and platforms using a variety of services including node.js, .net, php, powershell, javascript, c#, vb, ruby, python, java, angular, on linux, windows, android, using aws, and azure among others.

Updated on June 13, 2022

Comments

  • Willem van Ketwich
    Willem van Ketwich almost 2 years

    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?

  • Jonathan
    Jonathan over 5 years
    Can you have a colon delimited path (with multiple role paths)? I have subrepos with roles
  • Konstantin Suvorov
    Konstantin Suvorov over 5 years
    Not sure what you mean. role_path is the current role’s pathname.