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

后端 未结 7 1204
执念已碎
执念已碎 2021-01-30 01:48

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?

7条回答
  •  梦如初夏
    2021-01-30 01:56

    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:

    # rpm -q httpd
    httpd-2.2.15-15.el6.centos.1.x86_64
    

    and like this if the package doesn't exist:

    # rpm -q httpdfoo
    package httpdfoo is not installed
    

    So your ansible tasks would look something like this:

    - name: Check if foo.rpm is installed
      command: rpm -q foo.rpm
      register: rpm_check
    
    - name: Execute script if foo.rpm is not installed
      command: somescript
      when: rpm_check.stdout.find('is not installed') != -1
    

    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:

    when: rpm_check.rc == 1
    

提交回复
热议问题