DEV Community

loading...

A different approach working with Ansible variables

stefanomartins profile image Stefano Martins Updated on ・2 min read

When using folders to organize Ansible projects, usually we use the host_vars subfolder to store the variables that belong to hosts declared in our inventory files, ending with something like this in our hands:

.
├── group_vars
├── hosts
├── host_vars
│   └── host-01.yml
├── roles
│   └── webservers
│       ├── files
│       ├── tasks
│       │   └── main.yml
│       └── templates
└── webservers.yml
Enter fullscreen mode Exit fullscreen mode

Here, we're using the hosts file as our inventory, which has only one host, host-01, and storing all its variables on the host_vars/host-01.yml file.

For many people, this approach will work just great, with absolutely nothing wrong with it. But as our infrastructure grows, so does the number of variables, and manage it can become a little bit cumbersome, with two major problems:

Over time all variables from all subjects (different roles, for instance) are stored in the same place, so it can become quite messy.

The second problem is that when you're using Ansible Vault to encrypt files that contains sensitive information, like passwords, you have a workflow similar to this:

  • Run git pull
  • Edit your file with ansible-vault edit ${file}
  • Commit your changes
  • Run git push

But in this approach, you have to that even you're not changing anything sensitive-related, which is a bummer.

To solve those two problems, what you can do instead is create a folder inside host_vars with the name of your host, and inside of it YAML files containing your variables. Ansible automatically will concatenate them when called. Then, use Vault just for the files that have sensitive information (here, for instance, we're assuming that for the host_vars/host-01/password.yml file). Here's an example:

.
├── group_vars
├── hosts
├── host_vars
│   └── host-01
│       ├── main.yml
│       └── passwords.yml
├── roles
│   └── webservers
│       ├── files
│       ├── tasks
│       │   └── main.yml
│       └── templates
└── webservers.yml
Enter fullscreen mode Exit fullscreen mode

You can have as many YAML files you want inside the folder, and by the way, you don't have to name "main.yml" any of them.

Abraços!

Discussion (0)

pic
Editor guide