You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Jinja三元运算中引用变量?

在Ansible三元运算中引用变量的方法
  • 你的示例里变量some_str_var被包裹在单引号字符串中,Ansible不会解析字符串内的变量,需要通过以下方式正确引用:

  • 方法一:用Jinja2字符串拼接符~拆分字符串与变量

    shell: "{{ some_condition == 'True' | ternary('/bin/mycommand -F ' ~ some_str_var, '/bin/myOtherCommand -S ' ~ some_str_var) }}"
    

    用~连接静态命令片段和变量,Ansible会自动解析变量值并拼接成完整命令。

  • 方法二:使用格式化字符串语法

    shell: "{{ some_condition == 'True' | ternary('/bin/mycommand -F %s' % some_str_var, '/bin/myOtherCommand -S %s' % some_str_var) }}"
    

    以%s作为变量占位符,通过%操作符将变量值填充到对应位置。

  • 额外提示:

    • 如果some_condition本身是布尔类型(而非字符串"True"),可以简化条件判断:
      shell: "{{ some_condition | ternary('/bin/mycommand -F ' ~ some_str_var, '/bin/myOtherCommand -S ' ~ some_str_var) }}"
      
    • 注意引号嵌套逻辑,优先用单引号包裹字符串内容,避免和外层Jinja2的双引号冲突。

内容的提问来源于stack exchange,提问作者Mint

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 15:15:33