Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

ansible - How to use variable substitution in a when condition?

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:

when: {{ home_directory}}/var_name['var_key'] != command_output['stdout']

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?

question from:https://stackoverflow.com/questions/65866313/how-to-use-variable-substitution-in-a-when-condition

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

However, I later found out that jinja templates {{}} or {%%} are not allowed/recommended in the when condition.

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.

In other words, instead of:

when: {{ home_directory}}/var_name['var_key'] != command_output['stdout']

Write:

when: home_directory ~ "/" ~ var_name['var-key'] != command_output['stdout']

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

This takes advantage of Linux string formatting syntax to substitute variables into a string.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...