How to make Ansible execute a shell script if a package is not installed?

Question:

How can I make Ansible execute a shell script if a (rpm) package is not installed? Is it somehow possible to leverage the yum module?

Answer:

I don’t think the yum module would help in this case. It currently has 3 states: absent, present, and latest. Since it sounds like you don’t want to actually install or remove the package (at least at this point) then you would need to do this in two manual steps. The first task would check to see if the package exists, then the second task would invoke a command based on the output of the first command.

If you use “rpm -q” to check if a package exists then the output would look like this for a package that exists:

and like this if the package doesn’t exist:

So your ansible tasks would look something like this:

The rpm command will also exit with a 0 if the package exists, or a 1 if the package isn’t found, so another possibility is to use:

Leave a Reply