简体   繁体   English

如何在ansible的vars文件中使用if条件

[英]How can i use if condition in vars file in ansible

Is it possible to do something like this in anisble vars file 是不是可以在anisble vars文件中做这样的事情

env: "{{ lookup('env','MY_ENV') }}"    
user: tom if {{ env }} else mike

Here is an answer to your question, I think you cannot use env as variable because it's reserved word in ansible: 这是你的问题的答案,我认为你不能使用env作为变量,因为它是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 : ENV值为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: ENV的值是其他值时的结果:

% 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 希望对你有所帮助

One way is to use another lookup into a json file containing the user-env mappings. 一种方法是使用另一个查找到包含user-env映射的json文件。 Eg: 例如:

user_envs.json: 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! 现在没有环境尝试,但试一试!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM