Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible roles. Default values

Tags:

ansible

I cannot find the answer in the docs, neither I can find an example: is it possible to name files in role/defaults/ other then main.yml? I mean, is main.yml the only valid name for a file with default values?

like image 809
madhead - StandWithUkraine Avatar asked Oct 26 '25 12:10

madhead - StandWithUkraine


2 Answers

By the sound of this documentation;

http://docs.ansible.com/ansible/playbooks_roles.html#roles

Roles are just automation around ‘include’ directives as described above, and really don’t contain much additional magic beyond some improvements to search path handling for referenced files. However, that can be a big thing!

This designates the following behaviors, for each role ‘x’:

If roles/x/tasks/main.yml exists, tasks listed therein will be added to the play

If roles/x/handlers/main.yml exists, handlers listed therein will be added to the play

If roles/x/vars/main.yml exists, variables listed therein will be added to the play

If roles/x/defaults/main.yml exists, variables listed therein will be added to the play

If roles/x/meta/main.yml exists, any role dependencies listed therein will be added to the list of roles (1.3 and later) Any copy, script, template or include tasks (in the role) can reference files in roles/x/{files,templates,tasks}/ (dir depends on task) without having to path them relatively or absolutely

Q: I mean, is main.yml the only valid name for a file with default values?
A: Sounds like it is only if you are wanting ansible to automatically load certain var_files for that role and auto include the task file.

Q: Is it possible to name files
A: Yes, it just means in the playbook you have to use the include directive and explicitly point it to the unique task file name.

Example:

- name: Do role
  hosts: localhost
  tasks:
  - include: roles/operations/tasks/installProgram.yml
like image 189
Samuel Toh Avatar answered Oct 29 '25 07:10

Samuel Toh


As you tell in the comments, it's possible to call a file anything else under the roles/my_role/defaults/. The issue is that files like roles/my_role/defaults/anything_else.yml will never be loaded as default. Even you will be able to load it with include_vars, it will gain the high precedence of included vars (18/22).

Nevertheless, since Ansible 2.6, your are able to use a directory main in place of a main.yml file!

By doing so, you can reach your goal by splitting your variables into roles/my_role/defaults/main/something.yml, roles/my_role/defaults/main/anything_else.yml, …

More details in this StackOverflow answer.

But indeed this feature is not yet documented (I just created an issue about that).

like image 39
xenlo Avatar answered Oct 29 '25 05:10

xenlo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!