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

Question:

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..

Asked By: Zack

||

Answers:

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
Answered By: Kieran

For Ansible tasks – Here are some examples:

- name: Install bottle python package
  ansible.builtin.pip:
    name: bottle

- name: Install bottle python package on version 0.11
  ansible.builtin.pip:
    name: bottle==0.11

- name: Install bottle python package with version specifiers
  ansible.builtin.pip:
    name: bottle>0.10,<0.20,!=0.11

- name: Install multi python packages with version specifiers
  ansible.builtin.pip:
    name:
      - django>1.11.0,<1.12.0
      - bottle>0.10,<0.20,!=0.11

Reference:
https://docs.ansible.com/ansible/latest/collections/ansible/builtin/pip_module.html

Answered By: Yakir GIladi Edry