About Installing Any Python Version on a Remote Server with pyenv and Ansible

Using pyenv, you can install any python version on a remote server. Here is an Ansible snippet:

- name: Install pyenv build dependencies
  apt:
    pkg:
      - make
      - build-essential
      - libssl-dev
      - zlib1g-dev
      - libbz2-dev
      - libreadline-dev
      - libsqlite3-dev
      - curl
      - llvm
      - libncursesw5-dev
      - xz-utils
      - tk-dev
      - libxml2-dev
      - libxmlsec1-dev
      - libffi-dev
      - liblzma-dev
    update_cache: yes

- name: Install pyenv as root
  shell: curl -fsSL https://pyenv.run | bash
  args:
    executable: /bin/bash
    creates: /opt/pyenv/bin/pyenv
  environment:
    PYENV_ROOT: /opt/pyenv
    HOME: /root

- name: Install Python 3.14 via pyenv
  shell: /opt/pyenv/bin/pyenv install 3.14.0
  args:
    executable: /bin/bash
    creates: /opt/pyenv/versions/3.14.0/bin/python
  environment:
    PYENV_ROOT: /opt/pyenv

- name: Create virtual environment
  command: /opt/pyenv/versions/3.14.0/bin/python -m venv /var/webapps/myproject/.venv/
  args:
    creates: /var/webapps/myproject/.venv/bin/python

That's analogous to bash commands:

# Install pyenv build dependencies
apt-get update && apt-get install -y \
  make build-essential libssl-dev zlib1g-dev libbz2-dev \
  libreadline-dev libsqlite3-dev curl llvm libncursesw5-dev \
  xz-utils tk-dev libxml2-dev libxmlsec1-dev libffi-dev liblzma-dev

# Install pyenv
export PYENV_ROOT=/opt/pyenv
export HOME=/root
curl -fsSL https://pyenv.run | bash

# Install Python 3.14
/opt/pyenv/bin/pyenv install 3.14.0

# Create virtual environment
/opt/pyenv/versions/3.14.0/bin/python -m venv /var/webapps/myproject/.venv

Tips and Tricks Dev Ops Development Python 3 pyenv Ansible