I want to use the following condition in ansible playbook.
Scenario is as follows.
If arg1 > 5
follow some steps
else
endif;
IF ELSE is not possible in ansible. However, how can i achive with the WHEN condition.
I want to use the following condition in ansible playbook.
Scenario is as follows.
If arg1 > 5
follow some steps
else
endif;
IF ELSE is not possible in ansible. However, how can i achive with the WHEN condition.
Just add a when to the tasks you want in the ‘if’
when: arg1 > 5
for the ‘else’ just use the opposite condition.
when: arg1 <=5
I did create the small task. However, for defining variable (num, numami) in the same task is not working.
e.g
tasks:
date +%d%b%G
; num=3; numami=5;These are not valid variables for Ansible (not since 1.6). Also, setting them in a shell will not make them available.
when: $numami > $num
Where i can set this variable so that i can compare it in where condition.
Any small test scenario will help me to understand.
This should help:
Tried below one. However, when condition is not correctly evaluating.
Even following condition true its executing other commands mentioned in other when condition.
current_image_state <= desire_image_state
tasks:
name: Get the state of the Test version
shell: alert1=cat /tmp/test.log | grep -e "pending" -e "failed" | wc -l
;
register: image_state
tags: image
name: Set the output of the Test state
set_fact: current_image_state=image_state.stdout
tags: Test1
name: Define our static value for the desired Test state
set_fact: desire_image_state=0
tags: Test2
name: Perform TASK1
command: sh /tmp/test.sh
when: current_image_state > desire_image_state
tags: final
name: Message if couldnot able to perform TASK1
debug: msg=“Need to check the status of Pending image”
when: current_image_state <= desire_image_state
tags: message
Tried below one. However, when condition is not correctly evaluating.
Please show the exact error message. Or the exact output, maybe with -v.
tasks:
- name: Get the state of the Test version
shell: alert1=`cat /tmp/test.log | grep -e "pending" -e "failed" | wc
-l`;
register: image_state
tags: image
Add a debug task here (with correct indentation):
- debug: var="image_state"
set_fact: current_image_state=image_state.stdout
I guess here is your error. You set the variable current_image_state
to a text string called "image_state.stdout". Add double curly braces
and quotes:
set_fact: current_image_state="{{ image_state.stdout }}"
- name: Define our static value for the desired Test state
set_fact: desire_image_state=0
I am not sure if thus sets desire_image_state to an integer or a string.
Johannes
Thanks !!
It works, post adding set_fact: current_image_state=“{{ image_state.stdout }}”.