How To Make Command Deicide When To Run When To Not In Ansible
Hey guys in today's article we are going to solve an exciting use case in ansible we have to use a command module to start or stop the service but restarting service again and again or installing software one software again and again which is already installed is not a good option for production.

Here we are taking the example of an httpd server to suppose our server is running then we want our system to go to the remote system and check the status of the server is running then it should not do anything, but if the server is stopped then it should execute the command and start the server.

We have a module for this it's just an example.

For doing this we are going to use the register keyword,ignore_yes keyword etc

- hosts: all

tasks:

— command: “systemctl status httpd”

register: x

ignore_errors: yes

— debug:

var: x.rc

— command: “systemctl start httpd”

when: x.rc != 0

register keyword is used to store all output of a particular task in one variable as you can see above we have stored output of command module in x variable if the command no run then for ansible it is error and to skip it we have to use ignore_yes keywords because in ansible if one task fails then all succeeding task fail automatically.

When ansible run command it gives RC which called running code if its 0 then command run successfully and if any value other than 0 then it mean command not run. This is the reason we have set x.rc !=0 this means the command only runs when RC is not equal to zero.

Guys, here we come to the end of this blog I hope you all like it and found it informative. If have any query feel free to reach me :)
['Gupta Aditya']
['Articles', 'DevOps', 'Information Technology', 'Ansible', 'Automation']