Search code examples
pythonpipconditional-statementsansiblevirtualenv

How would I confirm that a python package is installed using ansible


I am writing an ansible playbook, and I would first like to install pew, and transition into that pew environment in order to install some other python libraries.

So, my playbook is going to look something like this...

tasks:

# task 1
- name: install pew if necessary
  command: pip install pew

# task 2
- name: create new pew environment if necessary
  command: pew new devpi-server

# task 3
- name: transition to pew environment
  command: pew workon devpi-server

# task 4
- name: install devpi-server
  command: pip install devpi-server

# task 5
- name: run devpi server
  command: devpi-server ## various args

In the spirit of keeping my playbook idempotent, I would like to do all of these tasks only if necesary.

So, I would only want to install pew if it isn't already installed, only want to create a new pew environment if it doesn't already exist, only workon the pew environment if we aren't already... etc etc...

Does anyone have good advice as to how to accomplish this? I am somewhat familiar with ansible conditionals, but only when it is something like, "is a file downloaded or not"

I haven't had to determine yet if programs are installed, virtual environments are loaded, etc..


Solution

  • You can use the Pip module in Ansible to ensure that certain packages are installed.

    For your conditionals I would refer to: How to make Ansible execute a shell script if a package is not installed and http://docs.ansible.com/ansible/playbooks_conditionals.html#register-variables - these should get you on the right track.

    So your playbook would look a little like:

    - pip: name=pew
    
    - name: Check if pew env exists
      command: pew command
      register: pew_env_check
    
    - name: Execute script if pew environment doesn't exist
      command: somescript
      when: pew_env_check.stdout.find('no packages found') != -1