Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current role name in an ansible task

How can I get the current role name in an ansible task yaml file?

I would like to do something like this

--- # role/some-role-name/tasks/main.yml  - name: Create a directory which is called like the current role name   action: file           path=/tmp/"{{ role_name }}"           mode=0755           state=directory 

The result of this task should be a directory /tmp/some-role-name on the server

like image 797
czerasz Avatar asked Aug 15 '14 09:08

czerasz


People also ask

What is Pre_tasks in Ansible?

What is pre_tasks in Ansible? pre_tasks is a task which Ansible executes before executing any tasks mentioned in . yml file. Consider this scenario. You provisioned a new instance on Amazon EC2 cloud or Google Cloud .

What is the difference between roles and tasks in Ansible?

tl;dr A task is a single declaration (operation); a role is one of many ways for grouping tasks. A task in Ansible is a basic unit of work, a kind of counterpart to a line of code in other languages. A task is executed and has a result (ok, changed, failed).


2 Answers

The simplest way is to just use the following

{{role_path|basename}} 
like image 156
krad Avatar answered Sep 20 '22 22:09

krad


As of Ansible 2.2:

{{role_name}}

As of Ansible 2.1:

{{role_path|basename}}

Older versions:

There is no way to do this in the current version of Ansible, here are a couple options that might work for you instead:

1) Use set_fact to set a role_name var to the name the of role as the first task in your tasks/main.yml file

- set_fact: role_name=some-role-name 

2) Pass a parameter to your role that has the name

- roles:   - role: some-role-name     role_name: some-role-name 
like image 22
jarv Avatar answered Sep 18 '22 22:09

jarv