Пример #1
0
// Communicate with all EC2 endpoints to see if they are alive.
func (s *ClientTests) TestRegions(c *C) {
	name := sessionName("goamz-region-test")
	perms := []ec2.IPPerm{{
		Protocol:  "tcp",
		FromPort:  80,
		ToPort:    80,
		SourceIPs: []string{"127.0.0.1/32"},
	}}
	errs := make(chan error, len(allRegions))
	for _, region := range allRegions {
		go func(r aws.Region) {
			e := ec2.New(s.ec2.Auth, r)
			_, err := e.AuthorizeSecurityGroup(ec2.SecurityGroup{Name: name}, perms)
			errs <- err
		}(region)
	}
	for _ = range allRegions {
		err := <-errs
		if err != nil {
			ec2_err, ok := err.(*ec2.Error)
			if ok {
				c.Check(ec2_err.Code, Matches, "InvalidGroup.NotFound")
			} else {
				c.Errorf("Non-EC2 error: %s", err)
			}
		} else {
			c.Errorf("Test should have errored but it seems to have succeeded")
		}
	}
}
Пример #2
0
func (s *AmazonClientSuite) SetUpSuite(c *C) {
	if !testutil.Amazon {
		c.Skip("AmazonClientSuite tests not enabled")
	}
	s.srv.SetUp(c)
	s.ec2 = ec2.New(s.srv.auth, aws.USEast)
}
Пример #3
0
func (s *StepCreateTags) Run(state multistep.StateBag) multistep.StepAction {
	ec2conn := state.Get("ec2").(ec2.EC2)
	ui := state.Get("ui").(packer.Ui)
	amis := state.Get("amis").(map[string]string)

	if len(s.Tags) > 0 {
		for region, ami := range amis {
			ui.Say(fmt.Sprintf("Adding tags to AMI (%s)...", ami))

			var ec2Tags []ec2.Tag
			for key, value := range s.Tags {
				ui.Message(fmt.Sprintf("Adding tag: \"%s\": \"%s\"", key, value))
				ec2Tags = append(ec2Tags, ec2.Tag{key, value})
			}

			regionconn := ec2.New(ec2conn.Auth, aws.Regions[region])
			_, err := regionconn.CreateTags([]string{ami}, ec2Tags)
			if err != nil {
				err := fmt.Errorf("Error adding tags to AMI (%s): %s", ami, err)
				state.Put("error", err)
				ui.Error(err.Error())
				return multistep.ActionHalt
			}
		}
	}

	return multistep.ActionContinue
}
Пример #4
0
func (s *StepAMIRegionCopy) Run(state multistep.StateBag) multistep.StepAction {
	ec2conn := state.Get("ec2").(ec2.EC2)
	ui := state.Get("ui").(packer.Ui)
	amis := state.Get("amis").(map[string]string)
	ami := amis[ec2conn.Region.Name]

	if len(s.Regions) == 0 {
		return multistep.ActionContinue
	}

	ui.Say(fmt.Sprintf("Copying AMI (%s) to other regions...", ami))
	for _, region := range s.Regions {
		ui.Message(fmt.Sprintf("Copying to: %s", region))

		// Connect to the region where the AMI will be copied to
		regionconn := ec2.New(ec2conn.Auth, aws.Regions[region])
		resp, err := regionconn.CopyImage(&ec2.CopyImage{
			SourceRegion:  ec2conn.Region.Name,
			SourceImageId: ami,
		})

		if err != nil {
			err := fmt.Errorf("Error Copying AMI (%s) to region (%s): %s", ami, region, err)
			state.Put("error", err)
			ui.Error(err.Error())
			return multistep.ActionHalt
		}

		stateChange := StateChangeConf{
			Conn:      regionconn,
			Pending:   []string{"pending"},
			Target:    "available",
			Refresh:   AMIStateRefreshFunc(regionconn, resp.ImageId),
			StepState: state,
		}

		ui.Say(fmt.Sprintf("Waiting for AMI (%s) in region (%s) to become ready...",
			resp.ImageId, region))
		if _, err := WaitForState(&stateChange); err != nil {
			err := fmt.Errorf("Error waiting for AMI (%s) in region (%s): %s", resp.ImageId, region, err)
			state.Put("error", err)
			ui.Error(err.Error())
			return multistep.ActionHalt
		}

		amis[region] = resp.ImageId
	}

	state.Put("amis", amis)
	return multistep.ActionContinue
}
Пример #5
0
func (s *S) TestSignatureWithEndpointPath(c *C) {
	ec2.FakeTime(true)
	defer ec2.FakeTime(false)

	testServer.Response(200, nil, RebootInstancesExample)

	// https://bugs.launchpad.net/goamz/+bug/1022749
	ec2 := ec2.New(s.ec2.Auth, aws.Region{EC2Endpoint: testServer.URL + "/services/Cloud"})

	_, err := ec2.RebootInstances("i-10a64379")
	c.Assert(err, IsNil)

	req := testServer.WaitRequest()
	c.Assert(req.Form["Signature"], DeepEquals, []string{"klxs+VwDa1EKHBsxlDYYN58wbP6An+RVdhETv1Fm/os="})
}
Пример #6
0
func (a *Artifact) Destroy() error {
	errors := make([]error, 0)

	for region, imageId := range a.Amis {
		log.Printf("Deregistering image ID (%s) from region (%s)", imageId, region)
		regionconn := ec2.New(a.Conn.Auth, aws.Regions[region])
		if _, err := regionconn.DeregisterImage(imageId); err != nil {
			errors = append(errors, err)
		}

		// TODO(mitchellh): Delete the snapshots associated with an AMI too
	}

	if len(errors) > 0 {
		if len(errors) == 1 {
			return errors[0]
		} else {
			return &packer.MultiError{errors}
		}
	}

	return nil
}
Пример #7
0
func (b *Builder) Run(ui packer.Ui, hook packer.Hook, cache packer.Cache) (packer.Artifact, error) {
	region, err := b.config.Region()
	if err != nil {
		return nil, err
	}

	auth, err := b.config.AccessConfig.Auth()
	if err != nil {
		return nil, err
	}

	ec2conn := ec2.New(auth, region)

	// Setup the state bag and initial state for the steps
	state := new(multistep.BasicStateBag)
	state.Put("config", b.config)
	state.Put("ec2", ec2conn)
	state.Put("hook", hook)
	state.Put("ui", ui)

	// Build the steps
	steps := []multistep.Step{
		&awscommon.StepKeyPair{
			Debug:        b.config.PackerDebug,
			DebugKeyPath: fmt.Sprintf("ec2_%s.pem", b.config.PackerBuildName),
			KeyPairName:  b.config.TemporaryKeyPairName,
		},
		&awscommon.StepSecurityGroup{
			SecurityGroupId: b.config.SecurityGroupId,
			SSHPort:         b.config.SSHPort,
			VpcId:           b.config.VpcId,
		},
		&awscommon.StepRunSourceInstance{
			Debug:              b.config.PackerDebug,
			ExpectedRootDevice: "ebs",
			InstanceType:       b.config.InstanceType,
			UserData:           b.config.UserData,
			UserDataFile:       b.config.UserDataFile,
			SourceAMI:          b.config.SourceAmi,
			IamInstanceProfile: b.config.IamInstanceProfile,
			SubnetId:           b.config.SubnetId,
			BlockDevices:       b.config.BlockDevices,
		},
		&common.StepConnectSSH{
			SSHAddress:     awscommon.SSHAddress(ec2conn, b.config.SSHPort),
			SSHConfig:      awscommon.SSHConfig(b.config.SSHUsername),
			SSHWaitTimeout: b.config.SSHTimeout(),
		},
		&common.StepProvision{},
		&stepStopInstance{},
		&stepCreateAMI{},
		&awscommon.StepAMIRegionCopy{
			Regions: b.config.AMIRegions,
		},
		&awscommon.StepModifyAMIAttributes{
			Description: b.config.AMIDescription,
			Users:       b.config.AMIUsers,
			Groups:      b.config.AMIGroups,
		},
		&awscommon.StepCreateTags{
			Tags: b.config.AMITags,
		},
	}

	// Run!
	if b.config.PackerDebug {
		b.runner = &multistep.DebugRunner{
			Steps:   steps,
			PauseFn: common.MultistepDebugFn(ui),
		}
	} else {
		b.runner = &multistep.BasicRunner{Steps: steps}
	}

	b.runner.Run(state)

	// If there was an error, return that
	if rawErr, ok := state.GetOk("error"); ok {
		return nil, rawErr.(error)
	}

	// If there are no AMIs, then just return
	if _, ok := state.GetOk("amis"); !ok {
		return nil, nil
	}

	// Build the artifact and return it
	artifact := &awscommon.Artifact{
		Amis:           state.Get("amis").(map[string]string),
		BuilderIdValue: BuilderId,
		Conn:           ec2conn,
	}

	return artifact, nil
}
Пример #8
0
func (s *LocalServerSuite) SetUpSuite(c *C) {
	s.srv.SetUp(c)
	s.ServerTests.ec2 = ec2.New(s.srv.auth, s.srv.region)
	s.clientTests.ec2 = ec2.New(s.srv.auth, s.srv.region)
}
Пример #9
0
func (b *Builder) Run(ui packer.Ui, hook packer.Hook, cache packer.Cache) (packer.Artifact, error) {
	if runtime.GOOS != "linux" {
		return nil, errors.New("The amazon-chroot builder only works on Linux environments.")
	}

	region, err := b.config.Region()
	if err != nil {
		return nil, err
	}

	auth, err := b.config.AccessConfig.Auth()
	if err != nil {
		return nil, err
	}

	ec2conn := ec2.New(auth, region)

	wrappedCommand := func(command string) (string, error) {
		return b.config.tpl.Process(
			b.config.CommandWrapper, &wrappedCommandTemplate{
				Command: command,
			})
	}

	// Setup the state bag and initial state for the steps
	state := new(multistep.BasicStateBag)
	state.Put("config", &b.config)
	state.Put("ec2", ec2conn)
	state.Put("hook", hook)
	state.Put("ui", ui)
	state.Put("wrappedCommand", CommandWrapper(wrappedCommand))

	// Build the steps
	steps := []multistep.Step{
		&StepInstanceInfo{},
		&StepSourceAMIInfo{},
		&StepFlock{},
		&StepPrepareDevice{},
		&StepCreateVolume{},
		&StepAttachVolume{},
		&StepEarlyUnflock{},
		&StepMountDevice{},
		&StepMountExtra{},
		&StepCopyFiles{},
		&StepChrootProvision{},
		&StepEarlyCleanup{},
		&StepSnapshot{},
		&StepRegisterAMI{},
		&awscommon.StepAMIRegionCopy{
			Regions: b.config.AMIRegions,
		},
		&awscommon.StepModifyAMIAttributes{
			Description: b.config.AMIDescription,
			Users:       b.config.AMIUsers,
			Groups:      b.config.AMIGroups,
		},
		&awscommon.StepCreateTags{
			Tags: b.config.AMITags,
		},
	}

	// Run!
	if b.config.PackerDebug {
		b.runner = &multistep.DebugRunner{
			Steps:   steps,
			PauseFn: common.MultistepDebugFn(ui),
		}
	} else {
		b.runner = &multistep.BasicRunner{Steps: steps}
	}

	b.runner.Run(state)

	// If there was an error, return that
	if rawErr, ok := state.GetOk("error"); ok {
		return nil, rawErr.(error)
	}

	// If there are no AMIs, then just return
	if _, ok := state.GetOk("amis"); !ok {
		return nil, nil
	}

	// Build the artifact and return it
	artifact := &awscommon.Artifact{
		Amis:           state.Get("amis").(map[string]string),
		BuilderIdValue: BuilderId,
		Conn:           ec2conn,
	}

	return artifact, nil
}
Пример #10
0
func (s *StepModifyAMIAttributes) Run(state multistep.StateBag) multistep.StepAction {
	ec2conn := state.Get("ec2").(ec2.EC2)
	ui := state.Get("ui").(packer.Ui)
	amis := state.Get("amis").(map[string]string)

	// Determine if there is any work to do.
	valid := false
	valid = valid || s.Description != ""
	valid = valid || (s.Users != nil && len(s.Users) > 0)
	valid = valid || (s.Groups != nil && len(s.Groups) > 0)
	valid = valid || (s.ProductCodes != nil && len(s.ProductCodes) > 0)

	if !valid {
		return multistep.ActionContinue
	}

	// Construct the modify image attribute requests we're going to make.
	// We need to make each separately since the EC2 API only allows changing
	// one type at a kind currently.
	options := make(map[string]*ec2.ModifyImageAttribute)
	if s.Description != "" {
		options["description"] = &ec2.ModifyImageAttribute{
			Description: s.Description,
		}
	}

	if len(s.Groups) > 0 {
		options["groups"] = &ec2.ModifyImageAttribute{
			AddGroups: s.Groups,
		}
	}

	if len(s.Users) > 0 {
		options["users"] = &ec2.ModifyImageAttribute{
			AddUsers: s.Users,
		}
	}

	if len(s.ProductCodes) > 0 {
		options["product codes"] = &ec2.ModifyImageAttribute{
			ProductCodes: s.ProductCodes,
		}
	}

	for region, ami := range amis {
		ui.Say(fmt.Sprintf("Modifying attributes on AMI (%s)...", ami))
		regionconn := ec2.New(ec2conn.Auth, aws.Regions[region])
		for name, opts := range options {
			ui.Message(fmt.Sprintf("Modifying: %s", name))
			_, err := regionconn.ModifyImageAttribute(ami, opts)
			if err != nil {
				err := fmt.Errorf("Error modify AMI attributes: %s", err)
				state.Put("error", err)
				ui.Error(err.Error())
				return multistep.ActionHalt
			}
		}
	}

	return multistep.ActionContinue
}
Пример #11
0
func (s *S) SetUpSuite(c *C) {
	testServer.Start()
	auth := aws.Auth{"abc", "123", ""}
	s.ec2 = ec2.New(auth, aws.Region{EC2Endpoint: testServer.URL})
}