Python Vagrant
python-vagrant provides Python bindings for interacting with Vagrant virtual machines, allowing programmatic control over Vagrant environments. The current stable version is 1.0.0. Releases are somewhat irregular but active, with bug fixes and minor features released as needed, typically every few months.
Warnings
- breaking The `up()` method in version 1.0.0 changed its signature. The `vm_name` argument is now the first positional argument. If you were calling `up(provision=True)` you must now call `up(vm_name=None, provision=True)` or `up(None, provision=True)`.
- breaking Version 1.0.0 dropped support for Python 3.7. The minimum required Python version is now 3.8.
- gotcha This library acts as a wrapper around the Vagrant CLI tool. It does NOT bundle Vagrant itself. You must have the Vagrant CLI installed on your system and available in your PATH for `python-vagrant` to function correctly.
- deprecated Support for Python 3.8 has been deprecated in the upcoming 1.1.0 release (already available on GitHub, but not yet PyPI at the time of writing). While it might still work, future versions will likely drop support.
- gotcha Version 1.0.0 adopted a `src` code layout. While this primarily affects packaging, users with non-standard import patterns or those directly accessing internal modules might need to adjust their paths.
Install
-
pip install python-vagrant
Imports
- Vagrant
from vagrant import Vagrant
Quickstart
import vagrant
import os
# Ensure you have a Vagrantfile in this directory or provide its root path
# Example: Create a dummy Vagrantfile for testing if not present
vagrantfile_path = './test_vagrant_project'
if not os.path.exists(vagrantfile_path):
os.makedirs(vagrantfile_path)
if not os.path.exists(os.path.join(vagrantfile_path, 'Vagrantfile')):
with open(os.path.join(vagrantfile_path, 'Vagrantfile'), 'w') as f:
f.write("Vagrant.configure(\"2\") do |config|\n config.vm.box = \"hashicorp/bionic64\"\nend")
# Initialize Vagrant object with the root path of the Vagrant project
v = vagrant.Vagrant(root=vagrantfile_path)
try:
# Bring up the VM
print(f"Bringing up Vagrant VM in {vagrantfile_path}...")
v.up()
print("VM is up.")
# Get VM status
status = v.status()
for vm_status in status:
print(f"VM Name: {vm_status.name}, Provider: {vm_status.provider}, State: {vm_status.state}")
finally:
# Destroy the VM
print("Destroying Vagrant VM...")
v.destroy()
print("VM destroyed.")
# Clean up dummy Vagrantfile and directory
if os.path.exists(os.path.join(vagrantfile_path, 'Vagrantfile')):
os.remove(os.path.join(vagrantfile_path, 'Vagrantfile'))
if os.path.exists(vagrantfile_path):
os.rmdir(vagrantfile_path)