vagrant

package module
v1.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 26, 2018 License: MIT Imports: 12 Imported by: 6

README

Release Build Status codecov.io Go Report Card GoDoc

go-vagrant

A golang wrapper around the Vagrant command-line utility.

Installation

go-vagrant can be installed with go get:

go get github.com/bmatcuk/go-vagrant

Import it in your code:

import "github.com/bmatcuk/go-vagrant"

The package name will be vagrant.

Basic Usage

func NewVagrantClient(vagrantfileDir string) (*VagrantClient, error)

First, you'll need to instantiate a VagrantClient object using NewVagrantClient. The function takes one argument: the path to the directory where the Vagrantfile lives. This instantiation will check that the vagrant command exists and that the Vagrantfile can be read.

func (*VagrantClient) Action() *CommandObject
CommandObject.Option1 = ...
CommandObject.Option2 = ...

func (*CommandObject) Run() error
func (*CommandObject) Start() error
func (*CommandObject) Wait() error
CommandObject.Output
CommandObject.Error

From there, every vagrant action follows the same pattern: call the appropriate method on the client object to retrieve a command object. The command object has fields for any optional arguments. Then either call the command's Run() method, or call Start() and then Wait() on it later. Any output from the command, including errors, will be fields on the command object. The exact field names for options and output are listed below in the Actions section.

For example:

package main

import "github.com/bmatcuk/go-vagrant"

func main() {
  client, err := vagrant.NewVagrantClient(".")
  if err != nil {
    ...
  }

  upcmd := client.Up()
  upcmd.Verbose = true
  if err := upcmd.Run(); err != nil {
    ...
  }
  if upcmd.Error != nil {
    ...
  }

  // TODO: vagrant VMs are up!
}

Available Actions

Destroy

Stop and delete all traces of the vagrant machines.

func (*VagrantClient) Destroy() *DestroyCommand

Options:

  • Force (default: true) - Destroy without confirmation. Defaults to true because, when it's false, vagrant will try to ask for confirmation but complain that there's no attached TTY.
  • Parallel (default: false) - Enable or disable parallelism if provider supports it (automatically enables Force).

Response:

  • Error - Set if an error occurred.
Halt

Stops the vagrant machine.

func (*VagrantClient) Halt() *HaltCommand

Options:

  • Force (default: false) - Force shutdown (equivalent to pulling the power of the VM)

Response:

  • Error - Set if an error occurred.
Port

Get information about guest port forwarded mappings.

func (*VagrantClient) Port() *PortCommand

Options:

  • MachineName (default: "") - Specify the vagrant machine you are interested in. If your Vagrantfile only brings up one machine, you do not need to specify this. However, if your Vagrantfile brings up multiple machines, you must specify this! For some reason, this is the only vagrant command that cannot handle multiple machines.

Response:

  • ForwardedPorts - an array of ForwardedPort objects. Each ForwardedPort has a Guest and a Host port, representing a mapping from the host port to the guest.
  • Error - Set if an error occurred.
Provision

Provision the vagrant machine.

func (*VagrantClient) Provision() *ProvisionCommand

Options:

  • Provisioners (default: nil) - Enable only certain provisioners, by type or name as an array of strings.

Response:

  • Error - Set if an error occurred.
Reload

Restarts the vagrant machine and loads any new Vagrantfile configuration.

func (*VagrantClient) Reload() *ReloadCommand

Options:

  • Provisioning (default: DefaultProvisioning) - By default will only run provisioners if they haven't been run already. If set to ForceProvisioning then provisioners will be forced to run; if set to DisableProvisioning then provisioners will be disabled.
  • Provisioners (default: nil) - Enable only certain provisioners, by type or name as an array of strings. Implies ForceProvisioning.

Response:

  • Error - Set if an error occurred.
Resume

Resume a suspended vagrant machine

func (*VagrantClient) Resume() *ResumeCommand

Options:

  • Provisioning (default: DefaultProvisioning) - By default will only run provisioners if they haven't been run already. If set to ForceProvisioning then provisioners will be forced to run; if set to DisableProvisioning then provisioners will be disabled.
  • Provisioners (default: nil) - Enable only certain provisioners, by type or name as an array of strings. Implies ForceProvisioning.

Response:

  • Error - Set if an error occurred.
SSHConfig

Get SSH configuration information for the vagrant machine.

func (*VagrantClient) SSHConfig() *SSHConfigCommand

Options:

  • Host (default: "") - Name the host for the config

Response:

  • Configs - a map of vagrant machine names to SSHConfig objects. Each SSHConfig has several fields including Host, User, Port, etc. You can see full field list in the godocs for SSHConfig.
Status

Get the status of the vagrant machine.

func (*VagrantClient) Status() *StatusCommand

Response:

  • Status - a map of vagrant machine names to a string describing the status of the VM.
  • Error - Set if an error occurred.
Suspend

Suspends the vagrant machine.

func (*VagrantClient) Suspend() *SuspendCommand

Response:

  • Error - Set if an error occurred.
Up

Starts and provisions the vagrant machine.

func (*VagrantClient) Up() *UpCommand

Options:

  • Provisioning (default: DefaultProvisioning) - By default will only run provisioners if they haven't been run already. If set to ForceProvisioning then provisioners will be forced to run; if set to DisableProvisioning then provisioners will be disabled.
  • Provisioners (default: nil) - Enable only certain provisioners, by type or name as an array of strings. Implies ForceProvisioning.
  • DestroyOnError (default: true) - Destroy machine if any fatal error happens.
  • Parallel (default: true) - Enable or disable parallelism if provider supports it.
  • Provider (default: "") - Back the machine with a specific provider.
  • InstallProvider (default: true) - If possible, install the provider if it isn't installed.

Response:

  • VMInfo - a map of vagrant machine names to VMInfo objects. Each VMInfo describes the Name of the machine and Provider.
  • Error - Set if an error occurred.
Version

Get the current and latest vagrant version.

func (*VagrantClient) Version() *VersionCommand

Response:

  • InstalledVersion - the version of vagrant installed
  • LatestVersion - the latest version available
  • Error - Set if an error occurred.

Documentation

Overview

Package vagrant is a golang wrapper around the vagrant command-line utility. Full documentation can be found in the README on github:

https://github.com/bmatcuk/go-vagrant
Example
client, err := NewVagrantClient("example")
if err != nil {
	fmt.Println("Got error while creating client:", err)
	os.Exit(-1)
}

// Let's start bringing up the vm
upcmd := client.Up()
upcmd.Verbose = true
fmt.Println("Bringing up the vm")
if err := upcmd.Start(); err != nil {
	fmt.Println("Error bringing up vm:", err)
	os.Exit(-1)
}

// while we're waiting, let's get version info
vercmd := client.Version()
if err := vercmd.Run(); err != nil {
	fmt.Println("Error retrieving version info:", err)
}

// now wait for up to finish
if err := upcmd.Wait(); err != nil {
	fmt.Println("Error waiting for up:", err)
	os.Exit(-1)
}

fmt.Println("\n\nInstalled Vagrant version:", vercmd.InstalledVersion)

// Get vm status
statuscmd := client.Status()
if err := statuscmd.Run(); err != nil {
	fmt.Println("Error getting status:", err)
} else {
	for vm, status := range statuscmd.Status {
		fmt.Printf("%v: %v\n", vm, status)
	}
}

// Destroy vm
if err := client.Destroy().Run(); err != nil {
	fmt.Println("Error destroying vm:", err)
	os.Exit(-1)
}
Output:

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type BaseCommand

type BaseCommand struct {
	OutputParser

	// Context for the running command - nil means none
	Context context.Context

	// Additional arguments to pass to the command. go-vagrant attempts to define
	// each argument as a field on the struct, but future versions of vagrant may
	// add options that didn't exist at the time of authoring. You can use this
	// to pass options to vagrant that go-vagrant doesn't know about.
	AdditionalArgs []string

	// Env is merged with the current process's environment and passed to the
	// vagrant command. Each entry is a "key=value" pair with later keys taking
	// precedence in the case of duplicates (keys here will take precedence over
	// keys in the current environment, too).
	Env []string

	// The underlying process, once it has been started with Run() or Start()
	Process *os.Process

	// ProcessState contains information about the process after it has exited.
	// Available after Run() or Wait().
	ProcessState *os.ProcessState
	// contains filtered or unexported fields
}

BaseCommand adds base functionality and fields for all commands constructed from the VagrantClient.

func (*BaseCommand) Run

func (b *BaseCommand) Run() error

Run the command.

func (*BaseCommand) Start

func (b *BaseCommand) Start() error

Start the command. You must call Wait() to complete execution.

func (*BaseCommand) Wait

func (b *BaseCommand) Wait() error

Wait is used to wait on a command that was started with Start().

type DestroyCommand

type DestroyCommand struct {
	BaseCommand
	ErrorResponse

	// Destroy without confirmation (defaults to true because, when false,
	// vagrant will try to ask for confirmation, but can't because it's running
	// without a TTY so it errors).
	Force bool

	// Enable parallelism if the provider supports it (automatically enables
	// force, default: false)
	Parallel bool
}

A DestroyCommand specifies the options and output of vagrant destroy.

func (*DestroyCommand) Run

func (cmd *DestroyCommand) Run() error

Run the command

func (*DestroyCommand) Start

func (cmd *DestroyCommand) Start() error

Start the command. You must call Wait() to complete execution.

type ErrorResponse added in v1.1.0

type ErrorResponse struct {
	// If set, there was an error while running the vagrant command.
	Error error
}

ErrorResponse adds the Error field to command output.

type ForwardedPort

type ForwardedPort struct {
	// Port on the guest OS
	Guest int

	// Port on the host which forwards to the guest
	Host int
}

ForwardedPort defines the host port that maps to a guest port.

type HaltCommand

type HaltCommand struct {
	BaseCommand
	ErrorResponse

	// Force shutdown (equivalent to pulling the power from the machine, default:
	// false)
	Force bool
}

A HaltCommand specifies the options and output of vagrant halt.

func (*HaltCommand) Run

func (cmd *HaltCommand) Run() error

Run the command

func (*HaltCommand) Start

func (cmd *HaltCommand) Start() error

Start the command. You must call Wait() to complete execution.

type OutputParser

type OutputParser struct {
	// If true, vagrant output will be echoed to stdout. Default: false
	Verbose bool
}

OutputParser is used to parse the output from the vagrant command.

type PortCommand

type PortCommand struct {
	BaseCommand
	PortResponse

	// MachineName is the vagrant machine you are interested in. If your
	// Vagrantfile only brings up a single machine, you do not need to specify
	// this. However, if your Vagrantfile brings up multiple machines, you MUST
	// specify this! For some reason, this is the only vagrant command that
	// cannot handle multiple machines.
	MachineName string
}

PortCommand specifies the options and output of vagrant port.

func (*PortCommand) Run

func (cmd *PortCommand) Run() error

Run the command

func (*PortCommand) Start

func (cmd *PortCommand) Start() error

Start the command. You must call Wait() to complete execution.

type PortResponse

type PortResponse struct {
	ErrorResponse

	// ForwardedPorts is a list of ports forwarded from the host OS to the guest
	// OS for the requested vagrant machine.
	ForwardedPorts []ForwardedPort
}

PortResponse is the output from the vagrant port command.

type ProvisionCommand

type ProvisionCommand struct {
	BaseCommand
	ErrorResponse
	ProvisionersArgument
}

ProvisionCommand specifies the options and output of vagrant provision

func (*ProvisionCommand) Run

func (cmd *ProvisionCommand) Run() error

Run the command

func (*ProvisionCommand) Start

func (cmd *ProvisionCommand) Start() error

Start the command. You must call Wait() to complete execution.

type ProvisionersArgument added in v1.1.0

type ProvisionersArgument struct {
	// Enabled provisioners by type or name (default: blank which means they're
	// all enable or disabled depending on the Provisioning flag)
	Provisioners []string
}

ProvisionersArgument adds the Provisioners argument to a command.

type ProvisioningArgument added in v1.1.0

type ProvisioningArgument struct {
	ProvisionersArgument

	// Enable or disable provisioning
	Provisioning ProvisioningOption
}

ProvisioningArgument adds Provisioning and Provisioners arguments to a Command.

type ProvisioningOption added in v1.1.0

type ProvisioningOption uint8

ProvisioningOption is used to set whether provisioning should be forced, disabled, or use the default.

const (
	// DefaultProvisioning will cause vagrant to run the provisioners only if
	// they haven't already been run.
	DefaultProvisioning ProvisioningOption = iota

	// ForceProvisioning will force the provisioners to run.
	ForceProvisioning

	// DisableProvisioning will disable provisioners.
	DisableProvisioning
)

type ReloadCommand

type ReloadCommand struct {
	BaseCommand
	ErrorResponse
	ProvisioningArgument
}

ReloadCommand specifies the options and output of vagrant reload

func (*ReloadCommand) Run

func (cmd *ReloadCommand) Run() error

Run the command

func (*ReloadCommand) Start

func (cmd *ReloadCommand) Start() error

Start the command. You must call Wait() to complete execution.

type ResumeCommand added in v1.1.0

type ResumeCommand struct {
	BaseCommand
	ErrorResponse
	ProvisioningArgument
}

A ResumeCommand specifies the options and output of vagrant resume.

func (*ResumeCommand) Run added in v1.1.0

func (cmd *ResumeCommand) Run() error

Run the command

func (*ResumeCommand) Start added in v1.1.0

func (cmd *ResumeCommand) Start() error

Start the command. You must call Wait() to complete execution.

type SSHConfig

type SSHConfig struct {
	// Any additional fields returned from the ssh-config command.
	AdditionalFields map[string]string

	// Whether or not to enable ForwardAgent - "yes" or "no"
	ForwardAgent string

	// The Host matches the vagrant machine name (ex: default)
	Host string

	// The HostName to connect to (ex: 127.0.0.1)
	HostName string

	// Whether or not to enable IdentitiesOnly - "yes" or "no"
	IdentitiesOnly string

	// Path to a private key file to use for the connection (ex: ~/.ssh/id_rsa)
	IdentityFile string

	// Level of logging to enable (ex: FATAL)
	LogLevel string

	// Whether or not to enable password authentication - "yes" or "no"
	PasswordAuthentication string

	// Port to connect to (ex: 22)
	Port int

	// Whether or not to enable StrictHostKeyChecking - "yes" or "no"
	StrictHostKeyChecking string

	// User to connect as (ex: root)
	User string

	// Path to a known hosts file (ex: /dev/null)
	UserKnownHostsFile string
}

The SSHConfig struct has all of the settings you'll need to connect to the vagrant machine via ssh. The fields and values match the fields and values that an ssh config file is expecting. For example, you could build a ssh config file like:

Host ...
  HostName ...
  Port ...
  User ...
  IdentityFile ...

type SSHConfigCommand

type SSHConfigCommand struct {
	BaseCommand
	SSHConfigResponse

	// Name of a specific host to get SSH config info for. If not set, info for
	// all VMs will be pulled.
	Host string
}

SSHConfigCommand specifies options and output from vagrant ssh-config

func (*SSHConfigCommand) Run

func (cmd *SSHConfigCommand) Run() error

Run the command

func (*SSHConfigCommand) Start

func (cmd *SSHConfigCommand) Start() error

Start the command. You must call Wait() to complete execution.

type SSHConfigResponse

type SSHConfigResponse struct {
	ErrorResponse

	// SSH Configs per VM. Map keys match vagrant VM names (ex: default) and
	// the values are configs.
	Configs map[string]SSHConfig
}

SSHConfigResponse has the output from vagrant ssh-config

type StatusCommand

type StatusCommand struct {
	BaseCommand
	StatusResponse
}

StatusCommand specifies options and output from vagrant status

func (*StatusCommand) Run

func (cmd *StatusCommand) Run() error

Run the command

func (*StatusCommand) Start

func (cmd *StatusCommand) Start() error

Start the command. You must call Wait() to complete execution.

type StatusResponse

type StatusResponse struct {
	ErrorResponse

	// Status per Vagrant VM. Keys are Vagrant VM names (ex: default) and values
	// are the status of the VM.
	Status map[string]string
}

StatusResponse has the output from vagrant status

type SuspendCommand

type SuspendCommand struct {
	BaseCommand
	ErrorResponse
}

SuspendCommand specifies options and output from vagrant suspend

func (*SuspendCommand) Run

func (cmd *SuspendCommand) Run() error

Run the command

func (*SuspendCommand) Start

func (cmd *SuspendCommand) Start() error

Start the command. You must call Wait() to complete execution.

type UpCommand

type UpCommand struct {
	BaseCommand
	UpResponse
	ProvisioningArgument

	// Destroy on error (default: true)
	DestroyOnError bool

	// Enable parallel execution if the provider supports it (default: true)
	Parallel bool

	// Provider to use (default: blank which means vagrant will use the default
	// provider)
	Provider string

	// Install the provider if it isn't installed, if possible (default: false)
	InstallProvider bool
}

UpCommand specifies options and output from vagrant up.

func (*UpCommand) Run

func (cmd *UpCommand) Run() error

Run the command

func (*UpCommand) Start

func (cmd *UpCommand) Start() error

Start the command. You must call Wait() to complete execution.

type UpResponse

type UpResponse struct {
	ErrorResponse

	// Info about all of the VMs constructed by the Vagrantfile. The map keys are
	// vagrant VM names (ex: default) and the values are VMInfo's.
	VMInfo map[string]*VMInfo
}

UpResponse is the output from vagrant up

type VMInfo

type VMInfo struct {
	// Name of the VM set by vagrant (ex: mydir_default_1534347044260_6006)
	Name string

	// The VM provider (ex: virtualbox)
	Provider string
}

VMInfo has information about the created vagrant machines.

type VagrantClient

type VagrantClient struct {
	// Directory where the Vagrantfile can be found.
	//
	// Normally this would be set by NewVagrantClient() and shouldn't
	// be changed afterward.
	VagrantfileDir string
	// contains filtered or unexported fields
}

VagrantClient is the main entry point to the library. Users should construct a new VagrantClient using NewVagrantClient().

func NewVagrantClient

func NewVagrantClient(vagrantfileDir string) (*VagrantClient, error)

NewVagrantClient creates a new VagrantClient.

vagrantfileDir should be the path to a directory where the Vagrantfile exists.

func (*VagrantClient) Destroy

func (client *VagrantClient) Destroy() *DestroyCommand

Destroy will destroy the vagrant machines. After setting options as appropriate, you must call Run() or Start() followed by Wait() to execute. Errors will be recorded in Error.

func (*VagrantClient) Halt

func (client *VagrantClient) Halt() *HaltCommand

Halt will shutdown the vagrant machine. After setting options as appropriate, you must call Run() or Start() followed by Wait() to execute. Errors will be recorded in Error.

func (*VagrantClient) Port

func (client *VagrantClient) Port() *PortCommand

Port will return information about ports forwarded from the host to the guest machine. After setting options as appropriate, you must call Run() or Start() followed by Wait() to execute. Output will be in ForwardedPorts with any error in Error.

This appears to be the only vagrant command that cannot handle multi-vm Vagrantfiles for some reason. If your Vagrantfile brings up multiple machines, you MUST specify which machine you are interested in by specifying the PortCommand.MachineName option!

func (*VagrantClient) Provision

func (client *VagrantClient) Provision() *ProvisionCommand

Provision will run the provisioners in a Vagrantfile. After setting options as appropriate, you must call Run() or Start() followed by Wait() to execute. Errors will be recorded in Error.

func (*VagrantClient) Reload

func (client *VagrantClient) Reload() *ReloadCommand

Reload will halt and restart vagrant machines, reloading config from the Vagrantfile. After setting options as appropriate, you must call Run() or Start() followed by Wait() to execute. Errors will be recorded in Error.

func (*VagrantClient) Resume added in v1.1.0

func (client *VagrantClient) Resume() *ResumeCommand

Resume will restart a vagrant machine that has been suspended or halted. After setting options as appropriate, you must call Run() or Start() followed by Wait() to execute. Errors will be recorded in Error.

func (*VagrantClient) SSHConfig

func (client *VagrantClient) SSHConfig() *SSHConfigCommand

SSHConfig will return connection information for connecting to a vagrant machine via ssh. After setting options as appropriate, you must call Run() or Start() followed by Wait() to execute. Output will be in Configs and any error will be in Error.

func (*VagrantClient) Status

func (client *VagrantClient) Status() *StatusCommand

Status will return the status of vagrant machines. After setting options as appropriate, you must call Run() or Start() followed by Wait() to execute. Output will be in Status and any error will be in Error.

func (*VagrantClient) Suspend

func (client *VagrantClient) Suspend() *SuspendCommand

Suspend will cause the vagrant machine to "suspend", like putting a computer to sleep. After setting options as appropriate, you must call Run() or Start() followed by Wait() to execute. Errors will be recorded in Error.

func (*VagrantClient) Up

func (client *VagrantClient) Up() *UpCommand

Up creates, if necessary, and brings up the vagrant machines. After setting options as appropriate, you must call Run() or Start() followed by Wait() to execute. Output will be in VMInfo or Error.

func (*VagrantClient) Version

func (client *VagrantClient) Version() *VersionCommand

Version returns the current and latest version of vagrant. After setting options as appropriate, you must call Run() or Start() followed by Wait() to execute. Output will be in InstalledVersion and LatestVersion and any error will be in Error.

type VersionCommand

type VersionCommand struct {
	BaseCommand
	VersionResponse
}

VersionCommand specifies options and output from vagrant version

func (*VersionCommand) Run

func (cmd *VersionCommand) Run() error

Run the command

func (*VersionCommand) Start

func (cmd *VersionCommand) Start() error

Start the command. You must call Wait() to complete execution.

type VersionResponse

type VersionResponse struct {
	ErrorResponse

	// The current version
	InstalledVersion string

	// The latest version
	LatestVersion string
}

VersionResponse is the output from vagrant version

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL