Reputation: 3113
Is it possible to do something like this in anisble vars file
env: "{{ lookup('env','MY_ENV') }}"
user: tom if {{ env }} else mike
Upvotes: 1
Views: 1580
Reputation: 23791
Here is an answer to your question, I think you cannot use env
as variable because it's reserved word in ansible:
---
- hosts: all
gather_facts: no
vars:
ENV: "dev"
tasks:
- debug:
msg: "{%- if ENV == 'dev' -%} tom {%- else -%} mike {%- endif -%}"
Result when the value of ENV
is dev
:
% ansible-playbook -i "localhost," test.yml -c local
PLAY [all] *********************************************************************
TASK [debug] *******************************************************************
ok: [localhost] => {
"msg": "tom"
}
PLAY RECAP *********************************************************************
localhost : ok=1 changed=0 unreachable=0 failed=0
Result when the value of ENV
is something else:
% ansible-playbook -i "localhost," test.yml -c local
PLAY [all] *********************************************************************
TASK [debug] *******************************************************************
ok: [localhost] => {
"msg": "mike"
}
PLAY RECAP *********************************************************************
localhost : ok=1 changed=0 unreachable=0 failed=0
Hope that help you
Upvotes: 2
Reputation: 4379
One way is to use another lookup into a json file containing the user-env mappings. E.g.:
user_envs.json:
{
"dev": "tom",
"prod": "mike"
}
lookup:
{{ (lookup('file', 'user_envs.json') | from_json).get('dev') }}
Don't have an env to try it now but give it a shot!
Upvotes: 1