How to install a Python version on server using Ansible

I am using ansible to connect with server. But I am getting errors for certain pip packages because of older version of python. How can I install a specific version of python (2.7.10) using ansible. Current python version on the server is 2.7.6

For now I have compiled and installed the python version manually but would prefer to have a way to do it via ansible.


The first thing to consider is that you probably don't want to replace or upgrade the system version of Python. This is because it's used by the system itself for things like package management, and so replacing it may cause other important things to break.

Installing an extra copy of Python that someone else made

To get an extra version of Python installed, the easiest option is to use a ppa, such as https://launchpad.net/~fkrull/+archive/ubuntu/deadsnakes-python2.7 so that someone else has done the work of turning Python into a package for you.

A PPA can be added with Ansible's apt repository module using a directive like the one below, which will then allow you to install packages from it the normal ansible way:

apt_repository: repo='ppa:fkrull/deadsnakes-python2.7'

Building a package yourself

If there is no ppa that has the version of Python you require, then you may need to build a .deb package yourself. The simplest way of doing this is a tool like checkinstall. There's also fpm, which can take lots of different sources and make deb, rpm and so on with them. It can also take a Python module only available with pip install and turn it into a system package for you, which is very useful.

Once you have a deb package you can install it with Ansible's apt module

apt: deb=/tmp/mypackage.deb

Additionally to @Simon Fraser's answer, the following playbook is what I use in Ansible to prepare a server with some specific Python 3 version:

# python_version is a given variable, eg. `3.5`
- name: Check if python is already latest
  command: python3 --version
  register: python_version_result
  failed_when: "{{ python_version_result.stdout | replace('Python ', '') | version_compare(python_version, '>=') }}"

- name: Install prerequisites
  apt: name=python-software-properties state=present
  become: true

- name: Add deadsnakes repo
  apt_repository: repo="ppa:deadsnakes/ppa"
  become: true

- name: Install python
  apt: name="python{{ python_version }}-dev" state=present
  become: true

I have the above in a role too, called ansible-python-latest (github link) in case you are interested.