github.com/dahs81/otto@v0.2.1-0.20160126165905-6400716cf085/helper/vagrant/build.go (about)

     1  package vagrant
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  
     7  	"github.com/hashicorp/otto/app"
     8  )
     9  
    10  type BuildOptions struct {
    11  	// Dir is the directory where Vagrant will be executed for the
    12  	// build. This should be the directory with the Vagrantfile, usually.
    13  	Dir string
    14  
    15  	// Script is the script to execute within the VM. This script must
    16  	// not ask for input.
    17  	Script string
    18  }
    19  
    20  // Build can be used to use Vagrant to build something. This will handle
    21  // starting Vagrant, running the script, collecting files into a list,
    22  // and destroying the Vagrant environment.
    23  func Build(ctx *app.Context, opts *BuildOptions) error {
    24  	log.Printf(
    25  		"[INFO] Vagrant build for '%s' in dir: %s",
    26  		ctx.Appfile.Application.Name, opts.Dir)
    27  
    28  	vagrant := &Vagrant{Dir: opts.Dir, Ui: ctx.Ui}
    29  
    30  	// tryDestroy is a helper function that we make a local here
    31  	// since we have to clean up in so many potential places.
    32  	tryDestroy := func() error {
    33  		err := vagrant.Execute("destroy", "-f")
    34  		if err != nil {
    35  			ctx.Ui.Header(fmt.Sprintf(
    36  				"[red]Error destroying the Vagrant environment! There may be\n"+
    37  					"lingering resources. The working directory where Vagrant\n"+
    38  					"can be run to check is below. Please manually clean up\n"+
    39  					"the resources:\n\n%s\n\n%s",
    40  				opts.Dir, err))
    41  		}
    42  
    43  		return err
    44  	}
    45  
    46  	// Bring the environment up. If there is an error, we need to
    47  	// destroy the VM because `vagrant up` can error even after the
    48  	// VM is built.
    49  	if err := vagrant.Execute("up"); err != nil {
    50  		ctx.Ui.Header(fmt.Sprintf(
    51  			"[red]Error while bringing up the Vagrant environment.\n" +
    52  				"The error message will be shown below. First, Otto\n" +
    53  				"will attempt to destroy the machine."))
    54  		tryDestroy()
    55  		return err
    56  	}
    57  
    58  	// The environment is running. Execute the build script.
    59  	if err := vagrant.Execute("ssh", "-c", opts.Script); err != nil {
    60  		ctx.Ui.Header(fmt.Sprintf(
    61  			"[red]Error while building in the Vagrant environment!\n" +
    62  				"The error message will be shown below. First, Otto will\n" +
    63  				"attempt to destroy the machine."))
    64  		tryDestroy()
    65  		return err
    66  	}
    67  
    68  	// Clean up the Vagrant environment
    69  	ctx.Ui.Message("Vagrant-based build is complete. Deleting Vagrant environment...")
    70  	tryDestroy()
    71  	return nil
    72  }