Replace file shared state by statebag (#9238)

This commit is contained in:
Sylvia Moss 2020-05-19 11:49:48 +02:00 committed by GitHub
parent 170520dcca
commit 1c30a71d09
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
34 changed files with 149 additions and 198 deletions

View File

@ -3,8 +3,6 @@ package dtl
import (
"context"
"github.com/hashicorp/packer/builder/azure/common/constants"
commonhelper "github.com/hashicorp/packer/helper/common"
"github.com/hashicorp/packer/helper/multistep"
"github.com/hashicorp/packer/packer"
)
@ -16,16 +14,9 @@ type StepSaveWinRMPassword struct {
func (s *StepSaveWinRMPassword) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
// store so that we can access this later during provisioning
err := commonhelper.SetSharedState("winrm_password", s.Password, s.BuildName)
if err != nil {
state.Put(constants.Error, err)
return multistep.ActionHalt
}
state.Put("winrm_password", s.Password)
packer.LogSecretFilter.Set(s.Password)
return multistep.ActionContinue
}
func (s *StepSaveWinRMPassword) Cleanup(multistep.StateBag) {
commonhelper.RemoveSharedStateFile("winrm_password", s.BuildName)
}
func (s *StepSaveWinRMPassword) Cleanup(multistep.StateBag) {}

View File

@ -8,7 +8,6 @@ import (
"net"
"strings"
"github.com/hashicorp/packer/common"
"github.com/hashicorp/packer/helper/multistep"
"github.com/hashicorp/packer/packer"
"github.com/hashicorp/packer/template/interpolate"
@ -94,7 +93,7 @@ func (s *stepCreateInstance) Run(ctx context.Context, state multistep.StateBag)
ui.Error(err.Error())
return multistep.ActionHalt
}
common.SetHTTPIP(httpIP)
state.Put("http_ip", httpIP)
s.Ctx.Data = &userDataTemplateData{
httpIP,

View File

@ -5,7 +5,6 @@ import (
"fmt"
"log"
"github.com/hashicorp/packer/common"
"github.com/hashicorp/packer/helper/multistep"
"github.com/hashicorp/packer/packer"
)
@ -32,7 +31,7 @@ func (s *StepRun) Run(ctx context.Context, state multistep.StateBag) multistep.S
}
ui.Say(fmt.Sprintf("Host IP for the HyperV machine: %s", hostIp))
common.SetHTTPIP(hostIp)
state.Put("http_ip", hostIp)
if !s.Headless {
ui.Say("Attempting to connect with vmconnect...")

View File

@ -6,7 +6,6 @@ import (
"strings"
"time"
"github.com/hashicorp/packer/common"
"github.com/hashicorp/packer/common/bootcommand"
"github.com/hashicorp/packer/helper/multistep"
"github.com/hashicorp/packer/packer"
@ -33,7 +32,7 @@ func (s *StepTypeBootCommand) Run(ctx context.Context, state multistep.StateBag)
ui := state.Get("ui").(packer.Ui)
driver := state.Get("driver").(Driver)
vmName := state.Get("vmName").(string)
hostIp := common.GetHTTPIP()
hostIp := state.Get("http_ip").(string)
// Wait the for the vm to boot.
if int64(s.BootWait) > 0 {

View File

@ -611,6 +611,7 @@ func TestUserVariablesInBootCommand(t *testing.T) {
state.Put("driver", driver)
state.Put("hook", hook)
state.Put("http_port", 0)
state.Put("http_ip", "0.0.0.0")
state.Put("ui", ui)
state.Put("vmName", "packer-foo")

View File

@ -512,6 +512,7 @@ func TestUserVariablesInBootCommand(t *testing.T) {
state.Put("driver", driver)
state.Put("hook", hook)
state.Put("http_port", 0)
state.Put("http_ip", "0.0.0.0")
state.Put("ui", ui)
state.Put("vmName", "packer-foo")

View File

@ -5,7 +5,6 @@ import (
"fmt"
"time"
packer_common "github.com/hashicorp/packer/common"
"github.com/hashicorp/packer/common/bootcommand"
"github.com/hashicorp/packer/helper/multistep"
"github.com/hashicorp/packer/packer"
@ -70,7 +69,7 @@ func (s *StepTypeBootCommand) Run(ctx context.Context, state multistep.StateBag)
ui.Say(fmt.Sprintf("Host IP for the Parallels machine: %s", hostIP))
packer_common.SetHTTPIP(hostIP)
state.Put("http_ip", hostIP)
s.Ctx.Data = &bootCommandTemplateData{
hostIP,
httpPort,

View File

@ -9,9 +9,7 @@ import (
"time"
"github.com/Telmate/proxmox-api-go/proxmox"
"github.com/hashicorp/packer/common"
"github.com/hashicorp/packer/common/bootcommand"
commonhelper "github.com/hashicorp/packer/helper/common"
"github.com/hashicorp/packer/helper/multistep"
"github.com/hashicorp/packer/packer"
"github.com/hashicorp/packer/template/interpolate"
@ -63,7 +61,7 @@ func (s *stepTypeBootCommand) Run(ctx context.Context, state multistep.StateBag)
ui.Error(err.Error())
return multistep.ActionHalt
}
common.SetHTTPIP(httpIP)
state.Put("http_ip", httpIP)
s.Ctx.Data = &bootCommandTemplateData{
HTTPIP: httpIP,
HTTPPort: state.Get("http_port").(int),
@ -97,9 +95,7 @@ func (s *stepTypeBootCommand) Run(ctx context.Context, state multistep.StateBag)
return multistep.ActionContinue
}
func (*stepTypeBootCommand) Cleanup(multistep.StateBag) {
commonhelper.RemoveSharedStateFile("ip", "")
}
func (*stepTypeBootCommand) Cleanup(multistep.StateBag) {}
func hostIP() (string, error) {
addrs, err := net.InterfaceAddrs()

View File

@ -3,7 +3,6 @@ package qemu
import (
"context"
"github.com/hashicorp/packer/common"
"github.com/hashicorp/packer/helper/multistep"
)
@ -13,8 +12,7 @@ import (
type stepHTTPIPDiscover struct{}
func (s *stepHTTPIPDiscover) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
hostIP := "10.0.2.2"
common.SetHTTPIP(hostIP)
state.Put("http_ip", "10.0.2.2")
return multistep.ActionContinue
}

View File

@ -4,7 +4,6 @@ import (
"context"
"testing"
"github.com/hashicorp/packer/common"
"github.com/hashicorp/packer/helper/multistep"
)
@ -12,7 +11,6 @@ func TestStepHTTPIPDiscover_Run(t *testing.T) {
state := new(multistep.BasicStateBag)
step := new(stepHTTPIPDiscover)
hostIp := "10.0.2.2"
previousHttpIp := common.GetHTTPIP()
// Test the run
if action := step.Run(context.Background(), state); action != multistep.ActionContinue {
@ -21,10 +19,8 @@ func TestStepHTTPIPDiscover_Run(t *testing.T) {
if _, ok := state.GetOk("error"); ok {
t.Fatal("should NOT have error")
}
httpIp := common.GetHTTPIP()
httpIp := state.Get("http_ip").(string)
if httpIp != hostIp {
t.Fatalf("bad: Http ip is %s but was supposed to be %s", httpIp, hostIp)
}
common.SetHTTPIP(previousHttpIp)
}

View File

@ -7,7 +7,6 @@ import (
"net"
"time"
"github.com/hashicorp/packer/common"
"github.com/hashicorp/packer/common/bootcommand"
"github.com/hashicorp/packer/helper/multistep"
"github.com/hashicorp/packer/packer"
@ -96,7 +95,7 @@ func (s *stepTypeBootCommand) Run(ctx context.Context, state multistep.StateBag)
log.Printf("Connected to VNC desktop: %s", c.DesktopName)
hostIP := common.GetHTTPIP()
hostIP := state.Get("http_ip").(string)
configCtx := config.ctx
configCtx.Data = &bootCommandTemplateData{
hostIP,

View File

@ -2,7 +2,6 @@ package common
import (
"context"
"github.com/hashicorp/packer/common"
"github.com/hashicorp/packer/helper/multistep"
)
@ -12,8 +11,7 @@ import (
type StepHTTPIPDiscover struct{}
func (s *StepHTTPIPDiscover) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
hostIP := "10.0.2.2"
common.SetHTTPIP(hostIP)
state.Put("http_ip", "10.0.2.2")
return multistep.ActionContinue
}

View File

@ -2,7 +2,6 @@ package common
import (
"context"
"github.com/hashicorp/packer/common"
"github.com/hashicorp/packer/helper/multistep"
"testing"
)
@ -11,7 +10,6 @@ func TestStepHTTPIPDiscover_Run(t *testing.T) {
state := new(multistep.BasicStateBag)
step := new(StepHTTPIPDiscover)
hostIp := "10.0.2.2"
previousHttpIp := common.GetHTTPIP()
// Test the run
if action := step.Run(context.Background(), state); action != multistep.ActionContinue {
@ -20,10 +18,8 @@ func TestStepHTTPIPDiscover_Run(t *testing.T) {
if _, ok := state.GetOk("error"); ok {
t.Fatal("should NOT have error")
}
httpIp := common.GetHTTPIP()
httpIp := state.Get("http_ip").(string)
if httpIp != hostIp {
t.Fatalf("bad: Http ip is %s but was supposed to be %s", httpIp, hostIp)
}
common.SetHTTPIP(previousHttpIp)
}

View File

@ -5,7 +5,6 @@ import (
"fmt"
"time"
"github.com/hashicorp/packer/common"
"github.com/hashicorp/packer/common/bootcommand"
"github.com/hashicorp/packer/helper/communicator"
"github.com/hashicorp/packer/helper/multistep"
@ -63,7 +62,7 @@ func (s *StepTypeBootCommand) Run(ctx context.Context, state multistep.StateBag)
pauseFn = state.Get("pauseFn").(multistep.DebugPauseFn)
}
hostIP := common.GetHTTPIP()
hostIP := state.Get("http_ip").(string)
s.Ctx.Data = &bootCommandTemplateData{
HTTPIP: hostIP,
HTTPPort: httpPort,

View File

@ -3,7 +3,6 @@ package common
import (
"context"
"fmt"
"github.com/hashicorp/packer/common"
"strings"
"github.com/hashicorp/packer/helper/multistep"
@ -44,7 +43,7 @@ func (s *StepVBoxManage) Run(ctx context.Context, state multistep.StateBag) mult
ui.Say("Executing custom VBoxManage commands...")
}
hostIP := common.GetHTTPIP()
hostIP := state.Get("http_ip").(string)
httpPort := state.Get("http_port").(int)
s.Ctx.Data = &commandTemplate{

View File

@ -5,7 +5,6 @@ import (
"fmt"
"log"
"github.com/hashicorp/packer/common"
"github.com/hashicorp/packer/helper/multistep"
"github.com/hashicorp/packer/packer"
)
@ -29,7 +28,7 @@ func (s *StepHTTPIPDiscover) Run(ctx context.Context, state multistep.StateBag)
}
log.Printf("Host IP for the VMware machine: %s", hostIP)
common.SetHTTPIP(hostIP)
state.Put("http_ip", hostIP)
return multistep.ActionContinue
}

View File

@ -5,7 +5,6 @@ import (
"errors"
"testing"
"github.com/hashicorp/packer/common"
"github.com/hashicorp/packer/helper/multistep"
)
@ -14,7 +13,6 @@ func TestStepHTTPIPDiscover_Run(t *testing.T) {
step := new(StepHTTPIPDiscover)
driverMock := state.Get("driver").(Driver)
hostIp, _ := driverMock.HostIP(state)
previousHttpIp := common.GetHTTPIP()
// Test the run
if action := step.Run(context.Background(), state); action != multistep.ActionContinue {
@ -23,7 +21,7 @@ func TestStepHTTPIPDiscover_Run(t *testing.T) {
if _, ok := state.GetOk("error"); ok {
t.Fatal("should NOT have error")
}
httpIp := common.GetHTTPIP()
httpIp := state.Get("http_ip").(string)
if httpIp != hostIp {
t.Fatalf("bad: Http ip is %s but was supposed to be %s", httpIp, hostIp)
}
@ -33,6 +31,4 @@ func TestStepHTTPIPDiscover_Run(t *testing.T) {
if action := step.Run(context.Background(), state); action != multistep.ActionHalt {
t.Fatalf("bad action: step was supposed to fail %#v", action)
}
common.SetHTTPIP(previousHttpIp)
}

View File

@ -7,7 +7,6 @@ import (
"net"
"time"
"github.com/hashicorp/packer/common"
"github.com/hashicorp/packer/common/bootcommand"
"github.com/hashicorp/packer/helper/multistep"
"github.com/hashicorp/packer/packer"
@ -98,7 +97,7 @@ func (s *StepTypeBootCommand) Run(ctx context.Context, state multistep.StateBag)
log.Printf("Connected to VNC desktop: %s", c.DesktopName)
hostIP := common.GetHTTPIP()
hostIP := state.Get("http_ip").(string)
s.Ctx.Data = &bootCommandTemplateData{
hostIP,
httpPort,

View File

@ -112,12 +112,7 @@ WAITLOOP:
state.Put("error", err)
return multistep.ActionHalt
}
err = packerCommon.SetHTTPIP(ip)
if err != nil {
state.Put("error", err)
return multistep.ActionHalt
}
state.Put("http_ip", ip)
s.Ctx.Data = &bootCommandTemplateData{
ip,
port,

View File

@ -169,17 +169,17 @@ func createFlattenedEnvVars(config *Config) (string, error) {
envVars["PACKER_BUILDER_TYPE"] = config.PackerBuilderType
// expose ip address variables
httpAddr := common.GetHTTPAddr()
if httpAddr != "" {
envVars["PACKER_HTTP_ADDR"] = httpAddr
httpAddr := config.generatedData["PackerHTTPAddr"]
if httpAddr != nil && httpAddr != common.HttpAddrNotImplemented {
envVars["PACKER_HTTP_ADDR"] = httpAddr.(string)
}
httpIP := common.GetHTTPIP()
if httpIP != "" {
envVars["PACKER_HTTP_IP"] = httpIP
httpIP := config.generatedData["PackerHTTPIP"]
if httpIP != nil && httpIP != common.HttpIPNotImplemented {
envVars["PACKER_HTTP_IP"] = httpIP.(string)
}
httpPort := common.GetHTTPPort()
if httpPort != "" {
envVars["PACKER_HTTP_PORT"] = httpPort
httpPort := config.generatedData["PackerHTTPPort"]
if httpPort != nil && httpPort != common.HttpPortNotImplemented {
envVars["PACKER_HTTP_PORT"] = httpPort.(string)
}
// Split vars into key/value components

View File

@ -7,7 +7,6 @@ import (
"net/http"
"github.com/hashicorp/packer/common/net"
"github.com/hashicorp/packer/helper/common"
"github.com/hashicorp/packer/helper/multistep"
"github.com/hashicorp/packer/packer"
)
@ -63,53 +62,13 @@ func (s *StepHTTPServer) Run(ctx context.Context, state multistep.StateBag) mult
// Save the address into the state so it can be accessed in the future
state.Put("http_port", s.l.Port)
SetHTTPPort(fmt.Sprintf("%d", s.l.Port))
return multistep.ActionContinue
}
func SetHTTPPort(port string) error {
return common.SetSharedState("port", port, "")
}
func SetHTTPIP(ip string) error {
return common.SetSharedState("ip", ip, "")
}
func GetHTTPAddr() string {
ip, err := common.RetrieveSharedState("ip", "")
if err != nil {
return ""
}
port, err := common.RetrieveSharedState("port", "")
if err != nil {
return ""
}
return fmt.Sprintf("%s:%s", ip, port)
}
func GetHTTPPort() string {
port, err := common.RetrieveSharedState("port", "")
if err != nil {
return ""
}
return port
}
func GetHTTPIP() string {
ip, err := common.RetrieveSharedState("ip", "")
if err != nil {
return ""
}
return ip
}
func (s *StepHTTPServer) Cleanup(multistep.StateBag) {
if s.l != nil {
// Close the listener so that the HTTP server stops
s.l.Close()
}
common.RemoveSharedStateFile("port", "")
common.RemoveSharedStateFile("ip", "")
}

View File

@ -5,6 +5,7 @@ import (
"fmt"
"log"
"os"
"strconv"
"time"
"github.com/hashicorp/packer/helper/communicator"
@ -22,6 +23,10 @@ import (
// Produces:
// <nothing>
const HttpIPNotImplemented = "ERR_HTTP_IP_NOT_IMPLEMENTED_BY_BUILDER"
const HttpPortNotImplemented = "ERR_HTTP_PORT_NOT_IMPLEMENTED_BY_BUILDER"
const HttpAddrNotImplemented = "ERR_HTTP_ADDR_NOT_IMPLEMENTED_BY_BUILDER"
func PopulateProvisionHookData(state multistep.StateBag) map[string]interface{} {
hookData := make(map[string]interface{})
@ -31,6 +36,9 @@ func PopulateProvisionHookData(state multistep.StateBag) map[string]interface{}
hookData = hd.(map[string]interface{})
}
// Warn user that the id isn't implemented
hookData["ID"] = "ERR_ID_NOT_IMPLEMENTED_BY_BUILDER"
// instance_id is placed in state by the builders.
// Not yet implemented in Chroot, lxc/lxd, Azure, Qemu.
// Implemented in most others including digitalOcean (droplet id),
@ -39,13 +47,26 @@ func PopulateProvisionHookData(state multistep.StateBag) map[string]interface{}
id, ok := state.GetOk("instance_id")
if ok {
hookData["ID"] = id
} else {
// Warn user that the id isn't implemented
hookData["ID"] = "ERR_ID_NOT_IMPLEMENTED_BY_BUILDER"
}
hookData["PackerRunUUID"] = os.Getenv("PACKER_RUN_UUID")
hookData["PackerHTTPAddr"] = GetHTTPAddr()
// Packer HTTP info
hookData["PackerHTTPIP"] = HttpIPNotImplemented
hookData["PackerHTTPPort"] = HttpPortNotImplemented
hookData["PackerHTTPAddr"] = HttpAddrNotImplemented
httpPort, okPort := state.GetOk("http_port")
if okPort {
hookData["PackerHTTPPort"] = strconv.Itoa(httpPort.(int))
}
httIP, okIP := state.GetOk("http_ip")
if okIP {
hookData["PackerHTTPIP"] = httIP.(string)
}
if okPort && okIP {
hookData["PackerHTTPAddr"] = fmt.Sprintf("%s:%s", hookData["PackerHTTPIP"], hookData["PackerHTTPPort"])
}
// Read communicator data into hook data
comm, ok := state.GetOk("communicator_config")

View File

@ -40,16 +40,16 @@ func TestPopulateProvisionHookData(t *testing.T) {
instanceId := 11111
packerRunUUID := "1fa225b8-27d1-42d1-9117-221772213962"
httpIP := "10.0.2.2"
httpPort := "2222"
httpAddr := fmt.Sprintf("%s:%s", httpIP, httpPort)
httpPort := 2222
httpAddr := fmt.Sprintf("%s:%d", httpIP, httpPort)
state.Put("generated_data", generatedData)
state.Put("instance_id", instanceId)
state.Put("communicator_config", commConfig)
os.Setenv("PACKER_RUN_UUID", packerRunUUID)
SetHTTPIP(httpIP)
SetHTTPPort(httpPort)
state.Put("http_ip", httpIP)
state.Put("http_port", httpPort)
hookData := PopulateProvisionHookData(state)

View File

@ -1,36 +1,6 @@
package common
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
)
// This is used in the BasicPlaceholderData() func in the packer/provisioner.go
// To force users to access generated data via the "generated" func.
const PlaceholderMsg = "To set this dynamically in the Packer template, " +
"you must use the `build` function"
// Used to set variables which we need to access later in the build, where
// state bag and config information won't work
func sharedStateFilename(suffix string, buildName string) string {
uuid := os.Getenv("PACKER_RUN_UUID")
return filepath.Join(os.TempDir(), fmt.Sprintf("packer-%s-%s-%s", uuid, suffix, buildName))
}
func SetSharedState(key string, value string, buildName string) error {
return ioutil.WriteFile(sharedStateFilename(key, buildName), []byte(value), 0600)
}
func RetrieveSharedState(key string, buildName string) (string, error) {
value, err := ioutil.ReadFile(sharedStateFilename(key, buildName))
if err != nil {
return "", err
}
return string(value), nil
}
func RemoveSharedStateFile(key string, buildName string) {
os.Remove(sharedStateFilename(key, buildName))
}

View File

@ -68,6 +68,8 @@ func BasicPlaceholderData() map[string]string {
placeholderData["Password"] = fmt.Sprintf(msg, "Password")
placeholderData["ConnType"] = fmt.Sprintf(msg, "Type")
placeholderData["PackerRunUUID"] = fmt.Sprintf(msg, "PackerRunUUID")
placeholderData["PackerHTTPPort"] = fmt.Sprintf(msg, "PackerHTTPPort")
placeholderData["PackerHTTPIP"] = fmt.Sprintf(msg, "PackerHTTPIP")
placeholderData["PackerHTTPAddr"] = fmt.Sprintf(msg, "PackerHTTPAddr")
placeholderData["SSHPublicKey"] = fmt.Sprintf(msg, "SSHPublicKey")
placeholderData["SSHPrivateKey"] = fmt.Sprintf(msg, "SSHPrivateKey")

View File

@ -75,6 +75,7 @@ type Provisioner struct {
config Config
playbookFiles []string
generatedData map[string]interface{}
}
func (p *Provisioner) ConfigSpec() hcldec.ObjectSpec { return p.config.FlatMapstructure().HCL2Spec() }
@ -191,8 +192,9 @@ func (p *Provisioner) Prepare(raws ...interface{}) error {
return nil
}
func (p *Provisioner) Provision(ctx context.Context, ui packer.Ui, comm packer.Communicator, _ map[string]interface{}) error {
func (p *Provisioner) Provision(ctx context.Context, ui packer.Ui, comm packer.Communicator, generatedData map[string]interface{}) error {
ui.Say("Provisioning with Ansible...")
p.generatedData = generatedData
if len(p.config.PlaybookDir) > 0 {
ui.Message("Uploading Playbook directory to Ansible staging directory...")
@ -378,7 +380,7 @@ func (p *Provisioner) executeAnsible(ui packer.Ui, comm packer.Communicator) err
inventory := filepath.ToSlash(filepath.Join(p.config.StagingDir, filepath.Base(p.config.InventoryFile)))
extraArgs := fmt.Sprintf(" --extra-vars \"packer_build_name=%s packer_builder_type=%s packer_http_addr=%s -o IdentitiesOnly=yes\" ",
p.config.PackerBuildName, p.config.PackerBuilderType, common.GetHTTPAddr())
p.config.PackerBuildName, p.config.PackerBuilderType, p.generatedData["PackerHTTPAddr"])
if len(p.config.ExtraArguments) > 0 {
extraArgs = extraArgs + strings.Join(p.config.ExtraArguments, " ")
}

View File

@ -592,7 +592,7 @@ func (p *Provisioner) createCmdArgs(httpAddr, inventory, playbook, privKeyFile s
func (p *Provisioner) executeAnsible(ui packer.Ui, comm packer.Communicator, privKeyFile string) error {
playbook, _ := filepath.Abs(p.config.PlaybookFile)
inventory := p.config.InventoryFile
httpAddr := common.GetHTTPAddr()
httpAddr := p.generatedData["PackerHTTPAddr"].(string)
// Fetch external dependencies
if len(p.config.GalaxyFile) > 0 {

View File

@ -404,17 +404,17 @@ func (p *Provisioner) createFlattenedEnvVars(elevated bool) (flattened string) {
envVars["PACKER_BUILDER_TYPE"] = p.config.PackerBuilderType
// expose ip address variables
httpAddr := common.GetHTTPAddr()
if httpAddr != "" {
envVars["PACKER_HTTP_ADDR"] = httpAddr
httpAddr := p.generatedData["PackerHTTPAddr"]
if httpAddr != nil && httpAddr != common.HttpAddrNotImplemented {
envVars["PACKER_HTTP_ADDR"] = httpAddr.(string)
}
httpIP := common.GetHTTPIP()
if httpIP != "" {
envVars["PACKER_HTTP_IP"] = httpIP
httpIP := p.generatedData["PackerHTTPIP"]
if httpIP != nil && httpIP != common.HttpIPNotImplemented {
envVars["PACKER_HTTP_IP"] = httpIP.(string)
}
httpPort := common.GetHTTPPort()
if httpPort != "" {
envVars["PACKER_HTTP_PORT"] = httpPort
httpPort := p.generatedData["PackerHTTPPort"]
if httpPort != nil && httpPort != common.HttpPortNotImplemented {
envVars["PACKER_HTTP_PORT"] = httpPort.(string)
}
// interpolate environment variables

View File

@ -11,6 +11,7 @@ import (
"testing"
"time"
"github.com/hashicorp/packer/common"
"github.com/hashicorp/packer/packer"
"github.com/stretchr/testify/assert"
)
@ -373,7 +374,7 @@ func TestProvisionerProvision_ValidExitCodes(t *testing.T) {
comm := new(packer.MockCommunicator)
comm.StartExitStatus = 200
p.Prepare(config)
err := p.Provision(context.Background(), ui, comm, make(map[string]interface{}))
err := p.Provision(context.Background(), ui, comm, generatedData())
if err != nil {
t.Fatal("should not have error")
}
@ -396,7 +397,7 @@ func TestProvisionerProvision_InvalidExitCodes(t *testing.T) {
comm := new(packer.MockCommunicator)
comm.StartExitStatus = 201 // Invalid!
p.Prepare(config)
err := p.Provision(context.Background(), ui, comm, make(map[string]interface{}))
err := p.Provision(context.Background(), ui, comm, generatedData())
if err == nil {
t.Fatal("should have error")
}
@ -418,7 +419,8 @@ func TestProvisionerProvision_Inline(t *testing.T) {
p.config.PackerBuilderType = "iso"
comm := new(packer.MockCommunicator)
_ = p.Prepare(config)
err := p.Provision(context.Background(), ui, comm, make(map[string]interface{}))
err := p.Provision(context.Background(), ui, comm, generatedData())
if err != nil {
t.Fatal("should not have error")
}
@ -438,7 +440,7 @@ func TestProvisionerProvision_Inline(t *testing.T) {
config["remote_path"] = "c:/Windows/Temp/inlineScript.ps1"
p.Prepare(config)
err = p.Provision(context.Background(), ui, comm, make(map[string]interface{}))
err = p.Provision(context.Background(), ui, comm, generatedData())
if err != nil {
t.Fatal("should not have error")
}
@ -468,7 +470,7 @@ func TestProvisionerProvision_Scripts(t *testing.T) {
p := new(Provisioner)
comm := new(packer.MockCommunicator)
p.Prepare(config)
err := p.Provision(context.Background(), ui, comm, make(map[string]interface{}))
err := p.Provision(context.Background(), ui, comm, generatedData())
if err != nil {
t.Fatal("should not have error")
}
@ -505,7 +507,7 @@ func TestProvisionerProvision_ScriptsWithEnvVars(t *testing.T) {
p := new(Provisioner)
comm := new(packer.MockCommunicator)
p.Prepare(config)
err := p.Provision(context.Background(), ui, comm, make(map[string]interface{}))
err := p.Provision(context.Background(), ui, comm, generatedData())
if err != nil {
t.Fatal("should not have error")
}
@ -554,7 +556,7 @@ func TestProvisionerProvision_SkipClean(t *testing.T) {
if err := p.Prepare(config); err != nil {
t.Fatalf("failed to prepare config when SkipClean is %t: %s", tc.SkipClean, err)
}
err := p.Provision(context.Background(), ui, comm, make(map[string]interface{}))
err := p.Provision(context.Background(), ui, comm, generatedData())
if err != nil {
t.Fatal("should not have error")
}
@ -578,7 +580,7 @@ func TestProvisionerProvision_UploadFails(t *testing.T) {
comm := new(packer.ScriptUploadErrorMockCommunicator)
p.Prepare(config)
p.config.StartRetryTimeout = 1 * time.Second
err := p.Provision(context.Background(), ui, comm, make(map[string]interface{}))
err := p.Provision(context.Background(), ui, comm, generatedData())
if !strings.Contains(err.Error(), packer.ScriptUploadErrorMockCommunicatorError.Error()) {
t.Fatalf("expected Provision() error %q to contain %q",
err.Error(),
@ -616,6 +618,7 @@ func TestProvisioner_createFlattenedElevatedEnvVars_windows(t *testing.T) {
}
p := new(Provisioner)
p.generatedData = generatedData()
p.Prepare(config)
// Defaults provided by Packer
@ -767,6 +770,7 @@ func TestProvisioner_createFlattenedEnvVars_windows(t *testing.T) {
}
p := new(Provisioner)
p.generatedData = generatedData()
p.Prepare(config)
// Defaults provided by Packer
@ -849,3 +853,11 @@ func testConfigWithSkipClean() map[string]interface{} {
"skip_clean": true,
}
}
func generatedData() map[string]interface{} {
return map[string]interface{}{
"PackerHTTPAddr": common.HttpAddrNotImplemented,
"PackerHTTPIP": common.HttpIPNotImplemented,
"PackerHTTPPort": common.HttpPortNotImplemented,
}
}

View File

@ -67,7 +67,8 @@ type Config struct {
}
type Provisioner struct {
config Config
config Config
generatedData map[string]interface{}
}
func (p *Provisioner) ConfigSpec() hcldec.ObjectSpec { return p.config.FlatMapstructure().HCL2Spec() }
@ -179,6 +180,7 @@ func (p *Provisioner) Provision(ctx context.Context, ui packer.Ui, comm packer.C
if generatedData == nil {
generatedData = make(map[string]interface{})
}
p.generatedData = generatedData
scripts := make([]string, len(p.config.Scripts))
copy(scripts, p.config.Scripts)
@ -414,17 +416,17 @@ func (p *Provisioner) escapeEnvVars() ([]string, map[string]string) {
envVars["PACKER_BUILDER_TYPE"] = p.config.PackerBuilderType
// expose ip address variables
httpAddr := common.GetHTTPAddr()
if httpAddr != "" {
envVars["PACKER_HTTP_ADDR"] = httpAddr
httpAddr := p.generatedData["PackerHTTPAddr"]
if httpAddr != nil && httpAddr != common.HttpAddrNotImplemented {
envVars["PACKER_HTTP_ADDR"] = httpAddr.(string)
}
httpIP := common.GetHTTPIP()
if httpIP != "" {
envVars["PACKER_HTTP_IP"] = httpIP
httpIP := p.generatedData["PackerHTTPIP"]
if httpIP != nil && httpIP != common.HttpIPNotImplemented {
envVars["PACKER_HTTP_IP"] = httpIP.(string)
}
httpPort := common.GetHTTPPort()
if httpPort != "" {
envVars["PACKER_HTTP_PORT"] = httpPort
httpPort := p.generatedData["PackerHTTPPort"]
if httpPort != nil && httpPort != common.HttpPortNotImplemented {
envVars["PACKER_HTTP_PORT"] = httpPort.(string)
}
// Split vars into key/value components

View File

@ -7,6 +7,7 @@ import (
"strings"
"testing"
"github.com/hashicorp/packer/common"
"github.com/hashicorp/packer/packer"
)
@ -271,6 +272,7 @@ func TestProvisioner_createFlattenedEnvVars(t *testing.T) {
}
p := new(Provisioner)
p.generatedData = generatedData()
p.Prepare(config)
// Defaults provided by Packer
@ -308,7 +310,7 @@ func TestProvisioner_createFlattenedEnvVars_withEnvVarFormat(t *testing.T) {
}
p := new(Provisioner)
p.generatedData = generatedData()
p.config.EnvVarFormat = "%s=%s "
p.Prepare(config)
@ -365,6 +367,7 @@ export PACKER_BUILD_NAME='vmware'
}
p := new(Provisioner)
p.generatedData = generatedData()
p.config.UseEnvVarFile = true
p.Prepare(config)
@ -411,7 +414,7 @@ PACKER_BUILD_NAME=vmware
}
p := new(Provisioner)
p.generatedData = generatedData()
p.config.UseEnvVarFile = true
//User provided env_var_format without export prefix
p.config.EnvVarFormat = "%s=%s\n"
@ -557,3 +560,11 @@ func TestProvisionerRemotePathDefaultsSuccessfully(t *testing.T) {
t.Fatalf("remote path does not match the expected default regex: %q", p.config.RemotePath)
}
}
func generatedData() map[string]interface{} {
return map[string]interface{}{
"PackerHTTPAddr": common.HttpAddrNotImplemented,
"PackerHTTPIP": common.HttpIPNotImplemented,
"PackerHTTPPort": common.HttpPortNotImplemented,
}
}

View File

@ -42,7 +42,8 @@ type Config struct {
}
type Provisioner struct {
config Config
config Config
generatedData map[string]interface{}
}
type ExecuteCommandTemplate struct {
@ -157,10 +158,11 @@ func extractScript(p *Provisioner) (string, error) {
return temp.Name(), nil
}
func (p *Provisioner) Provision(ctx context.Context, ui packer.Ui, comm packer.Communicator, _ map[string]interface{}) error {
func (p *Provisioner) Provision(ctx context.Context, ui packer.Ui, comm packer.Communicator, generatedData map[string]interface{}) error {
ui.Say("Provisioning with windows-shell...")
scripts := make([]string, len(p.config.Scripts))
copy(scripts, p.config.Scripts)
p.generatedData = generatedData
if p.config.Inline != nil {
temp, err := extractScript(p)
@ -237,17 +239,17 @@ func (p *Provisioner) createFlattenedEnvVars() (flattened string) {
envVars["PACKER_BUILDER_TYPE"] = p.config.PackerBuilderType
// expose ip address variables
httpAddr := common.GetHTTPAddr()
if httpAddr != "" {
envVars["PACKER_HTTP_ADDR"] = httpAddr
httpAddr := p.generatedData["PackerHTTPAddr"]
if httpAddr != nil && httpAddr != common.HttpAddrNotImplemented {
envVars["PACKER_HTTP_ADDR"] = httpAddr.(string)
}
httpIP := common.GetHTTPIP()
if httpIP != "" {
envVars["PACKER_HTTP_IP"] = httpIP
httpIP := p.generatedData["PackerHTTPIP"]
if httpIP != nil && httpIP != common.HttpIPNotImplemented {
envVars["PACKER_HTTP_IP"] = httpIP.(string)
}
httpPort := common.GetHTTPPort()
if httpPort != "" {
envVars["PACKER_HTTP_PORT"] = httpPort
httpPort := p.generatedData["PackerHTTPPort"]
if httpPort != nil && httpPort != common.HttpPortNotImplemented {
envVars["PACKER_HTTP_PORT"] = httpPort.(string)
}
// Split vars into key/value components

View File

@ -9,6 +9,7 @@ import (
"strings"
"testing"
"github.com/hashicorp/packer/common"
"github.com/hashicorp/packer/packer"
)
@ -287,7 +288,8 @@ func TestProvisionerProvision_Inline(t *testing.T) {
p.config.PackerBuilderType = "iso"
comm := new(packer.MockCommunicator)
p.Prepare(config)
err := p.Provision(context.Background(), ui, comm, make(map[string]interface{}))
err := p.Provision(context.Background(), ui, comm, generatedData())
if err != nil {
t.Fatal("should not have error")
}
@ -306,7 +308,7 @@ func TestProvisionerProvision_Inline(t *testing.T) {
config["remote_path"] = "c:/Windows/Temp/inlineScript.bat"
p.Prepare(config)
err = p.Provision(context.Background(), ui, comm, make(map[string]interface{}))
err = p.Provision(context.Background(), ui, comm, generatedData())
if err != nil {
t.Fatal("should not have error")
}
@ -337,7 +339,7 @@ func TestProvisionerProvision_Scripts(t *testing.T) {
p := new(Provisioner)
comm := new(packer.MockCommunicator)
p.Prepare(config)
err = p.Provision(context.Background(), ui, comm, make(map[string]interface{}))
err = p.Provision(context.Background(), ui, comm, generatedData())
if err != nil {
t.Fatal("should not have error")
}
@ -376,7 +378,7 @@ func TestProvisionerProvision_ScriptsWithEnvVars(t *testing.T) {
p := new(Provisioner)
comm := new(packer.MockCommunicator)
p.Prepare(config)
err = p.Provision(context.Background(), ui, comm, make(map[string]interface{}))
err = p.Provision(context.Background(), ui, comm, generatedData())
if err != nil {
t.Fatal("should not have error")
}
@ -409,6 +411,7 @@ func TestProvisioner_createFlattenedEnvVars_windows(t *testing.T) {
}
p := new(Provisioner)
p.generatedData = generatedData()
p.Prepare(config)
// Defaults provided by Packer
@ -423,7 +426,15 @@ func TestProvisioner_createFlattenedEnvVars_windows(t *testing.T) {
}
}
}
func TestCancel(t *testing.T) {
// Don't actually call Cancel() as it performs an os.Exit(0)
// which kills the 'go test' tool
}
func generatedData() map[string]interface{} {
return map[string]interface{}{
"PackerHTTPAddr": common.HttpAddrNotImplemented,
"PackerHTTPIP": common.HttpIPNotImplemented,
"PackerHTTPPort": common.HttpPortNotImplemented,
}
}

View File

@ -84,7 +84,7 @@ Here is a full list of the available functions for reference.
- **PackerRunUUID**: Current build's unique id. Can be used to specify build artifacts.
- **PackerHTTPAddr**: HTTP address of the file server Packer creates to serve items in the "http" dir to the vm, displayed in the format `IP:PORT`.
- **PackerHTTPIP**, **PackerHTTPPort**, and **PackerHTTPAddr**: HTTP IP, port, and address of the file server Packer creates to serve items in the "http" dir to the vm. The HTTP address is displayed in the format `IP:PORT`.
- **SSHPublicKey** and **SSHPrivateKey**: The public and private key that Packer uses to connect to the instance.
These are unique to the SSH communicator and are unset when using other communicators.