If you have built an ansible directory structure that allows you to invoke multiple roles and you want to use variables/credentials in ansible vault then you might get a bit stuck and find that when you run your playbook the variables are not found.
So let’s look at a directory structure to illustrate:
.
├── README.md
├── main.yml
└── roles
├── apache
│ ├── defaults
│ │ └── main.yml
│ ├── files
│ │ ├── apache.conf
│ ├── handlers
│ │ └── main.yml
│ ├── meta
│ │ └── main.yml
│ ├── tasks
│ │ └── main.yml
│ ├── templates
│ │ ├── wp-config.php.j2
│ │ ├── .htaccess.j2
│ └── vars
│ └── main.yml
├── mariadb
│ ├── defaults
│ │ └── main.yml
│ ├── handlers
│ │ └── main.yml
│ ├── tasks
│ │ ├── main.yml
│ │ ├── mariadb.config.yml
│ │ └── mariadb.install.yml
│ └── vars
│ └── main.yml
└── wordpress
├── handlers
│ └── main.yml
└── vars
└── main.yml
I’ve abridged some of the above output but it should hopefully be clear that we have 3 roles:
- apache
- mariadb
- wordpress
These are invoked from the main.yml in the root, which looks something like this:
---
- hosts: web_servers
become: true
roles:
- apache
- mariadb
- wordpress
Now, suppose that you have some variables/credentials which you want to use in these roles. Ansible documentation recommends that you create a group_vars directory to contain unencrypted variables which refer to the encrypted ones. The unencrypted variables would be prefixed by “vault_” and look something like this:
db_username: root
password: "{{ vault_root_password }}"
and your encrypted file’s contents would look something like this:
vault_root_password: 'somecomplexpasswordgoeshere'
But the bit that caught me out was that the variables would never get picked up.
The trick is that you need a group_vars directory in the root of the main directory and then an “all” subdirectory:
.
├── README.md
├── group_vars
│ └── all
│ ├── vars.yml
│ └── vault.yml
├── main.yml
└── roles
├── apache
│ ├── defaults
│ │ └── main.yml
│ ├── files
│ │ ├── apache.conf
│ ├── handlers
│ │ └── main.yml
│ ├── meta
│ │ └── main.yml
│ ├── tasks
│ │ └── main.yml
│ ├── templates
│ │ ├── wp-config.php.j2
│ │ ├── .htaccess.j2
│ └── vars
│ └── main.yml
├── mariadb
│ ├── defaults
│ │ └── main.yml
│ ├── handlers
│ │ └── main.yml
│ ├── tasks
│ │ ├── main.yml
│ │ ├── mariadb.config.yml
│ │ └── mariadb.install.yml
│ └── vars
│ └── main.yml
└── wordpress
├── handlers
│ └── main.yml
└── vars
└── main.yml
In the above, the vars.yml contains the unencrypted variables and the vault.yml contains the encrypted content.