Really quick tutorial of how to install a custom Python version from source code with a help of Ansible. The resulting playbook will help us to install python in automatic mode on any remote machine as well as on virtual machine within Vagrant. So the code of Ansible playbook first followed with a little bit of explanation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
---

- name: Install required packages
apt: name={{item}} state=installed
with_items:
- build-essential
- libssl-dev
- libreadline-dev
- openssl
become: true

- name: Download archive with python
get_url:
url: "https://www.python.org/ftp/python/{{ python_version }}/Python-{{ python_version }}.tgz"
dest: "/tmp/python.tgz"
force: yes

- name: Extract python archive
unarchive:
src: "/tmp/python.tgz"
dest: "/opt"
copy: no

- name: Build python from source code
shell: |
./configure && \
make && \
make install
args:
chdir: "/opt/Python-{{ python_version }}"
become: true

First we install packages that are required to compile/build Python properly, then download and extract source code from official ftp and finally build it from sources with a help of a make tool.
Optionally, you can add a check for current python version to save your time if running a playbook often enough

1
2
3
4
- name: Check which python version is installed
shell: "python3 --version"
register: python_output
ignore_errors: true

After that just wrap the task above in a block section with when condition or do the similar with inlude.

1
2
3
- name: Install specific version of Python
include: "python.yml"
when: python_output.stdout != "Python {{ python_version }}"

And yes, you can make it as a separate role or include directly into the tasks section within your playbook. In case of using Vagrant you need to update your Vagrantfile if haven’t done it yet.

1
2
3
4
config.vm.provision :ansible do |ansible|
ansible.playbook = "ansible/provision.yml"
ansible.config_file = "ansible/ansible.cfg"
end

Do not forget to specify required python version in your vars.yml and you’ll be good to go. Next time invoking a playbook on a remote or running provisioning on your vm (vagrant provision) you will get Python installed and ready to use.

Other approaches

You can try to install python with a help of apt-get using package archives provided by deadsnakes. There is an ansible module allowing you to write tasks corresponding to commands below

1
2
3
$ sudo add-apt-repository ppa:deadsnakes/ppa
$ sudo apt-get update
$ sudo apt-get install python3.5

This PPA contains most recent Python versions for each minor release so it will not fit your needs in case you should have specific patch version on your system. (X.Y.Z - x - major, y - minor, z - patch).

Next option is to use pyenv and allow it to install required distribution for you

1
$ pyenv install 3.5.2

That’s it! Stick with preferred solution and don’t forget to reuse the approach writing ansible playbook for that.

Resources