Installing Python from source

The Ansible Control node requires a relatively new version of Python (see matrix here), often newer then the one your OS relies on. For example, the default Python implementation in RHEL 9 is Python 3.9, while ansible-core 2.17 requires Python 3.10 or higher for the Ansible Control Node.

Sometimes you can install a newer version of Python with the package manager for your OS, but other times that is not an option. Therefore, the most reliable way to install Python is by building, compiling, and installing it from source.

In the following example, we will install Python3.12 on RHEL9 from source.

#!/bin/bash
# Mandatory packages - Python will not build without them.
sudo dnf -y install wget tar gzip gcc make zlib-devel 

# Required dependency for pip to work.
sudo dnf -y install openssl-devel

# Optional dependencies.
sudo dnf -y --skip-broken install bzip2-devel libffi-devel readline-devel sqlite-devel tk-devel uuid xz-devel

# Download and unarchive Python.
wget https://www.python.org/ftp/python/3.12.7/Python-3.12.7.tgz
tar zxvf Python-3.12.7.tgz
cd Python-3.12.7 || exit

# Set installation prefix before building. The altinstall target will leave the default system Python untouched.
./configure --prefix=/opt/python/3.12.7/
make
sudo make altinstall

# Create symlinks. Make sure that ~/.local/bin is in your $PATH.
ln -s /opt/python/3.12.7/bin/python3.12 ~/.local/bin/python3
ln -s /opt/python/3.12.7/bin/pip3.12 ~/.local/bin/pip

This process can also be automated with Ansible and you can check out an example on GitHub here.


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *