Python Vagrant

1.0.0 · active · verified Fri Apr 10

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

Install

Imports

Quickstart

This quickstart demonstrates how to initialize `python-vagrant`, bring up a VM, check its status, and destroy it. It requires the Vagrant CLI tool to be installed and available in your system's PATH. A simple Vagrantfile is created for demonstration purposes if not already present.

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)

view raw JSON →