3

I am having an ansible script. It calls other scripts using include module.

I need to get the current file name in a variable.

For ex:

 - include: Run-Config889.yml

Inside Run-Config889.yml, i need to get the file name Run-Config889.yml in a variable.

Whether any built-in variable is there to find the current file name? if so what it is?

Samselvaprabu
  • 16,830
  • 32
  • 144
  • 230
  • 1
    Idk about a starightforward way to do it. I guess you could use roles instead as they do give you a special var named "role_name". The workaround you could use if you don't want to use roles, is to maybe define the names of the .yml in variables. Save the name in a file in your localhost, and then execute the "include". So your included playbook, can then read the name from your file in your localhost. Does this make sense to you? – carrotcakeslayer Jan 30 '20 at 09:00
  • @SebastiánGreco Currently i am using variables to store the file name and use it. But in some places i need file name still. – Samselvaprabu Jan 30 '20 at 10:26

2 Answers2

1

You can get the current playbook file name with :

---
- hosts: 127.0.0.1
  connection: local
  gather_facts: no

  vars:
    playbook_absoluteName: "{{ (lookup('file', '/proc/self/cmdline') | regex_replace('\u0000',' ')).split() | select('match','^.*[.]ya?ml$') | list | first }}"
    playbook_baseName: "{{ playbook_absoluteName | basename }}"

  tasks:
  - debug:
      var: item
    loop:
      - "{{ playbook_absoluteName }}"
      - "{{ playbook_baseName }}"
...

This was inspired by this blog article, with minor/cosmetics improvements.

Httqm
  • 799
  • 7
  • 13
0

Don't know about any built-in variable but there are 2 options I can think of.

Option 1

You can pass variables to included files like so:

main.yml

---

- include: Run-Config889.yml file_name_variable="Run-Config889.yml"

Option 2

Set the variable in any of the vars files used by the play. All defined variables in a play are inherited by subsequent include statements.

sample-vars.yml

---

file_name_variable: "Run-Config889.yml"

Using the variable.

Run-Config889.yml

---

- name: Display variable
  debug:
    msg: File name {{ file_name_variable }}
Sten Saliste
  • 96
  • 1
  • 3