How To Make Command Deicide When To Run When To Not In Ansible

Gupta Aditya
2 min readDec 21, 2020

--

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

Guys follow me for such amazing blogs and if have any review then please let me know I will keep those points in my mind next time while writing blogs. If want to read more such blog to know more about me here is my website link .https://sites.google.com/view/adityvgupta/home.Guys Please do not hesitate to keep 👏👏👏👏👏 for it (An Open Secret: You can clap up to 50 times for a post, and the best part is, it wouldn’t cost you anything), also feel free to share it across. This really means a lot to me.

--

--

Responses (1)