如何在 when 条件中使用变量替换? [英] How to use variable substitution in a when condition?
问题描述
我是一个新的 ansible 用户.我在任务的 when 条件中需要一个变量.我正在尝试使用定义为 home_directory 的 home_directory 变量:"{{ ansible_env.HOME }}"在 vars/main.yaml 文件中.
I'm a new ansible user. I need a variable in a task's when condition. I am trying to use home_directory variable, which is defined as home_directory: "{{ ansible_env.HOME }}" in the vars/main.yaml file.
我尝试使用以下内容:
when: {{ home_directory}}/var_name['var_key'] != command_output['stdout']
when: {{ home_directory}}/var_name['var_key'] != command_output['stdout']
然而,我后来发现 jinja 模板 {{}} 或 {%%} 在当条件.我也试过不带引号和 {{}} 的条件,但 home_directory 值是在 when 条件下不被替换.
However, I later found out that jinja templates {{}} or {%%} are not allowed/recommended in the when condition. I also tried condition without quotes and {{}} but home_directory value is not being replaced in the when condition.
有人能告诉我我可以在这里做什么吗?
Could someone please tell me what I can do here?
推荐答案
但是,我后来发现在 when 条件中不允许/推荐使用 jinja 模板 {{}} 或 {%%}.
However, I later found out that jinja templates {{}} or {%%} are not allowed/recommended in the when condition.
这是因为 when
的参数是在隐式模板上下文中计算的.换句话说,在 {{...}}
标记中准确地写下您将要写的内容,但您不需要标记,因为上下文是命令的固有内容.
This is because the arguments to when
are evaluated in an implicit template context. In other words, write exactly what you would write inside {{...}}
markers, but you don't need the markers because the context is intrinsic to the command.
换句话说,不是:
when: {{ home_directory}}/var_name['var_key'] != command_output['stdout']
写:
when: home_directory ~ "/" ~ var_name['var-key'] != command_output['stdout']
其中 ~
是 Jinja 字符串连接运算符.
Where ~
is the Jinja string concatenation operator.
我们可以稍微简化一下:
We can simplify that a bit:
when: "%s/%s" % (home_directory, var_name.var_key) != command_output.stdout
这利用 Linux 字符串格式化语法将变量替换为字符串.
This takes advantage of Linux string formatting syntax to substitute variables into a string.
这篇关于如何在 when 条件中使用变量替换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!