當前位置: 首頁>>代碼示例>>Golang>>正文


Golang uuid.TimeOrderedUUID函數代碼示例

本文整理匯總了Golang中github.com/mitchellh/packer/common/uuid.TimeOrderedUUID函數的典型用法代碼示例。如果您正苦於以下問題:Golang TimeOrderedUUID函數的具體用法?Golang TimeOrderedUUID怎麽用?Golang TimeOrderedUUID使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了TimeOrderedUUID函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: generateElevatedRunner

func (p *Provisioner) generateElevatedRunner(command string) (uploadedPath string, err error) {
	log.Printf("Building elevated command wrapper for: %s", command)

	// generate command
	var buffer bytes.Buffer

	base64EncodedCommand, err := powershellEncode(command)
	if err != nil {
		return "", fmt.Errorf("Error encoding command: %s", err)
	}

	err = elevatedTemplate.Execute(&buffer, elevatedOptions{
		User:            p.config.ElevatedUser,
		Password:        p.config.ElevatedPassword,
		TaskDescription: "Packer elevated task",
		TaskName:        fmt.Sprintf("packer-%s", uuid.TimeOrderedUUID()),
		EncodedCommand:  base64EncodedCommand,
	})

	if err != nil {
		fmt.Printf("Error creating elevated template: %s", err)
		return "", err
	}

	tmpFile, err := ioutil.TempFile(os.TempDir(), "packer-elevated-shell.ps1")
	writer := bufio.NewWriter(tmpFile)
	if _, err := writer.WriteString(string(buffer.Bytes())); err != nil {
		return "", fmt.Errorf("Error preparing elevated shell script: %s", err)
	}

	if err := writer.Flush(); err != nil {
		return "", fmt.Errorf("Error preparing elevated shell script: %s", err)
	}
	tmpFile.Close()
	f, err := os.Open(tmpFile.Name())
	if err != nil {
		return "", fmt.Errorf("Error opening temporary elevated shell script: %s", err)
	}
	defer f.Close()

	uuid := uuid.TimeOrderedUUID()
	path := fmt.Sprintf(`${env:TEMP}\packer-elevated-shell-%s.ps1`, uuid)
	log.Printf("Uploading elevated shell wrapper for command [%s] to [%s] from [%s]", command, path, tmpFile.Name())
	err = p.communicator.Upload(path, f, nil)
	if err != nil {
		return "", fmt.Errorf("Error preparing elevated shell script: %s", err)
	}

	// CMD formatted Path required for this op
	path = fmt.Sprintf("%s-%s.ps1", "%TEMP%\\packer-elevated-shell", uuid)
	return path, err
}
開發者ID:arizvisa,項目名稱:packer,代碼行數:52,代碼來源:provisioner.go

示例2: Provision

func (p *Provisioner) Provision(ui packer.Ui, comm packer.Communicator) error {

	nodeName := p.config.NodeName
	if nodeName == "" {
		nodeName = fmt.Sprintf("packer-%s", uuid.TimeOrderedUUID())
	}
	remoteValidationKeyPath := ""
	serverUrl := p.config.ServerUrl

	if !p.config.SkipInstall {
		if err := p.installChef(ui, comm); err != nil {
			return fmt.Errorf("Error installing Chef: %s", err)
		}
	}

	if err := p.createDir(ui, comm, p.config.StagingDir); err != nil {
		return fmt.Errorf("Error creating staging directory: %s", err)
	}

	if p.config.ValidationKeyPath != "" {
		remoteValidationKeyPath = fmt.Sprintf("%s/validation.pem", p.config.StagingDir)
		if err := p.copyValidationKey(ui, comm, remoteValidationKeyPath); err != nil {
			return fmt.Errorf("Error copying validation key: %s", err)
		}
	}

	configPath, err := p.createConfig(
		ui, comm, nodeName, serverUrl, remoteValidationKeyPath, p.config.ValidationClientName, p.config.ChefEnvironment, p.config.SslVerifyMode)
	if err != nil {
		return fmt.Errorf("Error creating Chef config file: %s", err)
	}

	jsonPath, err := p.createJson(ui, comm)
	if err != nil {
		return fmt.Errorf("Error creating JSON attributes: %s", err)
	}

	err = p.executeChef(ui, comm, configPath, jsonPath)
	if !p.config.SkipCleanNode {
		if err2 := p.cleanNode(ui, comm, nodeName); err2 != nil {
			return fmt.Errorf("Error cleaning up chef node: %s", err2)
		}
	}

	if !p.config.SkipCleanClient {
		if err2 := p.cleanClient(ui, comm, nodeName); err2 != nil {
			return fmt.Errorf("Error cleaning up chef client: %s", err2)
		}
	}

	if err != nil {
		return fmt.Errorf("Error executing Chef: %s", err)
	}

	if err := p.removeDir(ui, comm, p.config.StagingDir); err != nil {
		return fmt.Errorf("Error removing /etc/chef directory: %s", err)
	}

	return nil
}
開發者ID:dkhenry,項目名稱:packer,代碼行數:60,代碼來源:provisioner.go

示例3: doCopy

func doCopy(client *winrm.Client, config *Config, in io.Reader, toPath string) error {
	tempFile := fmt.Sprintf("winrmcp-%s.tmp", uuid.TimeOrderedUUID())
	tempPath := "$env:TEMP\\" + tempFile

	if os.Getenv("WINRMCP_DEBUG") != "" {
		log.Printf("Copying file to %s\n", tempPath)
	}

	err := uploadContent(client, config.MaxOperationsPerShell, "%TEMP%\\"+tempFile, in)
	if err != nil {
		return errors.New(fmt.Sprintf("Error uploading file to %s: %v", tempPath, err))
	}

	if os.Getenv("WINRMCP_DEBUG") != "" {
		log.Printf("Moving file from %s to %s", tempPath, toPath)
	}

	err = restoreContent(client, tempPath, toPath)
	if err != nil {
		return errors.New(fmt.Sprintf("Error restoring file from %s to %s: %v", tempPath, toPath, err))
	}

	if os.Getenv("WINRMCP_DEBUG") != "" {
		log.Printf("Removing temporary file %s", tempPath)
	}

	err = cleanupContent(client, tempPath)
	if err != nil {
		return errors.New(fmt.Sprintf("Error removing temporary file %s: %v", tempPath, err))
	}

	return nil
}
開發者ID:markpeek,項目名稱:winrmcp,代碼行數:33,代碼來源:cp.go

示例4: createCommandText

func createCommandText() (command string, err error) {

	// doesn't take well to the flattened env vars
	cmd = fmt.Sprintf(`$env:FOO="bar"; %s`, cmd)

	log.Printf("Building elevated command for: %s", cmd)

	// generate command
	var buffer bytes.Buffer
	err = elevatedTemplate.Execute(&buffer, elevatedOptions{
		User:            user,
		Password:        pass,
		TaskDescription: "Packer elevated task",
		TaskName:        fmt.Sprintf("packer-%s", uuid.TimeOrderedUUID()),
		EncodedCommand:  powershellEncode([]byte(cmd + "; exit $LASTEXITCODE")),
	})

	if err != nil {
		return "", err
	}

	log.Printf("ELEVATED SCRIPT: %s\n\n", string(buffer.Bytes()))
	return string(buffer.Bytes()), nil

}
開發者ID:scopely,項目名稱:winrm-powershell,代碼行數:25,代碼來源:winrm-powershell.go

示例5: Run

func (s *stepCreateDroplet) Run(state multistep.StateBag) multistep.StepAction {
	client := state.Get("client").(*DigitalOceanClient)
	ui := state.Get("ui").(packer.Ui)
	c := state.Get("config").(config)
	sshKeyId := state.Get("ssh_key_id").(uint)

	ui.Say("Creating droplet...")

	// Some random droplet name as it's temporary
	name := fmt.Sprintf("packer-%s", uuid.TimeOrderedUUID())

	// Create the droplet based on configuration
	dropletId, err := client.CreateDroplet(name, c.SizeID, c.ImageID, c.RegionID, sshKeyId)
	if err != nil {
		err := fmt.Errorf("Error creating droplet: %s", err)
		state.Put("error", err)
		ui.Error(err.Error())
		return multistep.ActionHalt
	}

	// We use this in cleanup
	s.dropletId = dropletId

	// Store the droplet id for later
	state.Put("droplet_id", dropletId)

	return multistep.ActionContinue
}
開發者ID:reoring,項目名稱:packer,代碼行數:28,代碼來源:step_create_droplet.go

示例6: Prepare

func (c *RunConfig) Prepare(ctx *interpolate.Context) []error {
	// If we are not given an explicit ssh_keypair_name,
	// then create a temporary one, but only if the
	// temporary_key_pair_name has not been provided.
	if c.SSHKeyPairName == "" {
		if c.TemporaryKeyPairName == "" {
			c.TemporaryKeyPairName = fmt.Sprintf(
				"packer_%s", uuid.TimeOrderedUUID())
		}
	}

	if c.WindowsPasswordTimeout == 0 {
		c.WindowsPasswordTimeout = 10 * time.Minute
	}

	// Validation
	errs := c.Comm.Prepare(ctx)
	if c.SourceAmi == "" {
		errs = append(errs, errors.New("A source_ami must be specified"))
	}

	if c.InstanceType == "" {
		errs = append(errs, errors.New("An instance_type must be specified"))
	}

	if c.SpotPrice == "auto" {
		if c.SpotPriceAutoProduct == "" {
			errs = append(errs, errors.New(
				"spot_price_auto_product must be specified when spot_price is auto"))
		}
	}

	if c.UserData != "" && c.UserDataFile != "" {
		errs = append(errs, fmt.Errorf("Only one of user_data or user_data_file can be specified."))
	} else if c.UserDataFile != "" {
		if _, err := os.Stat(c.UserDataFile); err != nil {
			errs = append(errs, fmt.Errorf("user_data_file not found: %s", c.UserDataFile))
		}
	}

	if c.SecurityGroupId != "" {
		if len(c.SecurityGroupIds) > 0 {
			errs = append(errs, fmt.Errorf("Only one of security_group_id or security_group_ids can be specified."))
		} else {
			c.SecurityGroupIds = []string{c.SecurityGroupId}
			c.SecurityGroupId = ""
		}
	}

	if c.InstanceInitiatedShutdownBehavior == "" {
		c.InstanceInitiatedShutdownBehavior = "stop"
	} else if !reShutdownBehavior.MatchString(c.InstanceInitiatedShutdownBehavior) {
		errs = append(errs, fmt.Errorf("shutdown_behaviour only accepts 'stop' or 'terminate' values."))
	}

	return errs
}
開發者ID:threatstream,項目名稱:packer,代碼行數:57,代碼來源:run_config.go

示例7: Run

func (s *StepSecurityGroup) Run(state multistep.StateBag) multistep.StepAction {
	ec2conn := state.Get("ec2").(*ec2.EC2)
	ui := state.Get("ui").(packer.Ui)

	if len(s.SecurityGroupIds) > 0 {
		log.Printf("Using specified security groups: %v", s.SecurityGroupIds)
		state.Put("securityGroupIds", s.SecurityGroupIds)
		return multistep.ActionContinue
	}

	if s.SSHPort == 0 {
		panic("SSHPort must be set to a non-zero value.")
	}

	// Create the group
	ui.Say("Creating temporary security group for this instance...")
	groupName := fmt.Sprintf("packer %s", uuid.TimeOrderedUUID())
	log.Printf("Temporary group name: %s", groupName)
	group := ec2.SecurityGroup{
		Name:        groupName,
		Description: "Temporary group for Packer",
		VpcId:       s.VpcId,
	}
	groupResp, err := ec2conn.CreateSecurityGroup(group)
	if err != nil {
		ui.Error(err.Error())
		return multistep.ActionHalt
	}

	// Set the group ID so we can delete it later
	s.createdGroupId = groupResp.Id

	// Authorize the SSH access
	perms := []ec2.IPPerm{
		ec2.IPPerm{
			Protocol:  "tcp",
			FromPort:  s.SSHPort,
			ToPort:    s.SSHPort,
			SourceIPs: []string{"0.0.0.0/0"},
		},
	}

	ui.Say("Authorizing SSH access on the temporary security group...")
	if _, err := ec2conn.AuthorizeSecurityGroup(groupResp.SecurityGroup, perms); err != nil {
		err := fmt.Errorf("Error creating temporary security group: %s", err)
		state.Put("error", err)
		ui.Error(err.Error())
		return multistep.ActionHalt
	}

	// Set some state data for use in future steps
	state.Put("securityGroupIds", []string{s.createdGroupId})

	return multistep.ActionContinue
}
開發者ID:EdevMosaic,項目名稱:packer,代碼行數:55,代碼來源:step_security_group.go

示例8: Run

func (s *StepKeyPair) Run(state multistep.StateBag) multistep.StepAction {
	csp := state.Get("csp").(gophercloud.CloudServersProvider)
	ui := state.Get("ui").(packer.Ui)

	ui.Say("Creating temporary keypair for this instance...")
	keyName := fmt.Sprintf("packer %s", uuid.TimeOrderedUUID())
	log.Printf("temporary keypair name: %s", keyName)
	keyResp, err := csp.CreateKeyPair(gophercloud.NewKeyPair{Name: keyName})
	if err != nil {
		state.Put("error", fmt.Errorf("Error creating temporary keypair: %s", err))
		return multistep.ActionHalt
	}
	if keyResp.PrivateKey == "" {
		state.Put("error", fmt.Errorf("The temporary keypair returned was blank"))
		return multistep.ActionHalt
	}

	// If we're in debug mode, output the private key to the working
	// directory.
	if s.Debug {
		ui.Message(fmt.Sprintf("Saving key for debug purposes: %s", s.DebugKeyPath))
		f, err := os.Create(s.DebugKeyPath)
		if err != nil {
			state.Put("error", fmt.Errorf("Error saving debug key: %s", err))
			return multistep.ActionHalt
		}
		defer f.Close()

		// Write the key out
		if _, err := f.Write([]byte(keyResp.PrivateKey)); err != nil {
			state.Put("error", fmt.Errorf("Error saving debug key: %s", err))
			return multistep.ActionHalt
		}

		// Chmod it so that it is SSH ready
		if runtime.GOOS != "windows" {
			if err := f.Chmod(0600); err != nil {
				state.Put("error", fmt.Errorf("Error setting permissions of debug key: %s", err))
				return multistep.ActionHalt
			}
		}
	}

	// Set the keyname so we know to delete it later
	s.keyName = keyName

	// Set some state data for use in future steps
	state.Put("keyPair", keyName)
	state.Put("privateKey", keyResp.PrivateKey)

	return multistep.ActionContinue
}
開發者ID:JNPRAutomate,項目名稱:packer,代碼行數:52,代碼來源:step_key_pair.go

示例9: Run

// Run executes the Packer build step that creates a GCE instance.
func (s *StepCreateInstance) Run(state multistep.StateBag) multistep.StepAction {
	config := state.Get("config").(*Config)
	driver := state.Get("driver").(Driver)
	sshPublicKey := state.Get("ssh_public_key").(string)
	ui := state.Get("ui").(packer.Ui)

	ui.Say("Creating instance...")
	name := fmt.Sprintf("packer-%s", uuid.TimeOrderedUUID())

	errCh, err := driver.RunInstance(&InstanceConfig{
		Description: "New instance created by Packer",
		Image:       config.SourceImage,
		MachineType: config.MachineType,
		Metadata: map[string]string{
			"sshKeys": fmt.Sprintf("%s:%s", config.SSHUsername, sshPublicKey),
		},
		Name:    name,
		Network: config.Network,
		Tags:    config.Tags,
		Zone:    config.Zone,
	})

	if err == nil {
		ui.Message("Waiting for creation operation to complete...")
		select {
		case err = <-errCh:
		case <-time.After(config.stateTimeout):
			err = errors.New("time out while waiting for instance to create")
		}
	}

	if err != nil {
		err := fmt.Errorf("Error creating instance: %s", err)
		state.Put("error", err)
		ui.Error(err.Error())
		return multistep.ActionHalt
	}

	ui.Message("Instance has been created!")

	if s.Debug {
		if name != "" {
			ui.Message(fmt.Sprintf("Instance: %s started in %s", name, config.Zone))
		}
	}

	// Things succeeded, store the name so we can remove it later
	state.Put("instance_name", name)
	s.instanceName = name

	return multistep.ActionContinue
}
開發者ID:johnbellone,項目名稱:packer,代碼行數:53,代碼來源:step_create_instance.go

示例10: Run

func (s *StepCreateExternalSwitch) Run(state multistep.StateBag) multistep.StepAction {
	driver := state.Get("driver").(Driver)
	ui := state.Get("ui").(packer.Ui)

	vmName := state.Get("vmName").(string)
	errorMsg := "Error createing external switch: %s"
	var err error

	ui.Say("Creating external switch...")

	packerExternalSwitchName := "paes_" + uuid.TimeOrderedUUID()

	err = driver.CreateExternalVirtualSwitch(vmName, packerExternalSwitchName)
	if err != nil {
		err := fmt.Errorf("Error creating switch: %s", err)
		state.Put(errorMsg, err)
		ui.Error(err.Error())
		s.SwitchName = ""
		return multistep.ActionHalt
	}

	switchName, err := driver.GetVirtualMachineSwitchName(vmName)
	if err != nil {
		err := fmt.Errorf(errorMsg, err)
		state.Put("error", err)
		ui.Error(err.Error())
		return multistep.ActionHalt
	}

	if len(switchName) == 0 {
		err := fmt.Errorf(errorMsg, err)
		state.Put("error", "Can't get the VM switch name")
		ui.Error(err.Error())
		return multistep.ActionHalt
	}

	ui.Say("External switch name is: '" + switchName + "'")

	if switchName != packerExternalSwitchName {
		s.SwitchName = ""
	} else {
		s.SwitchName = packerExternalSwitchName
		s.oldSwitchName = state.Get("SwitchName").(string)
	}

	// Set the final name in the state bag so others can use it
	state.Put("SwitchName", switchName)

	return multistep.ActionContinue
}
開發者ID:arizvisa,項目名稱:packer,代碼行數:50,代碼來源:step_create_external_switch.go

示例11: Prepare

func (c *RunConfig) Prepare(ctx *interpolate.Context) []error {
	// if we are not given an explicit keypairname, create a temporary one
	if c.SSHKeyPairName == "" {
		c.TemporaryKeyPairName = fmt.Sprintf(
			"packer %s", uuid.TimeOrderedUUID())
	}

	if c.WindowsPasswordTimeout == 0 {
		c.WindowsPasswordTimeout = 10 * time.Minute
	}

	// Validation
	errs := c.Comm.Prepare(ctx)
	if c.SourceAmi == "" {
		errs = append(errs, errors.New("A source_ami must be specified"))
	}

	if c.InstanceType == "" {
		errs = append(errs, errors.New("An instance_type must be specified"))
	}

	if c.SpotPrice == "auto" {
		if c.SpotPriceAutoProduct == "" {
			errs = append(errs, errors.New(
				"spot_price_auto_product must be specified when spot_price is auto"))
		}
	}

	if c.UserData != "" && c.UserDataFile != "" {
		errs = append(errs, fmt.Errorf("Only one of user_data or user_data_file can be specified."))
	} else if c.UserDataFile != "" {
		if _, err := os.Stat(c.UserDataFile); err != nil {
			errs = append(errs, fmt.Errorf("user_data_file not found: %s", c.UserDataFile))
		}
	}

	if c.SecurityGroupId != "" {
		if len(c.SecurityGroupIds) > 0 {
			errs = append(errs, fmt.Errorf("Only one of security_group_id or security_group_ids can be specified."))
		} else {
			c.SecurityGroupIds = []string{c.SecurityGroupId}
			c.SecurityGroupId = ""
		}
	}

	return errs
}
開發者ID:cewood,項目名稱:packer,代碼行數:47,代碼來源:run_config.go

示例12: Run

func (s *stepCreateServer) Run(state multistep.StateBag) multistep.StepAction {
	client := state.Get("client").(*vultr.Client)
	ui := state.Get("ui").(packer.Ui)
	c := state.Get("config").(config)
	var keyId string
	var err error
	if c.SSHPrivateKey != "" {
		ui.Say("Uploading SSH key")
		name := fmt.Sprintf("packer-%s", uuid.TimeOrderedUUID())
		keyId, err = client.CreateSSHKey(name, c.SSHPrivateKey)
		if err != nil {
			err := fmt.Errorf("Error uploading ssh key: %s", err)
			state.Put("error", err)
			ui.Error(err.Error())
			return multistep.ActionHalt
		}
	}
	ui.Say("Creating server...")
	// Create the droplet based on configuration
	opts := client.CreateOpts()
	opts.Region = c.Region
	opts.Plan = c.Plan
	opts.Os = c.Os
	opts.PrivateNet = c.PrivateNetworking
	opts.IpV6 = c.IPv6
	opts.IpxeUrl = c.IpxeUrl
	if c.SSHPrivateKey != "" {
		opts.SSHKeyId = keyId
	}
	serverId, err := client.CreateServer(&opts)

	if err != nil {
		err := fmt.Errorf("Error creating server: %s", err)
		state.Put("error", err)
		ui.Error(err.Error())
		return multistep.ActionHalt
	}

	// We use this in cleanup
	s.serverId = serverId

	// Store the droplet id for later
	state.Put("server_id", serverId)

	return multistep.ActionContinue
}
開發者ID:stephencheng,項目名稱:packer-builder-vultr,代碼行數:46,代碼來源:step_create.go

示例13: Run

func (s *stepCreateSSHKey) Run(state multistep.StateBag) multistep.StepAction {
	client := state.Get("client").(*DigitalOceanClient)
	ui := state.Get("ui").(packer.Ui)

	ui.Say("Creating temporary ssh key for droplet...")

	priv, err := rsa.GenerateKey(rand.Reader, 2014)

	// ASN.1 DER encoded form
	priv_der := x509.MarshalPKCS1PrivateKey(priv)
	priv_blk := pem.Block{
		Type:    "RSA PRIVATE KEY",
		Headers: nil,
		Bytes:   priv_der,
	}

	// Set the private key in the statebag for later
	state.Put("privateKey", string(pem.EncodeToMemory(&priv_blk)))

	// Marshal the public key into SSH compatible format
	// TODO properly handle the public key error
	pub, _ := ssh.NewPublicKey(&priv.PublicKey)
	pub_sshformat := string(ssh.MarshalAuthorizedKey(pub))

	// The name of the public key on DO
	name := fmt.Sprintf("packer-%s", uuid.TimeOrderedUUID())

	// Create the key!
	keyId, err := client.CreateKey(name, pub_sshformat)
	if err != nil {
		err := fmt.Errorf("Error creating temporary SSH key: %s", err)
		state.Put("error", err)
		ui.Error(err.Error())
		return multistep.ActionHalt
	}

	// We use this to check cleanup
	s.keyId = keyId

	log.Printf("temporary ssh key name: %s", name)

	// Remember some state for the future
	state.Put("ssh_key_id", keyId)

	return multistep.ActionContinue
}
開發者ID:Nitron,項目名稱:packer,代碼行數:46,代碼來源:step_create_ssh_key.go

示例14: Run

func (s *stepDeployVirtualMachine) Run(state multistep.StateBag) multistep.StepAction {
	client := state.Get("client").(*gopherstack.CloudstackClient)
	ui := state.Get("ui").(packer.Ui)
	c := state.Get("config").(config)
	sshKeyName := state.Get("ssh_key_name").(string)

	ui.Say("Creating virtual machine...")

	// Some random virtual machine name as it's temporary
	displayName := fmt.Sprintf("packer-%s", uuid.TimeOrderedUUID())

	// Massage any userData that we wish to send to the virtual
	// machine to help it boot properly.
	processTemplatedUserdata(state)
	userData := state.Get("user_data").(string)

	// Create the virtual machine based on configuration
	response, err := client.DeployVirtualMachine(c.ServiceOfferingId,
		c.TemplateId, c.ZoneId, "", c.DiskOfferingId, displayName,
		c.NetworkIds, sshKeyName, "", userData, c.Hypervisor)

	if err != nil {
		err := fmt.Errorf("Error deploying virtual machine: %s", err)
		state.Put("error", err)
		ui.Error(err.Error())
		return multistep.ActionHalt
	}

	// Unpack the async jobid and wait for it
	vmid := response.Deployvirtualmachineresponse.ID
	jobid := response.Deployvirtualmachineresponse.Jobid
	client.WaitForAsyncJob(jobid, c.stateTimeout)

	// We use this in cleanup
	s.id = vmid

	// Store the virtual machine id for later use
	state.Put("virtual_machine_id", vmid)

	return multistep.ActionContinue
}
開發者ID:shouyu,項目名稱:packer-cloudstack,代碼行數:41,代碼來源:step_deploy_virtual_machine.go

示例15: NewConfig

func NewConfig(raws ...interface{}) (*Config, []string, error) {
	c := new(Config)
	md, err := common.DecodeConfig(c, raws...)
	if err != nil {
		return nil, nil, err
	}

	c.tpl, err = packer.NewConfigTemplate()
	if err != nil {
		return nil, nil, err
	}
	c.tpl.UserVars = c.PackerUserVars

	// Prepare the errors
	errs := common.CheckUnusedConfig(md)

	// Set defaults.
	if c.Network == "" {
		c.Network = "default"
	}

	if c.DiskSizeGb == 0 {
		c.DiskSizeGb = 10
	}

	if c.ImageDescription == "" {
		c.ImageDescription = "Created by Packer"
	}

	if c.ImageName == "" {
		c.ImageName = "packer-{{timestamp}}"
	}

	if c.InstanceName == "" {
		c.InstanceName = fmt.Sprintf("packer-%s", uuid.TimeOrderedUUID())
	}

	if c.MachineType == "" {
		c.MachineType = "n1-standard-1"
	}

	if c.RawSSHTimeout == "" {
		c.RawSSHTimeout = "5m"
	}

	if c.RawStateTimeout == "" {
		c.RawStateTimeout = "5m"
	}

	if c.SSHUsername == "" {
		c.SSHUsername = "root"
	}

	if c.SSHPort == 0 {
		c.SSHPort = 22
	}

	// Process Templates
	templates := map[string]*string{
		"account_file":        &c.AccountFile,
		"client_secrets_file": &c.ClientSecretsFile,

		"bucket_name":             &c.BucketName,
		"image_name":              &c.ImageName,
		"image_description":       &c.ImageDescription,
		"instance_name":           &c.InstanceName,
		"machine_type":            &c.MachineType,
		"network":                 &c.Network,
		"project_id":              &c.ProjectId,
		"source_image":            &c.SourceImage,
		"source_image_project_id": &c.SourceImageProjectId,
		"ssh_username":            &c.SSHUsername,
		"ssh_timeout":             &c.RawSSHTimeout,
		"state_timeout":           &c.RawStateTimeout,
		"zone":                    &c.Zone,
	}

	for n, ptr := range templates {
		var err error
		*ptr, err = c.tpl.Process(*ptr, nil)
		if err != nil {
			errs = packer.MultiErrorAppend(
				errs, fmt.Errorf("Error processing %s: %s", n, err))
		}
	}

	// Process required parameters.
	if c.BucketName == "" {
		errs = packer.MultiErrorAppend(
			errs, errors.New("a bucket_name must be specified"))
	}

	if c.AccountFile == "" {
		errs = packer.MultiErrorAppend(
			errs, errors.New("an account_file must be specified"))
	}

	if c.ClientSecretsFile == "" {
		errs = packer.MultiErrorAppend(
			errs, errors.New("a client_secrets_file must be specified"))
//.........這裏部分代碼省略.........
開發者ID:JNPRAutomate,項目名稱:packer,代碼行數:101,代碼來源:config.go


注:本文中的github.com/mitchellh/packer/common/uuid.TimeOrderedUUID函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。