Ansible Do Task If Apt Package Is Missing

Simply  Seth picture Simply Seth · Feb 26, 2015 · Viewed 15.1k times · Source

I'm looking to do a series of tasks if a specific apt package is missing.

for example:

if graphite-carbon is NOT installed do:

- apt: name=debconf-utils state=present
- shell: echo 'graphite-carbon/postrm_remove_databases boolean false' | debconf-set-selections
- apt: name=debconf-utils state=absent

another example:

if statsd is NOT installed do:

- file: path=/tmp/build state=directory
- shell: cd /tmp/build ; git clone https://github.com/etsy/statsd.git ; cd statsd ; dpkg-buildpackage 
- shell: dpkg -i /tmp/build/statsd*.deb

How would I begin to crack this?

I'm thinking maybe I can do a -shell: dpkg -l|grep <package name> and capture the return code somehow.

Answer

Simply  Seth picture Simply Seth · Feb 27, 2015

It looks like my solution is working.

This is an example of how I have it working:

- shell: dpkg-query -W 'statsd'
  ignore_errors: True
  register: is_statd

- name: create build dir
  file: path=/tmp/build state=directory
  when: is_statd|failed

- name: install dev packages for statd build
  apt:  name={{ item }} 
  with_items: 
    - git 
    - devscripts 
    - debhelper
  when: is_statd|failed

- shell: cd /tmp/build ; git clone https://github.com/etsy/statsd.git ; cd statsd ; dpkg-buildpackage 
  when: is_statd|failed

....

Here is another example:

 - name: test if create_superuser.sh exists
  stat: path=/tmp/create_superuser.sh 
  ignore_errors: True
  register: f

- name: create graphite superuser
  command: /tmp/create_superuser.sh
  when: f.stat.exists == True

...and one more

- stat: path=/tmp/build
  ignore_errors: True
  register: build_dir

- name: destroy build dir
  shell: rm -fvR /tmp/build 
  when: build_dir.stat.isdir is defined and build_dir.stat.isdir