如何使用条件在 Ansible 中设置变量值? [英] How can I use a condition to set a variable value in Ansible?

查看:27
本文介绍了如何使用条件在 Ansible 中设置变量值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个变量:ab.

我想为变量 c 赋值,基于它:ab 包含更大的数值.

I want to assign a value to a variable c based on which: a or b contains greater numerical value.

这是我试过的:

- set_fact:
    c: "test1"
  when: a <= b

- set_fact:
    c: "test2"
  when: b <= a

看起来它总是将 c 设置为 test1 而不是 test2.

Look like it always sets c to test1 not test2.

推荐答案

  • 使用 if-else 表达式:

    - set_fact:
        c: "{{ 'test1' if (a >= b) else 'test2' }}"
    

  • 使用三元运算符:

  • Using ternary operator:

    - set_fact:
        c: "{{ (a >= b) | ternary ('test1', 'test2') }}"
    

  • 使用您自己的正确代码(请参阅下面的通知)

  • Using your own code which is correct (see the notice below)

    上述任何一种方法都要求用于比较的两个变量具有相同的类型才能给出合理的结果.对于数值比较,它们要求两个值都是整数.

    Either of the above methods requires both variables used in comparison to be of the same type to give sensible results. And for a numerical comparison, they require both values to be integers.

    问题中的代码:

    - set_fact:
        c: "test1"
      when: a <= b
    
    - set_fact:
        c: "test2"
      when: b <= a
    

    在两种情况下都能正常工作:

    works properly in two cases:

    • 两者:ab 都是整数
    • 两者:ab 都是包含相同位数的数值的字符串
    • both: a and b are integers
    • both: a and b are strings containing numerical value with the same number of digits

    然而它会产生意想不到的结果是什么时候:

    However it produces unexpected result is when:

    • 其中一个值是字符串,另一个是整数
    • 字符串值包含不同位数的数值

    这篇关于如何使用条件在 Ansible 中设置变量值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆