Ansible, set_fact 使用 if then else 语句 [英] Ansible, set_fact using if then else statement

查看:39
本文介绍了Ansible, set_fact 使用 if then else 语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试根据另一个变量在运行时使用 set_fact 在 Ansible 中设置一个变量.无论实际值是什么,如果使用第一个值.这是我的代码示例:

I am trying to set a variable in Ansible with set_fact at runtime based upon another variable. If uses first value no matter what the actual value is. Here is my code example:

- name: Global_vars - get date info
    set_fact:  
      jm_env: "{{lookup('env', 'Environment')}}"
      l_env: "{% if '{{jm_env}}==Develop' %}d{% elif '{{jm_env}}==Staging'%}s{% else %}p{% endif %}"

l_envd,无论 jm_env 设置了什么.

l_env is d no matter what jm_env is set.

推荐答案

首先,YAML 中的字典没有排序(这里 Ansible 使用的语法是 YAML 字典),所以你不能保证 Ansible 会先设置 jm_env 在继续 l_env 之前 - 您需要将作业拆分为两个任务.

Firstly, dictionaries in YAML are not ordered (and the syntax used by Ansible here is a YAML dictionary), so you have no guarantee Ansible would first set jm_env before proceeding to l_env -- you need to split the assignment into two tasks.

其次,你的测试表达式不正确——'{{jm_env}}==Develop' 是一个字符串,因为它被引用了;并测试 if 'string' 将始终评估为 true(这是您总是在输出中得到 d 的直接原因).

Secondly, your test expressions are incorrect -- '{{jm_env}}==Develop' is a string because it is quoted; and testing if 'string' will always evaluate to true (this is the direct reason you always get d in the output).

使用:

- name: Set the jm_env
    set_fact:  
      jm_env: "{{lookup('env', 'Environment')}}"

- name: Set the l_env
    set_fact:  
      l_env: "{% if jm_env=='Develop' %}d{% elif jm_env=='Staging'%}s{% else %}p{% endif %}"

这篇关于Ansible, set_fact 使用 if then else 语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆