简体   繁体   中英

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

最简单的方法是使用以下

{{role_path|basename}}

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

See this post :

To get the role directory:

role_dir: "{{ lookup('pipe', 'pwd') | dirname }}"

To get the role name:

role_name: "{{ lookup('pipe', 'pwd') | dirname | basename }}"

As of Ansible 2.8 there is ansible_play_name which contains the name of the currently executed play.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM