ahawkins
ahawkins

Reputation: 1174

Use multiple var files in ansible role

One of my roles has two different variable types. One is public (things like package versions and other benign information). These can be committed to SCM without a worry. It also requires some private information (such as API keys and other secret information). I'm using ansible-vault to encrypt secret information. My solution was to have vars/main.yaml for pulic, and vars/vault.yml for the encrypted private information.

I came across a problem and am uncertain what's the best practice or actual solution here. It seems that ansible only loads the vars/main.yml file. Naturally I do not want to encrypt the public information so I looked for solution. So far the only solution I came up with (suggested on IRC) is to create group_vars/all/vault.yml and prefix all variables with the role name. This works because ansible seems to recursively load everything under group_vars. This does work but seems organizationally incorrect because the variables are for a specific role and not "globally universally true". I also tried to put include: vars/vault.yml into vars/main.yml but that did not work.

Is there a proper way to do this?

Upvotes: 23

Views: 24150

Answers (3)

Chadys
Chadys

Reputation: 196

In case anyone is still trying to do that, instead of having the following structure:

vars/main.yml
vars/vault.yml

which won't work like you saw, you can instead organise your role like this:

vars/main/vars.yml
vars/main/vault.yml

Every vars file in the 'main' dir will be loaded by your role and you can encrypt your 'vault.yml' file only.

Upvotes: 13

flxPeters
flxPeters

Reputation: 1542

Using Vault is a good idea. But you should not do this in a role.

The reason is, your role just declares a variable and its default. A playbook will use this or set its one value. If a variable is private, you should declare the variable as required, but without a default. So if anybody is using your role he must declare the variable in order to make it run.

One solution to ask for a required variable is a simple condition:

- fail: msg="Variable foo is required"
  when: foo is not defined

So the handling of vault encrypted variables is on playbook level an. It's an implementation detail which should not be in a role.

Upvotes: 6

udondan
udondan

Reputation: 59989

As very first task in your role you could have an include_vars task.

- include_vars: vault.yml

I have never tried it but according to the docs vault encrypted files can be used with the include_vars module.

The vault feature can encrypt any structured data file used by Ansible. This can include “group_vars/” or “host_vars/” inventory variables, variables loaded by “include_vars” or “vars_files” [...]

Upvotes: 15

Related Questions