在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.
我尝试使用类似以下的内容:
I tried to use something like following:
何时:{{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.
我们可以简化一下:
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屋!