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
123 views
in Technique[技术] by (71.8m points)

How can I use a condition to set a variable value in Ansible?

I have two variables: a, b.

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

This what I tried:

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

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

Look like it always sets c to test1 not test2.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)
  • Using if-else expression:

    - 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.

The code from the question:

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

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

works properly in two cases:

  • 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:

  • one of the values is string and the other integer
  • the string values contain numerical values with different number of digits

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

...