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
.
Assigning a value to a variable in a playbook is quite easy and straightforward. Begin by calling the vars keyword then call the variable name followed by the value as shown. In the playbook above, the variable name is salutations and the value is Hello world!
To pass a value to nodes, use the --extra-vars or -e option while running the Ansible playbook, as seen below. This ensures you avoid accidental running of the playbook against hardcoded hosts.
Setting Variables on the Command Line Variables set by passing -e var=value to ansible-playbook have the highest precedence, which means you can use this to override variables that are already defined. Example 4-11 shows how to set the variable named token to the value 12345 .
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:
a
and b
are integersa
and b
are strings containing numerical value with the same number of digitsHowever it produces unexpected result is when:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With