I'm trying to set up environment specific variables in ansible (e.g. production, staging, development). For some reason, ansible is not picking up variables in group_vars/[environment].
I'm using ansible 1.9.1
Here's a stripped down example of what I'm trying to do.
Directory structure:
.
├── group_vars
│ └── staging
├── hosts
│ └── staging
└── site.yml
group_vars/staging:
test_var: "this is a test"
site.yml:
---
- hosts: localhost
tasks:
- debug: msg="test variable = {{ test_var }}"
hosts/staging is an empty file
Output of running ansible-playbook -i hosts/staging site.yml
:
PLAY [localhost] **************************************************************
GATHERING FACTS ***************************************************************
ok: [localhost]
TASK: [debug msg="test variable = {{ test_var }}"] ****************************
fatal: [localhost] => One or more undefined variables: 'test_var' is undefined
FATAL: all hosts have already failed -- aborting
PLAY RECAP ********************************************************************
to retry, use: --limit @/Users/jcowley/site.retry
localhost : ok=1 changed=0 unreachable=1 failed=0
If I move group_vars/staging to group_vars/all, it works as expected and outputs the value of test_var. But I'm trying to understand how I can separate environments per the documentation in Ansible's Best Practices
EDIT:
To answer your question more specifically, please have a look at this github exemple project. This is, I think, what you tried to do. I might be wrong, but I think the problem comes from your inventory file. You actually named your
group_vars
files (staging
) after your inventory filename (staging
too). But, you must name it after the section inside your inventory file, which is, I suppose,localhost
looking at your playbook.Thus, this is what you should have:
hosts/staging:
Here is, according to me, a more viable solution to organize your project. It is based on roles.
Directory structure:
The
group_vars/all
could have an env variable:Your inventory file:
Then, your playbook
sites.yml
could look like this:Doing it this way gives you multiple benefits:
roles/exemple/vars/
directory.