Question:
I have an ansible variable passed in on the command line as such:
1 2 |
ansible-playbook -e environment=staging ansible/make_server.yml |
I want to load in some variables in my role dependeing on the value of environment. I have tried a lot of different methods such as:
1 2 3 |
- include_vars: staging_vars.yml when: environment | staging |
and
1 2 3 |
- include_vars: staging_vars.yml when: "{{environment}} == "staging" |
and
1 2 3 |
- include_vars: staging_vars.yml when: "{{environment}} | match('staging')" |
but nothing seems to work. How do I do this?
Details:
- I am using ansible 1.7.2
Answer:
Be careful with a variable called environment
, it can cause problems because Ansible uses it internally. I can’t remember if it’s in the docs, but here’s a mailing list thread:
https://groups.google.com/forum/#!topic/ansible-project/fP0hX2Za4I0
We use a variable called stage
.
It looks like you’ll end up with a bunch of these in a row:
1 2 3 4 5 6 7 |
- include_vars: testing_vars.yml when: stage == "testing" - include_vars: staging_vars.yml when: stage == "staging" - include_vars: production_vars.yml when: stage == "production" |
But you could also just include your environment:
1 2 |
- include_vars: "{{ stage }}_vars.yml" |
Or, use the
vars_files
on a playbook level:
1 2 3 |
vars_files: - vars/{{ stage }}_vars.yml |