How to split an ansible role's `defaults/main.yml` file into multiple files?

myrdd picture myrdd · Aug 13, 2018 · Viewed 12.2k times · Source

In some ansible roles (e.g. roles/my-role/) I've got quite some big default variables files (defaults/main.yml). I'd like to split the main.yml into several smaller files. Is it possible to do that?

I've tried creating the files defaults/1.yml and defaults/2.yml, but they aren't loaded by ansible.

Answer

myrdd picture myrdd · Aug 13, 2018

The feature I'm describing below has been available since Ansible 2.6, but got a bugfix in v2.6.2 and another (minor) one in v2.7.
To see a solution for older versions, see Paul's answer.


defaults/main/

Instead of creating defaults/main.yml, create a directorydefaults/main/ — and place all YAML files in there.

  • defaults/main.ymldefaults/main/*.yml

Ansible will load any *.yml file inside that directory, so you can name your files like roles/my-role/defaults/main/{1,2}.yml.

Note, the old file — defaults/main.yml — must not exist. See this Github comment.


vars/main/

By the way, the above solution also works for vars/:

  • vars/main.ymlvars/main/*.yml

further details

The feature has been introduced in v2.6 — git commit, Pull Request, main Github issue.

There have been two bugfixes: