Search code examples
pythonvagrantvagrantfilevagrant-provisionpyenv

Install PyEnv in Vagrantfile


PyEnv does not have a great installer, and it requires some post-install processing to get it to work correctly (such as modifying .bashrc to add to $PATH and make two pyenv calls). I'm wondering how anyone has been able to get PyEnv installed via Vagrantfile. I want to build a reusable image to develop on so that I don't have to go through the reinstall process if I destroy this VM.

I've tried running the installer and making the recommended edits to .bashrc to get pyenv working, but when I get into my Vagrant box pyenv is not installed. I've tried moving the pyenv script into /bin/pyenv but it is not there when the machine comes up. How do I make this work?

For reference, here is the script I'm currently running that fails to install PyEnv to a Vagrant machine during a Vagrant provision step in the Vagrantfile:

#! /usr/bin/env bash

# REQUIRES: curl, git

curl -L https://raw.githubusercontent.com/pyenv/pyenv-
installer/master/bin/pyenv-installer | bash

cat >> /home/ubuntu/.bashrc << 'EOF'

export PATH="$PATH:~/.pyenv/bin"
eval "$(pyenv init -)"
eval "$(pyenv virtualenv-init -)"

EOF

exec $SHELL

And trying to move pyenv under /bin:

#! /usr/bin/env bash

# REQUIRES: curl, git

curl -L https://raw.githubusercontent.com/pyenv/pyenv-installer/master/bin/pyenv-installer | bash
mv ~/.pyenv/bin/pyenv /bin/pyenv

cat >> /home/ubuntu/.bashrc << 'EOF'

eval "$(pyenv init -)"
eval "$(pyenv virtualenv-init -)"

EOF

exec $SHELL

Neither work. How do I get this installed?


Solution

  • Your issue is that you're running the script through Vagrant shell provisioning as root so the update is done for your root user. When you ssh into the VM, you're logged in with your vagrant user so its not available.

    When you need to change is in your Vagrantfile to run the script using privileged option

    config.vm.provision "shell", path: "xxx", privileged: false