just make vagrantfile instead of calling init

This commit is contained in:
Megan Marsh 2019-02-07 12:39:56 -08:00
parent e56d7f7234
commit dc848ea5d7
5 changed files with 80 additions and 174 deletions

View File

@ -56,7 +56,6 @@ type Config struct {
// Options for the "vagrant init" command // Options for the "vagrant init" command
BoxVersion string `mapstructure:"box_version"` BoxVersion string `mapstructure:"box_version"`
Minimal bool `mapstructure:"init_minimal"`
Template string `mapstructure:"template"` Template string `mapstructure:"template"`
SyncedFolder string `mapstructure:"synced_folder"` SyncedFolder string `mapstructure:"synced_folder"`
@ -200,14 +199,12 @@ func (b *Builder) Run(ui packer.Ui, hook packer.Hook, cache packer.Cache) (packe
Force: b.config.PackerForce, Force: b.config.PackerForce,
Path: b.config.OutputDir, Path: b.config.OutputDir,
}, },
&StepInitializeVagrant{ &StepCreateVagrantfile{
BoxVersion: b.config.BoxVersion, Template: b.config.Template,
Minimal: b.config.Minimal, SyncedFolder: b.config.SyncedFolder,
Template: b.config.Template, SourceBox: b.config.SourceBox,
SourceBox: b.config.SourceBox, OutputDir: b.config.OutputDir,
OutputDir: b.config.OutputDir, GlobalID: b.config.GlobalID,
BoxName: b.config.BoxName,
GlobalID: b.config.GlobalID,
}, },
&StepAddBox{ &StepAddBox{
BoxVersion: b.config.BoxVersion, BoxVersion: b.config.BoxVersion,

View File

@ -3,6 +3,7 @@ package vagrant
import ( import (
"context" "context"
"fmt" "fmt"
"log"
"os" "os"
"path/filepath" "path/filepath"
"text/template" "text/template"
@ -11,10 +12,7 @@ import (
"github.com/hashicorp/packer/packer" "github.com/hashicorp/packer/packer"
) )
type StepInitializeVagrant struct { type StepCreateVagrantfile struct {
BoxName string
BoxVersion string
Minimal bool
Template string Template string
SourceBox string SourceBox string
OutputDir string OutputDir string
@ -36,8 +34,8 @@ type VagrantfileOptions struct {
BoxName string BoxName string
} }
func (s *StepInitializeVagrant) getVagrantfileTemplate() (string, error) { func (s *StepCreateVagrantfile) createVagrantfile() (string, error) {
tplPath := filepath.Join(s.OutputDir, "packer-vagrantfile-template.erb") tplPath := filepath.Join(s.OutputDir, "Vagrantfile")
templateFile, err := os.Create(tplPath) templateFile, err := os.Create(tplPath)
if err != nil { if err != nil {
retErr := fmt.Errorf("Error creating vagrantfile %s", err.Error()) retErr := fmt.Errorf("Error creating vagrantfile %s", err.Error())
@ -74,36 +72,7 @@ func (s *StepInitializeVagrant) getVagrantfileTemplate() (string, error) {
return abspath, nil return abspath, nil
} }
func (s *StepInitializeVagrant) prepInitArgs() ([]string, error) { func (s *StepCreateVagrantfile) Run(_ context.Context, state multistep.StateBag) multistep.StepAction {
// Prepare arguments
initArgs := []string{}
if s.BoxName != "" {
initArgs = append(initArgs, s.BoxName)
}
initArgs = append(initArgs, s.SourceBox)
if s.BoxVersion != "" {
initArgs = append(initArgs, "--box-version", s.BoxVersion)
}
if s.Minimal {
initArgs = append(initArgs, "-m")
}
tplPath, err := s.getVagrantfileTemplate()
if err != nil {
return initArgs, err
}
initArgs = append(initArgs, "--template", tplPath)
return initArgs, nil
}
func (s *StepInitializeVagrant) Run(_ context.Context, state multistep.StateBag) multistep.StepAction {
driver := state.Get("driver").(VagrantDriver)
ui := state.Get("ui").(packer.Ui) ui := state.Get("ui").(packer.Ui)
// Skip the initialize step if we're trying to launch from a global ID. // Skip the initialize step if we're trying to launch from a global ID.
@ -112,24 +81,18 @@ func (s *StepInitializeVagrant) Run(_ context.Context, state multistep.StateBag)
return multistep.ActionContinue return multistep.ActionContinue
} }
ui.Say("Initializing Vagrant in build directory...") ui.Say("Creating a Vagrantfile in the build directory...")
vagrantfilePath, err := s.createVagrantfile()
initArgs, err := s.prepInitArgs()
if err != nil { if err != nil {
state.Put("error", err) state.Put("error", err)
return multistep.ActionHalt return multistep.ActionHalt
} }
log.Printf("Created vagrantfile at %s", vagrantfilePath)
os.Chdir(s.OutputDir) os.Chdir(s.OutputDir)
// Call vagrant using prepared arguments
err = driver.Init(initArgs)
if err != nil {
state.Put("error", err)
return multistep.ActionHalt
}
return multistep.ActionContinue return multistep.ActionContinue
} }
func (s *StepInitializeVagrant) Cleanup(state multistep.StateBag) { func (s *StepCreateVagrantfile) Cleanup(state multistep.StateBag) {
} }

View File

@ -0,0 +1,60 @@
package vagrant
import (
"io/ioutil"
"os"
"strings"
"testing"
"github.com/hashicorp/packer/helper/multistep"
)
func TestStepCreateVagrantfile_Impl(t *testing.T) {
var raw interface{}
raw = new(StepCreateVagrantfile)
if _, ok := raw.(multistep.Step); !ok {
t.Fatalf("initialize should be a step")
}
}
func TestCreateFile(t *testing.T) {
testy := StepCreateVagrantfile{
OutputDir: "./",
SourceBox: "bananas",
}
templatePath, err := testy.createVagrantfile()
if err != nil {
t.Fatalf(err.Error())
}
defer os.Remove(templatePath)
contents, err := ioutil.ReadFile(templatePath)
actual := string(contents)
expected := `Vagrant.configure("2") do |config|
config.vm.box = "bananas"
config.vm.synced_folder ".", "/vagrant", disabled: true
end`
if ok := strings.Compare(actual, expected); ok != 0 {
t.Fatalf("EXPECTED: \n%s\n\n RECEIVED: \n%s\n\n", expected, actual)
}
}
func TestCreateFile_customSync(t *testing.T) {
testy := StepCreateVagrantfile{
OutputDir: "./",
SyncedFolder: "myfolder/foldertimes",
}
templatePath, err := testy.createVagrantfile()
if err != nil {
t.Fatalf(err.Error())
}
defer os.Remove(templatePath)
contents, err := ioutil.ReadFile(templatePath)
actual := string(contents)
expected := `Vagrant.configure("2") do |config|
config.vm.box = ""
config.vm.synced_folder "myfolder/foldertimes", "/vagrant"
end`
if ok := strings.Compare(actual, expected); ok != 0 {
t.Fatalf("EXPECTED: \n%s\n\n RECEIVED: \n%s\n\n", expected, actual)
}
}

View File

@ -1,110 +0,0 @@
package vagrant
import (
"io/ioutil"
"os"
"strings"
"testing"
"github.com/hashicorp/packer/helper/multistep"
)
func TestStepInitialize_Impl(t *testing.T) {
var raw interface{}
raw = new(StepInitializeVagrant)
if _, ok := raw.(multistep.Step); !ok {
t.Fatalf("initialize should be a step")
}
}
func TestCreateFile(t *testing.T) {
testy := StepInitializeVagrant{
OutputDir: "./",
SourceBox: "bananas",
}
templatePath, err := testy.getVagrantfileTemplate()
if err != nil {
t.Fatalf(err.Error())
}
contents, err := ioutil.ReadFile(templatePath)
actual := string(contents)
expected := `Vagrant.configure("2") do |config|
config.vm.box = "bananas"
config.vm.synced_folder ".", "/vagrant", disabled: true
end`
if ok := strings.Compare(actual, expected); ok != 0 {
t.Fatalf("EXPECTED: \n%s\n\n RECEIVED: \n%s\n\n", expected, actual)
}
os.Remove(templatePath)
}
func TestCreateFile_customSync(t *testing.T) {
testy := StepInitializeVagrant{
OutputDir: "./",
SyncedFolder: "myfolder/foldertimes",
}
templatePath, err := testy.getVagrantfileTemplate()
defer os.Remove(templatePath)
if err != nil {
t.Fatalf(err.Error())
}
contents, err := ioutil.ReadFile(templatePath)
actual := string(contents)
expected := `Vagrant.configure("2") do |config|
config.vm.box = ""
config.vm.synced_folder "myfolder/foldertimes", "/vagrant"
end`
if ok := strings.Compare(actual, expected); ok != 0 {
t.Fatalf("EXPECTED: \n%s\n\n RECEIVED: \n%s\n\n", expected, actual)
}
}
func TestPrepInitArgs(t *testing.T) {
type testArgs struct {
Step StepInitializeVagrant
Expected []string
}
initTests := []testArgs{
{
Step: StepInitializeVagrant{
SourceBox: "my_source_box.box",
},
Expected: []string{"my_source_box.box", "--template"},
},
{
Step: StepInitializeVagrant{
SourceBox: "my_source_box",
BoxName: "My Box",
},
Expected: []string{"My Box", "my_source_box", "--template"},
},
{
Step: StepInitializeVagrant{
SourceBox: "my_source_box",
BoxName: "My Box",
BoxVersion: "42",
},
Expected: []string{"My Box", "my_source_box", "--box-version", "42", "--template"},
},
{
Step: StepInitializeVagrant{
SourceBox: "my_source_box",
BoxName: "My Box",
Minimal: true,
},
Expected: []string{"My Box", "my_source_box", "-m", "--template"},
},
}
for _, initTest := range initTests {
initArgs, err := initTest.Step.prepInitArgs()
defer os.Remove(initArgs[len(initArgs)-1])
if err != nil {
t.Fatalf(err.Error())
}
for i, val := range initTest.Expected {
if strings.Compare(initArgs[i], val) != 0 {
t.Fatalf("expected %#v but received %#v", initTest.Expected, initArgs[:len(initArgs)-1])
}
}
}
}

View File

@ -58,11 +58,11 @@ Optional:
not recommended since OVA files can be very large and corruption does happen not recommended since OVA files can be very large and corruption does happen
from time to time. from time to time.
- `vagrantfile_template` (string) - a path to an ERB template to use for the - `vagrantfile_template` (string) - a path to a golang template for a
vagrantfile when calling `vagrant init`. See the blog post vagrantfile. Our default template can be found
[here](https://www.hashicorp.com/blog/hashicorp-vagrant-2-0-2#customized-vagrantfile-templates) [here](https://github.com/hashicorp/packer/tree/master/builder/vagrant/step_initialize_vagrant.go#L23-L30). So far the only template variables available to you are {{ .BoxName }} and
for some more details on how this works. Available variables are `box_name`, {{ .SyncedFolder }}, which correspond to the Packer options `box_name` and
`box_url`, and `box_version`. `synced_folder`
- `skip_add` (string) - Don't call "vagrant add" to add the box to your local - `skip_add` (string) - Don't call "vagrant add" to add the box to your local
environment; this is necesasry if you want to launch a box that is already environment; this is necesasry if you want to launch a box that is already
@ -73,10 +73,6 @@ Optional:
- `box_version` (string) - What box version to use when initializing Vagrant. - `box_version` (string) - What box version to use when initializing Vagrant.
- `init_minimal` (bool) - If true, will add the --minimal flag to the Vagrant
init command, creating a minimal vagrantfile instead of one filled with helpful
comments.
- `add_cacert` (string) - Equivalent to setting the - `add_cacert` (string) - Equivalent to setting the
[`--cacert`](https://www.vagrantup.com/docs/cli/box.html#cacert-certfile) [`--cacert`](https://www.vagrantup.com/docs/cli/box.html#cacert-certfile)
option in `vagrant add`; defaults to unset. option in `vagrant add`; defaults to unset.