9

Given a playbook like this:

- name: "Tasks for service XYZ"
  hosts: apiservers
  roles:
    - { role: common }

Is there a way to reference the playbook's name ("Tasks for service XYZ")? (i.e. a variable)


EDIT:

My intention is to be able to reference the playbook's name in a role task, i.e. sending a msg via slack like

- name: "Send Slack notification indicating deploy has started"
  slack:
    channel: '#project-deploy'
    token: '{{ slack_token }}'
    msg: '*Deploy started* to _{{ inventory_hostname }}_ of `{{ PLAYBOOK_NAME }}` version *{{ service_version }}*'
  delegate_to: localhost
  tags: deploy
Diego Shevek
  • 486
  • 3
  • 15
  • 1
    I'm not sure what is your intention. Do you want something like `- name: "{{task_name}}"` if yes simply define a variable `task_name: "Tasks for service XYZ"` – JGK Sep 13 '18 at 12:42
  • Thanks for the correction @JGK. – Alex Harvey Sep 13 '18 at 13:21
  • @JGK My intention is actually to be able to get the name of the playbook in a role so I can use the name in the role (i.e. sending a msg to slack with the inventory's name) – Diego Shevek Sep 13 '18 at 13:42
  • Just to be precise, what your are referencing here is not the playbook name but the **play** name. You have a response below by @alexb involving ansible 2.8. – Zeitounator May 13 '19 at 10:07

3 Answers3

6

It was added in 2.8:

ansible_play_name
The name of the currently executed play. Added in 2.8.

L. F.
  • 19,445
  • 8
  • 48
  • 82
alexb
  • 880
  • 11
  • 16
4

No, the special variables for Ansible are documented here, and you can see that there is no variable to return the playbook name.

As mentioned in the comments, however, you can always do this:

---
- name: "{{ task_name }}"
  hosts: localhost
  vars:
    task_name: "Tasks for service XYZ"
  tasks:
    - debug:
        msg: "{{ task_name }}"
Alex Harvey
  • 14,494
  • 5
  • 61
  • 97
2

From your circumstances, it looks like you only want this for audit/notification purposes? In that case (and assuming unixy clients), using

lookup('file', '/proc/self/cmdline') | regex_replace('\u0000',' ')

will give you the entire command line that ansible-playbook was called with, parameters and all, which would include the playbook name. Depending on your circumstances, that might be a useful enough tradeoff.

Ulrich Schwarz
  • 7,598
  • 1
  • 36
  • 48