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

问题描述

我正在尝试在运行时基于另一个变量在Ansible中使用set_fact设置一个变量。如果使用第一个值,无论实际值是多少。这是我的代码示例:

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 %}"

<$ c $无论设置了什么 jm_env ,c> l_env 都是 d

l_env is d no matter what jm_env is set.

推荐答案

首先,YAML中的字典未排序(并且Ansible使用的语法是YAML字典),因此您无法保证Ansible首先在继续执行 l_env 之前,先设置 jm_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'是一个字符串,因为它被引用了;并测试如果'string'将始终评估为 true (这就是您始终获得<$ c $的直接原因c> 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,使用if then else语句的set_fact的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 09:51