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
}
Exemple #2
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")
		}
	}
}
// newAWSCloud creates a new instance of AWSCloud.
// authFunc and instanceId are primarily for tests
func newAWSCloud(config io.Reader, authFunc AuthFunc, metadata AWSMetadata) (*AWSCloud, error) {
	cfg, err := readAWSCloudConfig(config, metadata)
	if err != nil {
		return nil, fmt.Errorf("unable to read AWS cloud provider config file: %v", err)
	}

	auth, err := authFunc()
	if err != nil {
		return nil, err
	}

	zone := cfg.Global.Zone
	if len(zone) <= 1 {
		return nil, fmt.Errorf("invalid AWS zone in config file: %s", zone)
	}
	regionName := zone[:len(zone)-1]

	region, ok := aws.Regions[regionName]
	if !ok {
		return nil, fmt.Errorf("not a valid AWS zone (unknown region): %s", zone)
	}

	ec2 := &goamzEC2{ec2: ec2.New(auth, region)}

	awsCloud := &AWSCloud{
		ec2:              ec2,
		cfg:              cfg,
		region:           region,
		availabilityZone: zone,
		metadata:         metadata,
	}

	return awsCloud, nil
}
Exemple #4
0
func main() {
	kingpin.Version("0.0.1")
	kingpin.CommandLine.Help = "AWS deployment tools."
	kingpin.Parse()

	auth, err := aws.EnvAuth()
	Check(err)

	state := new(multistep.BasicStateBag)

	// This allows us to share our client connections while in each of the steps.
	state.Put("client_elb", elb.New(auth, aws.USWest2))
	state.Put("client_ec2", ec2.New(auth, aws.USWest2))

	// Standard configuration that has been passed in via the CLI.
	state.Put("elb", *elbId)
	state.Put("ami", *amiId)
	state.Put("key", *key)
	state.Put("size", *size)
	state.Put("region", aws.Regions[*region])
	state.Put("security", *security)
	state.Put("tags", *tags)

	steps := []multistep.Step{
		&StepDestroy{}, // Remove the existing hosts from the Load balancer.
		&StepCreate{},  // Create some EC2 instances and ensure they are ready to be deployed.
	}
	runner := &multistep.BasicRunner{Steps: steps}
	runner.Run(state)
}
func main() {
	var regionStr string
	flag.StringVar(&regionStr, "r", "us-east-1", "Region")
	flag.Parse()

	region, err := strToRegion(regionStr)
	if err == nil {
		log.Fatal(err)
	}

	auth, err := aws.EnvAuth()
	if err != nil {
		log.Fatal(err)
	}

	client := ec2.New(auth, *region)

	resp, err := client.Instances(nil, nil)
	if err != nil {
		log.Fatal(err)
	}

	instances := []ec2.Instance{}
	for _, reservation := range resp.Reservations {
		instances = append(instances, reservation.Instances...)
	}

	b, err := json.Marshal(instances)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("%s\n", b)
}
Exemple #6
0
func (s *AmazonServerSuite) SetUpSuite(c *C) {
	if !testutil.Amazon {
		c.Skip("AmazonServerSuite tests not enabled")
	}
	s.srv.SetUp(c)
	s.ServerTests.ec2 = ec2.New(s.srv.auth, aws.USEast)
}
Exemple #7
0
func NewEc2Discoverer(c *cli.Context) Ec2Discoverer {
	auth, err := aws.EnvAuth()
	if err != nil {
		log.Fatal(err)
	}

	tag := c.String("ec2-tag")
	if tag == "" {
		log.Fatal(errors.New("You must specify --ec2-tag option"))
	}

	t := strings.Split(tag, ":")
	tagKey, tagValue := t[0], t[1]

	regionStr := c.String("ec2-region")
	region, ok := aws.Regions[regionStr]
	if !ok {
		log.Fatal(fmt.Errorf("%s region is not valid", regionStr))
	}

	client := ec2.New(auth, region)
	return Ec2Discoverer{
		Client:   client,
		TagKey:   tagKey,
		TagValue: tagValue,
	}
}
// amiRegionCopy does a copy for the given AMI to the target region and
// returns the resulting ID or error.
func amiRegionCopy(state multistep.StateBag, auth aws.Auth, imageId string,
	target aws.Region, source aws.Region) (string, error) {

	// Connect to the region where the AMI will be copied to
	regionconn := ec2.New(auth, target)
	resp, err := regionconn.CopyImage(&ec2.CopyImage{
		SourceRegion:  source.Name,
		SourceImageId: imageId,
	})

	if err != nil {
		return "", fmt.Errorf("Error Copying AMI (%s) to region (%s): %s",
			imageId, target.Name, err)
	}

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

	if _, err := WaitForState(&stateChange); err != nil {
		return "", fmt.Errorf("Error waiting for AMI (%s) in region (%s): %s",
			resp.ImageId, target.Name, err)
	}

	return resp.ImageId, nil
}
func (cache *EC2Cache) Instances() (*ec2.InstancesResp, error) {
	auth, err := aws.GetAuth(cache.accessKey, cache.secretKey)
	if err != nil {
		return nil, err
	}

	return ec2.New(auth, cache.region).Instances(nil, nil)
}
Exemple #10
0
func main() {
	s := &session{}

	handleOptions(s)

	// connect to AWS
	auth := aws.Auth{AccessKey: s.awsAccessKeyId, SecretKey: s.awsSecretAccessKey}
	awsec2 := ec2.New(auth, s.sourceRegion)
	awsec2dest := ec2.New(auth, s.destRegion)

	// purge old AMIs and snapshots in both regions
	if len(s.windows) > 0 {
		err := purgeAMIs(awsec2, s.instanceNameTag, s.windows, s)
		if err != nil {
			s.warning(fmt.Sprintf("Error purging old AMIs: %s", err.Error()))
		}
		if s.destRegion.Name != s.sourceRegion.Name {
			err = purgeAMIs(awsec2dest, s.instanceNameTag, s.windows, s)
			if err != nil {
				s.warning(fmt.Sprintf("Error purging old AMIs: %s", err.Error()))
			}
		}
	}
	if s.purgeonly {
		s.ok("Purging done and --purgeonly specified - exiting.")
		os.Exit(s.finish())
	}

	// search for our instances
	instances := findInstances(awsec2, s)
	if len(instances) < 1 {
		s.fatal(fmt.Sprintf("No instances with matching name tag: %s", s.instanceNameTag))
	} else {
		s.debug(fmt.Sprintf("Found %d instances with matching Name tag: %s", len(instances), s.instanceNameTag))
	}

	// create local AMIs
	newAMIs := createAMIs(awsec2, instances, s)

	// create AMIs to backup region
	copyAMI(awsec2dest, s, &newAMIs)

	// this finish() call gives us nagios output, if desired
	os.Exit(s.finish())
}
Exemple #11
0
func (b *Builder) Run(ui packer.Ui, hook packer.Hook, cache packer.Cache) (packer.Artifact, error) {
	region, ok := aws.Regions[b.config.Region]
	if !ok {
		panic("region not found")
	}

	auth := aws.Auth{b.config.AccessKey, b.config.SecretKey}
	ec2conn := ec2.New(auth, region)

	// Setup the state bag and initial state for the steps
	state := make(map[string]interface{})
	state["config"] = b.config
	state["ec2"] = ec2conn
	state["hook"] = hook
	state["ui"] = ui

	// Build the steps
	steps := []multistep.Step{
		&stepKeyPair{},
		&stepSecurityGroup{},
		&stepRunSourceInstance{},
		&stepConnectSSH{},
		&stepProvision{},
		&stepStopInstance{},
		&stepCreateAMI{},
	}

	// 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["error"]; ok {
		return nil, rawErr.(error)
	}

	// If there are no AMIs, then just return
	if _, ok := state["amis"]; !ok {
		return nil, nil
	}

	// Build the artifact and return it
	artifact := &artifact{
		amis: state["amis"].(map[string]string),
		conn: ec2conn,
	}

	return artifact, nil
}
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
}
Exemple #13
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="})
}
Exemple #14
0
func getInstances(name string) (instances []ec2.Instance, err error) {
	auth, err := aws.EnvAuth()
	if err != nil {
		panic(err.Error())
	}
	e := ec2.New(auth, aws.USEast)
	filter := ec2.NewFilter()
	filter.Add("instance-state-name", "running")
	filter.Add("instance-state-name", "stopped")
	filter.Add("tag:Name", name)
	resp, err2 := e.Instances(nil, filter)
	instances = make([]ec2.Instance, 0, 5)
	for _, reservation := range resp.Reservations {
		instances = append(instances, reservation.Instances...)
	}
	return instances, err2
}
func (p *ResourceProvider) Configure(c *terraform.ResourceConfig) error {
	if _, err := config.Decode(&p.Config, c.Config); err != nil {
		return err
	}

	// Get the auth and region. This can fail if keys/regions were not
	// specified and we're attempting to use the environment.
	var errs []error
	log.Println("[INFO] Building AWS auth structure")
	auth, err := p.Config.AWSAuth()
	if err != nil {
		errs = append(errs, err)
	}

	log.Println("[INFO] Building AWS region structure")
	region, err := p.Config.AWSRegion()
	if err != nil {
		errs = append(errs, err)
	}

	if len(errs) == 0 {
		log.Println("[INFO] Initializing EC2 connection")
		p.ec2conn = ec2.New(auth, region)
		log.Println("[INFO] Initializing ELB connection")
		p.elbconn = elb.New(auth, region)
		log.Println("[INFO] Initializing AutoScaling connection")
		p.autoscalingconn = autoscaling.New(auth, region)
		log.Println("[INFO] Initializing S3 connection")
		p.s3conn = s3.New(auth, region)
		log.Println("[INFO] Initializing RDS connection")
		p.rdsconn = rds.New(auth, region)
		log.Println("[INFO] Initializing Route53 connection")
		p.route53 = route53.New(auth, region)
	}

	if len(errs) > 0 {
		return &multierror.Error{Errors: errs}
	}

	// Create the provider, set the meta
	p.p = Provider()
	p.p.SetMeta(p)

	return nil
}
func main() {
	initFlags()

	filter := ec2.NewFilter()
	for _, t := range tags {
		filter.Add("tag-key", t)
	}

	auth, err := aws.EnvAuth()
	if err != nil {
		log.Fatal(err)
	}
	e := ec2.New(auth, region)

	for {
		resp, err := e.Instances(nil, filter)
		if err != nil {
			log.Fatal(err)
		}
		instances := flattenReservations(resp.Reservations)

		if len(tags) == 0 {
			tags = allTagKeys(instances)
		}

		targetGroups := groupByTags(instances, tags)
		b := marshalTargetGroups(targetGroups)
		if dest == "-" {
			_, err = os.Stdout.Write(b)
		} else {
			err = atomicWriteFile(dest, b, ".new")
		}
		if err != nil {
			log.Fatal(err)
		}

		if sleep == 0 {
			break
		} else {
			time.Sleep(sleep)
		}
	}
}
func main() {
	var regionStr string
	var flatten bool
	flag.StringVar(&regionStr, "r", "us-east-1", "Region")
	flag.BoolVar(&flatten, "f", false, "Flatten instances (The result will be an array)")
	flag.Parse()

	region, ok := aws.Regions[regionStr]
	if !ok {
		log.Fatal(fmt.Errorf("Region %s is unknown.", regionStr))
	}

	auth, err := aws.EnvAuth()
	if err != nil {
		log.Fatal(err)
	}

	client := ec2.New(auth, region)

	resp, err := client.Instances(nil, nil)
	if err != nil {
		log.Fatal(err)
	}

	var obj interface{}

	if flatten {
		instances := []ec2.Instance{}
		for _, reservation := range resp.Reservations {
			instances = append(instances, reservation.Instances...)
		}
		obj = instances
	} else {
		obj = resp
	}

	b, err := json.Marshal(obj)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("%s\n", b)
}
Exemple #18
0
func printList(cfg *configuration) {
	auth, err := aws.GetAuth(cfg.AccessKey, cfg.SecretKey)
	if err != nil {
		die("Error creating AWS auth:\n%s\n", err)
	}

	e := ec2.New(auth, aws.EUWest)
	instances, err := e.Instances([]string{}, nil)
	if err != nil {
		die("Error fetching EC2 instances:\n%s\n", err)
	}
	inv, err := newInventory(instances)
	if err != nil {
		die("Error creating inventory from EC2 instances:\n%s\n", err)
	}
	invJSON, err := inv.toJSON()
	if err != nil {
		die("Error generatin inventory JSON:\n%s\n", err)
	}
	os.Stdout.Write(invJSON)
}
Exemple #19
0
// newAWSCloud creates a new instance of AWSCloud.
func newAWSCloud(config io.Reader, authFunc AuthFunc) (*AWSCloud, error) {
	cfg, err := readAWSCloudConfig(config)
	if err != nil {
		return nil, fmt.Errorf("unable to read AWS cloud provider config file: %v", err)
	}

	auth, err := authFunc()
	if err != nil {
		return nil, err
	}

	region, ok := aws.Regions[cfg.Global.Region]
	if !ok {
		return nil, fmt.Errorf("not a valid AWS region: %s", cfg.Global.Region)
	}

	ec2 := ec2.New(auth, region)
	return &AWSCloud{
		ec2: ec2,
		cfg: cfg,
	}, nil
}
Exemple #20
0
// Client configures and returns a fully initailized AWSClient
func (c *Config) Client() (interface{}, error) {
	var client AWSClient

	// Get the auth and region. This can fail if keys/regions were not
	// specified and we're attempting to use the environment.
	var errs []error
	log.Println("[INFO] Building AWS auth structure")
	auth, err := c.AWSAuth()
	if err != nil {
		errs = append(errs, err)
	}

	log.Println("[INFO] Building AWS region structure")
	region, err := c.AWSRegion()
	if err != nil {
		errs = append(errs, err)
	}

	if len(errs) == 0 {
		log.Println("[INFO] Initializing EC2 connection")
		client.ec2conn = ec2.New(auth, region)
		log.Println("[INFO] Initializing ELB connection")
		client.elbconn = elb.New(auth, region)
		log.Println("[INFO] Initializing AutoScaling connection")
		client.autoscalingconn = autoscaling.New(auth, region)
		log.Println("[INFO] Initializing S3 connection")
		client.s3conn = s3.New(auth, region)
		log.Println("[INFO] Initializing RDS connection")
		client.rdsconn = rds.New(auth, region)
		log.Println("[INFO] Initializing Route53 connection")
		client.route53 = route53.New(auth, region)
	}

	if len(errs) > 0 {
		return nil, &multierror.Error{Errors: errs}
	}

	return &client, nil
}
Exemple #21
0
// newAWSCloud creates a new instance of AWSCloud.
func newAWSCloud(config io.Reader, authFunc AuthFunc) (*AWSCloud, error) {
	cfg, err := readAWSCloudConfig(config)
	if err != nil {
		return nil, fmt.Errorf("unable to read AWS cloud provider config file: %v", err)
	}

	auth, err := authFunc()
	if err != nil {
		return nil, err
	}

	// TODO: We can get the region very easily from the instance-metadata service
	region, ok := aws.Regions[cfg.Global.Region]
	if !ok {
		return nil, fmt.Errorf("not a valid AWS region: %s", cfg.Global.Region)
	}

	return &AWSCloud{
		ec2:    &GoamzEC2{ec2: ec2.New(auth, region)},
		cfg:    cfg,
		region: region,
	}, nil
}
Exemple #22
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
}
Exemple #23
0
// NewEC2Interface ... Creates a new EC2 Helper interface
func NewEC2Interface(awsKey, awsSecret, awsRegion, envTag string) (EC2Interface, error) {
	glog.Infof("Create a new EC2 API client for region: %s", awsRegion)

	service := new(ec2Helper)
	service.region = awsRegion
	service.envTag = envTag
	// step: check the region is valid
	region, valid := service.isValidRegion(awsRegion)
	if !valid {
		return nil, fmt.Errorf("invalid aws region specified, please check")
	}

	// step: attempt to acquire credentials
	auth, err := aws.GetAuth(awsKey, awsSecret)
	if err != nil {
		return nil, fmt.Errorf("unable to find authentication details, error: %s", err)
	}

	// step: create a client and return
	service.client = ec2.New(auth, region)
	glog.V(5).Infof("Successfully create a api client for aws in region: %s", awsRegion)

	return service, nil
}
Exemple #24
0
func (b *Builder) Run(ui packer.Ui, hook packer.Hook, cache packer.Cache) (packer.Artifact, error) {
	region, ok := aws.Regions[b.config.Region]
	if !ok {
		panic("region not found")
	}

	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 := make(map[string]interface{})
	state["config"] = &b.config
	state["ec2"] = ec2conn
	state["hook"] = hook
	state["ui"] = ui

	// Build the steps
	steps := []multistep.Step{
		&awscommon.StepKeyPair{},
		&awscommon.StepSecurityGroup{
			SecurityGroupId: b.config.SecurityGroupId,
			SSHPort:         b.config.SSHPort,
			VpcId:           b.config.VpcId,
		},
		&awscommon.StepRunSourceInstance{
			ExpectedRootDevice: "instance-store",
			InstanceType:       b.config.InstanceType,
			SourceAMI:          b.config.SourceAmi,
			SubnetId:           b.config.SubnetId,
		},
		&common.StepConnectSSH{
			SSHAddress:     awscommon.SSHAddress(b.config.SSHPort),
			SSHConfig:      awscommon.SSHConfig(b.config.SSHUsername),
			SSHWaitTimeout: b.config.SSHTimeout(),
		},
		&common.StepProvision{},
		&StepUploadX509Cert{},
		&StepBundleVolume{},
		&StepUploadBundle{},
		&StepRegisterAMI{},
	}

	// 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["error"]; ok {
		return nil, rawErr.(error)
	}

	// If there are no AMIs, then just return
	if _, ok := state["amis"]; !ok {
		return nil, nil
	}

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

	return artifact, nil
}
Exemple #25
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)
}
Exemple #26
0
func main() {
	flag.Parse()

	args := flag.Args()
	//fmt.Println(args)
	if len(args) < 1 {
		usage()
	}
	Auth = aws.Auth{accessKey, secretKey, ""}
	awsRegion := aws.Regions[*region]
	EC2 = ec2.New(Auth, awsRegion)

	switch args[0] {
	case "list":
		args = args[1:]
		filter, args := getfilter(args)
		if len(args) > 0 {
			filter.Add("tag:Name", "*"+args[0]+"*")
		}
		instances, err := EC2.Instances(nil, filter)
		if err != nil {
			fmt.Println(err)
			os.Exit(2)
		}
		list(instances)
	case "rename":
		args = args[1:]
		filter, args := getfilter(args)
		if len(args) > 1 {
			filter.Add("tag:Name", "*"+args[0]+"*")
			args = args[1:]
		}
		if len(args) == 0 {
			fmt.Println("Missing new name")
			usage()
		}
		name := args[0]
		instances, err := EC2.Instances(nil, filter)
		if err != nil {
			fmt.Println(err)
			os.Exit(2)
		}
		nInst := list(instances)
		var confirm string = ""
		for confirm != "y" && confirm != "Y" && confirm != "n" && confirm != "N" {
			fmt.Println("\nAre you sure you want to rename these", nInst, "instances to", name+"_xx", "[y,N] ? ")
			fmt.Scanf("%s", &confirm)
		}
		if confirm == "y" || confirm == "Y" {
			fmt.Println("OK!")
		}
		rename(instances, name, nInst)
	case "stop":
		fmt.Println("stop")
	case "ssh":
		args = args[1:]
		if len(args) < 1 {
			fmt.Println("Missing host")
			usage()
		}
		filter, args := getfilter(args)
		if len(args) > 0 {
			filter.Add("tag:Name", "*"+args[0]+"*")
		}
		instances, err := EC2.Instances(nil, filter)
		if err != nil {
			fmt.Println(err)
			os.Exit(2)
		}
		ssh(instances)
	default:
		filter := ec2.NewFilter()
		filter.Add("tag:Name", "*"+args[0]+"*")
		instances, err := EC2.Instances(nil, filter)
		if err != nil {
			fmt.Println(err)
			os.Exit(2)
		}
		list(instances)
	}
}
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
		}

		ui.Say(fmt.Sprintf("Waiting for AMI (%s) in region (%s) to become ready...", resp.ImageId, region))
		if err := WaitForAMI(regionconn, resp.ImageId); 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
		}

		// Need to re-apply Tags since they are not copied with the AMI
		if len(s.Tags) > 0 {
			ui.Say(fmt.Sprintf("Adding tags to AMI (%s)...", resp.ImageId))

			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})
			}

			_, err := regionconn.CreateTags([]string{resp.ImageId}, ec2Tags)
			if err != nil {
				err := fmt.Errorf("Error adding tags to AMI (%s): %s", resp.ImageId, err)
				state.Put("error", err)
				ui.Error(err.Error())
				return multistep.ActionHalt
			}
		}

		amis[region] = resp.ImageId
	}

	state.Put("amis", amis)
	return multistep.ActionContinue
}
Exemple #28
0
func buildEc2Client() *ec2.EC2 {
	auth := aws.Auth{os.Getenv("AWS_ACCESS_KEY_ID"), os.Getenv("AWS_SECRET_ACCESS_KEY"), ""}
	return ec2.New(auth, aws.USEast)
}
Exemple #29
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,
			PrivateKeyFile: b.config.SSHPrivateKeyFile,
		},
		&awscommon.StepSecurityGroup{
			SecurityGroupIds: b.config.SecurityGroupIds,
			SSHPort:          b.config.SSHPort,
			VpcId:            b.config.VpcId,
		},
		&awscommon.StepRunSourceInstance{
			Debug:                    b.config.PackerDebug,
			ExpectedRootDevice:       "instance-store",
			InstanceType:             b.config.InstanceType,
			IamInstanceProfile:       b.config.IamInstanceProfile,
			UserData:                 b.config.UserData,
			UserDataFile:             b.config.UserDataFile,
			SourceAMI:                b.config.SourceAmi,
			SubnetId:                 b.config.SubnetId,
			AssociatePublicIpAddress: b.config.AssociatePublicIpAddress,
			AvailabilityZone:         b.config.AvailabilityZone,
			BlockDevices:             b.config.BlockDevices,
			Tags:                     b.config.RunTags,
		},
		&common.StepConnectSSH{
			SSHAddress:     awscommon.SSHAddress(ec2conn, b.config.SSHPort),
			SSHConfig:      awscommon.SSHConfig(b.config.SSHUsername),
			SSHWaitTimeout: b.config.SSHTimeout(),
		},
		&common.StepProvision{},
		&StepUploadX509Cert{},
		&StepBundleVolume{},
		&StepUploadBundle{},
		&StepRegisterAMI{},
		&awscommon.StepAMIRegionCopy{
			Regions: b.config.AMIRegions,
		},
		&awscommon.StepModifyAMIAttributes{
			Description:  b.config.AMIDescription,
			Users:        b.config.AMIUsers,
			Groups:       b.config.AMIGroups,
			ProductCodes: b.config.AMIProductCodes,
		},
		&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
}
Exemple #30
0
//helper function for getting an EC2 handle at US east
func getUSEast(creds aws.Auth) *ec2.EC2 {
	return ec2.New(creds, aws.USEast)
}