• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang ec2.New函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/aws/aws-sdk-go/service/ec2.New函数的典型用法代码示例。如果您正苦于以下问题:Golang New函数的具体用法?Golang New怎么用?Golang New使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了New函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: AllSecurityGroups

// AllSecurityGroups describes every instance in the requested regions
// *SecurityGroups are created for each *ec2.SecurityGroup
// and are passed to a channel
func AllSecurityGroups() chan *SecurityGroup {
	ch := make(chan *SecurityGroup, len(config.Regions))
	// waitgroup for all regions
	wg := sync.WaitGroup{}
	for _, region := range config.Regions {
		wg.Add(1)
		go func(region string) {
			defer wg.Done()
			// add region to waitgroup
			api := ec2.New(sess, aws.NewConfig().WithRegion(region))
			resp, err := api.DescribeSecurityGroups(&ec2.DescribeSecurityGroupsInput{})
			for _, sg := range resp.SecurityGroups {
				ch <- NewSecurityGroup(region, sg)
			}
			if err != nil {
				// probably should do something here...
				log.Error(err.Error())
			}
		}(region)
	}
	go func() {
		// in a separate goroutine, wait for all regions to finish
		// when they finish, close the chan
		wg.Wait()
		close(ch)

	}()
	return ch
}
开发者ID:milescrabill,项目名称:reaper,代码行数:32,代码来源:aws.go


示例2: handleDescribeInstances

func handleDescribeInstances(req *cwRequest, c *middleware.Context) {
	svc := ec2.New(&aws.Config{Region: aws.String(req.Region)})

	reqParam := &struct {
		Parameters struct {
			Filters     []*ec2.Filter `json:"filters"`
			InstanceIds []*string     `json:"instanceIds"`
		} `json:"parameters"`
	}{}
	json.Unmarshal(req.Body, reqParam)

	params := &ec2.DescribeInstancesInput{}
	if len(reqParam.Parameters.Filters) > 0 {
		params.Filters = reqParam.Parameters.Filters
	}
	if len(reqParam.Parameters.InstanceIds) > 0 {
		params.InstanceIds = reqParam.Parameters.InstanceIds
	}

	resp, err := svc.DescribeInstances(params)
	if err != nil {
		c.JsonApiErr(500, "Unable to call AWS API", err)
		return
	}

	c.JSON(200, resp)
}
开发者ID:wangy1931,项目名称:grafana,代码行数:27,代码来源:cloudwatch.go


示例3: clientEC2

// clientEC2 creates a client to interact with AWS EC2 API.
func (b *backend) clientEC2(s logical.Storage, region string) (*ec2.EC2, error) {
	b.configMutex.RLock()
	if b.EC2ClientsMap[region] != nil {
		defer b.configMutex.RUnlock()
		// If the client object was already created, return it.
		return b.EC2ClientsMap[region], nil
	}

	// Release the read lock and acquire the write lock.
	b.configMutex.RUnlock()
	b.configMutex.Lock()
	defer b.configMutex.Unlock()

	// If the client gets created while switching the locks, return it.
	if b.EC2ClientsMap[region] != nil {
		return b.EC2ClientsMap[region], nil
	}

	// Create a AWS config object using a chain of providers.
	awsConfig, err := b.getClientConfig(s, region)
	if err != nil {
		return nil, err
	}

	// Create a new EC2 client object, cache it and return the same.
	b.EC2ClientsMap[region] = ec2.New(session.New(awsConfig))
	return b.EC2ClientsMap[region], nil
}
开发者ID:GauntletWizard,项目名称:vault,代码行数:29,代码来源:client.go


示例4: NewEbsVolumeDriver

func NewEbsVolumeDriver() (VolumeDriver, error) {
	d := &ebsVolumeDriver{
		volumes: make(map[string]*ebsVolume),
	}

	ec2sess := session.New()
	d.ec2meta = ec2metadata.New(ec2sess)

	// Fetch AWS information, validating along the way.
	if !d.ec2meta.Available() {
		return nil, errors.New("Not running on an EC2 instance.")
	}
	var err error
	if d.awsInstanceId, err = d.ec2meta.GetMetadata("instance-id"); err != nil {
		return nil, err
	}
	if d.awsRegion, err = d.ec2meta.Region(); err != nil {
		return nil, err
	}
	if d.awsAvailabilityZone, err =
		d.ec2meta.GetMetadata("placement/availability-zone"); err != nil {
		return nil, err
	}

	d.ec2 = ec2.New(ec2sess, &aws.Config{Region: aws.String(d.awsRegion)})

	// Print some diagnostic information and then return the driver.
	log("Auto-detected EC2 information:\n")
	log("\tInstanceId        : %v\n", d.awsInstanceId)
	log("\tRegion            : %v\n", d.awsRegion)
	log("\tAvailability Zone : %v\n", d.awsAvailabilityZone)
	return d, nil
}
开发者ID:joeduffy,项目名称:blocker,代码行数:33,代码来源:ebs_driver.go


示例5: getTags

func getTags(region *string, instanceId *string) []string {
	output := []string{}

	service := ec2.New(&aws.Config{
		Region: region,
	})

	instances, err := service.DescribeInstances(&ec2.DescribeInstancesInput{
		InstanceIds: []*string{instanceId},
	})
	if err != nil {
		log.Fatal(err)
	}

	if len(instances.Reservations) > 1 {
		// more than one reservation isn't expected
		log.Fatal("Not Expected: Reservations > 1")
	}
	for _, res := range instances.Reservations {
		if len(res.Instances) > 1 {
			// more than one instance isn't expected
			log.Fatal("Not Expected: Instances > 1")
		}
		for _, instance := range res.Instances {
			for _, tag := range instance.Tags {
				output = append(output, *tag.Key+"="+*tag.Value)
			}
		}
	}
	return output
}
开发者ID:roboll,项目名称:aws-fleet-metadata,代码行数:31,代码来源:main.go


示例6: New

func New(config Config) *Client {
	credentials := credentials.NewStaticCredentials(config.AccessKey, config.SecretKey, "")
	sdkConfig := &aws.Config{
		Credentials: credentials,
		Region:      aws.String(config.RegionName),
	}

	endpointOverrides := config.EndpointOverrides
	if endpointOverrides == nil {
		endpointOverrides = &Endpoints{}
	}

	route53Client := route53.New(sdkConfig.Merge(&aws.Config{MaxRetries: aws.Int(7), Endpoint: aws.String(endpointOverrides.Route53)}))
	ec2Client := ec2.New(sdkConfig.Merge(&aws.Config{MaxRetries: aws.Int(7), Endpoint: aws.String(endpointOverrides.EC2)}))
	s3Client := s3.New(sdkConfig.Merge(&aws.Config{MaxRetries: aws.Int(7), Endpoint: aws.String(endpointOverrides.S3), S3ForcePathStyle: aws.Bool(true)}))
	cloudformationClient := cloudformation.New(sdkConfig.Merge(&aws.Config{MaxRetries: aws.Int(7), Endpoint: aws.String(endpointOverrides.Cloudformation)}))

	return &Client{
		EC2:            ec2Client,
		S3:             s3Client,
		Route53:        route53Client,
		Cloudformation: cloudformationClient,
		// HostedZoneID:   config.HostedZoneID,
		// HostedZoneName: config.HostedZoneName,
		Bucket: config.Bucket,
	}
}
开发者ID:rosenhouse,项目名称:bosh-classroom,代码行数:27,代码来源:aws_client.go


示例7: GetSnapshotsByTag

// GetSnapshotsByTag returns a slice of EBS Snapshots that match the provided region and Tag key/value
func GetSnapshotsByTag(region, key, value string) (Snapshots, error) {
	svc := ec2.New(session.New(&aws.Config{Region: aws.String(region)}))

	params := &ec2.DescribeSnapshotsInput{
		OwnerIds: []*string{aws.String("self")},
		Filters: []*ec2.Filter{
			{
				Name: aws.String("tag:" + key),
				Values: []*string{
					aws.String(value),
				},
			},
		},
	}

	result, err := svc.DescribeSnapshots(params)

	snapList := make(Snapshots, len(result.Snapshots))
	for i, snapshot := range result.Snapshots {
		snapList[i].Marshal(snapshot, region)
	}

	if len(snapList) == 0 {
		return snapList, errors.New("No Snapshot found with tag [" + key + "] of [" + value + "] in [" + region + "].")
	}

	return snapList, err
}
开发者ID:murdinc,项目名称:awsm,代码行数:29,代码来源:snapshots.go


示例8: FindDefaultVPC

// FindDefaultVPC looks for the default VPC in a given region
// and returns its ID if found.
func FindDefaultVPC(region string) (string, error) {
	ec2Service := ec2.New(&aws.Config{Region: aws.String(region)})

	// Call the DescribeInstances Operation
	resp, err := ec2Service.DescribeVpcs(&ec2.DescribeVpcsInput{
		Filters: []*ec2.Filter{
			{
				Name:   aws.String("isDefault"),
				Values: []*string{aws.String("true")},
			},
		},
	})
	if err != nil {
		return "", err
	}

	if len(resp.Vpcs) == 0 {
		return "", util.Errorf("no default VPC found in region %s", region)
	}
	if len(resp.Vpcs) > 1 {
		return "", util.Errorf("found %d default Vpcs in region %s", len(resp.Vpcs), region)
	}

	return *resp.Vpcs[0].VpcId, nil
}
开发者ID:nvanbenschoten,项目名称:cockroach-prod,代码行数:27,代码来源:vpc.go


示例9: main

// This example will list instances with a filter
//
// Usage:
// filter_ec2_by_tag <name_filter>
func main() {
	sess, err := session.NewSession()
	if err != nil {
		log.Fatalf("failed to create session %v\n", err)
	}

	nameFilter := os.Args[1]
	awsRegion := "us-east-1"
	svc := ec2.New(sess, &aws.Config{Region: aws.String(awsRegion)})
	fmt.Printf("listing instances with tag %v in: %v\n", nameFilter, awsRegion)
	params := &ec2.DescribeInstancesInput{
		Filters: []*ec2.Filter{
			{
				Name: aws.String("tag:Name"),
				Values: []*string{
					aws.String(strings.Join([]string{"*", nameFilter, "*"}, "")),
				},
			},
		},
	}
	resp, err := svc.DescribeInstances(params)
	if err != nil {
		fmt.Println("there was an error listing instances in", awsRegion, err.Error())
		log.Fatal(err.Error())
	}
	fmt.Printf("%+v\n", *resp)
}
开发者ID:xibz,项目名称:aws-sdk-go,代码行数:31,代码来源:filter_ec2_by_tag.go


示例10: main

func main() {
	svc := ec2.New(session.New(), &aws.Config{Region: aws.String("sa-east-1")})
	resp, err := svc.DescribeInstances(nil)
	if err != nil {
		panic(err)
	}
	table := tablewriter.NewWriter(os.Stdout)
	table.SetHeader([]string{"Tag Name", "Instance Id", "Instance Type", "AZ", "IP", "Status"})

	for _, res := range resp.Reservations {
		for _, instance := range res.Instances {
			var tag_name string
			for _, tag := range instance.Tags {
				if *tag.Key == "Name" {
					tag_name = *tag.Value
				}
			}
			table.Append([]string{
				tag_name,
				*instance.InstanceId,
				*instance.InstanceType,
				*instance.Placement.AvailabilityZone,
				*instance.PrivateIpAddress,
				*instance.State.Name,
			})

		}
	}
	table.Render()

}
开发者ID:jaibheem,项目名称:trash,代码行数:31,代码来源:ec2_info.go


示例11: main

func main() {
	defaults.DefaultConfig.Region = aws.String("us-west-2")
	svc := ec2.New(nil)

	var filters = []*ec2.Filter{
		&ec2.Filter{
			Name:   aws.String("instance-state-name"),
			Values: []*string{aws.String("running")},
		},
	}

	request := ec2.DescribeInstancesInput{Filters: filters}
	result, err := svc.DescribeInstances(&request)
	if err != nil {
		log.Fatalf("Error getting description: %s", err)
	}

	for _, reservation := range result.Reservations {
		for _, instance := range reservation.Instances {
			var id = *instance.InstanceId
			var publicIp = *instance.PublicIpAddress
			var privateIp = *instance.PrivateIpAddress
			var keyName = *instance.KeyName
			fmt.Printf("%s\t%s\t%s\t%s\n", id, publicIp, privateIp, keyName)
		}
	}
}
开发者ID:rendon,项目名称:gosnippets,代码行数:27,代码来源:get_running_instances.go


示例12: Stop

func Stop(config *Config) {
	svc := ec2.New(session.New())

	for i := range config.EC2 {
		fmt.Println("Stopping ", config.EC2[i].Name)
		//fmt.Println(config.EC2[i].InstanceType)

		instances := getInstancesByName(svc, config.EC2[i].Name)
		for k := range instances {
			if *instances[k].State.Name == "terminated" {
				//fmt.Println("Instance is terminated:", *instances[k].InstanceId)
			} else {
				fmt.Println("Instance will be shutdown: ", *instances[k].InstanceId)
				instanceids := []*string{instances[k].InstanceId}
				sii := ec2.StopInstancesInput{InstanceIds: instanceids}
				_, err := svc.StopInstances(&sii)
				if err != nil {
					panic(err)
				}
				fmt.Println("Stopped instance ", *instances[k].InstanceId)

			}
		}
	}

}
开发者ID:jamesunger,项目名称:saws,代码行数:26,代码来源:saws.go


示例13: GetImagesByTag

// GetImagesByTag returns a slice of Amazon Machine Images given the provided region, and tag key/values
func GetImagesByTag(region, key, value string) (Images, error) {
	svc := ec2.New(session.New(&aws.Config{Region: aws.String(region)}))

	params := &ec2.DescribeImagesInput{
		Owners: []*string{aws.String("self")},
		Filters: []*ec2.Filter{
			{
				Name: aws.String("tag:" + key),
				Values: []*string{
					aws.String(value),
				},
			},
		},
	}

	result, err := svc.DescribeImages(params)

	imgList := make(Images, len(result.Images))
	for i, image := range result.Images {
		imgList[i].Marshal(image, region)
	}

	if len(imgList) == 0 {
		return imgList, errors.New("No Images found with tag [" + key + "] of [" + value + "] in [" + region + "].")
	}

	return imgList, err

}
开发者ID:murdinc,项目名称:awsm,代码行数:30,代码来源:images.go


示例14: copyImage

// private function without prompts
func copyImage(image Image, region string, dryRun bool) (*ec2.CopyImageOutput, error) {

	svc := ec2.New(session.New(&aws.Config{Region: aws.String(region)}))

	// Copy image to the destination region
	params := &ec2.CopyImageInput{
		Name:          aws.String(image.Name),
		SourceImageId: aws.String(image.ImageID),
		SourceRegion:  aws.String(image.Region),
		DryRun:        aws.Bool(dryRun),
		//ClientToken: aws.String("String"),
		//Description: aws.String("String"),
		//Encrypted:   aws.Bool(true),
		//KmsKeyId:    aws.String("String"),
	}
	copyImageResp, err := svc.CopyImage(params)

	if err != nil {
		if awsErr, ok := err.(awserr.Error); ok {
			return copyImageResp, errors.New(awsErr.Message())
		}
	}

	return copyImageResp, err
}
开发者ID:murdinc,项目名称:awsm,代码行数:26,代码来源:images.go


示例15: GetRunningInstances

// GetRunningInstances returns the list of running instances.
func GetRunningInstances() ([]Instance, error) {
	var svc = ec2.New(session.New(), nil)

	request := ec2.DescribeInstancesInput{
		Filters: []*ec2.Filter{
			&ec2.Filter{
				Name:   aws.String("instance-state-name"),
				Values: []*string{aws.String("running")},
			},
		},
	}
	resp, err := svc.DescribeInstances(&request)
	if err != nil {
		return nil, err
	}

	var instances = make([]Instance, 0)
	for _, res := range resp.Reservations {
		for _, ins := range res.Instances {
			var tag = ""
			if len(ins.Tags) > 0 {
				tag = *ins.Tags[0].Value
			}
			var i = Instance{
				ID:        *ins.InstanceId,
				PublicIP:  *ins.PublicIpAddress,
				PrivateIP: *ins.PrivateIpAddress,
				Tag:       tag,
			}
			instances = append(instances, i)
		}
	}
	return instances, nil
}
开发者ID:rendon,项目名称:insman,代码行数:35,代码来源:api.go


示例16: NewEBSService

func NewEBSService() (*ebsService, error) {
	var err error

	s := &ebsService{}
	s.metadataClient = ec2metadata.New(nil)
	if !s.isEC2Instance() {
		return nil, fmt.Errorf("Not running on an EC2 instance")
	}

	s.InstanceID, err = s.metadataClient.GetMetadata("instance-id")
	if err != nil {
		return nil, err
	}

	s.Region, err = s.metadataClient.Region()
	if err != nil {
		return nil, err
	}

	s.AvailabilityZone, err = s.metadataClient.GetMetadata("placement/availability-zone")
	if err != nil {
		return nil, err
	}

	config := aws.NewConfig().WithRegion(s.Region)
	s.ec2Client = ec2.New(config)

	return s, nil
}
开发者ID:PaulCharlton,项目名称:convoy,代码行数:29,代码来源:ebs_service.go


示例17: Run

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: &key, Value: &value})
			}

			regionconn := ec2.New(&aws.Config{
				Credentials: ec2conn.Config.Credentials,
				Region:      region,
			})
			_, err := regionconn.CreateTags(&ec2.CreateTagsInput{
				Resources: []*string{&ami},
				Tags:      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
}
开发者ID:henrysher,项目名称:packer,代码行数:34,代码来源:step_create_tags.go


示例18: amiRegionCopy

// amiRegionCopy does a copy for the given AMI to the target region and
// returns the resulting ID or error.
func amiRegionCopy(state multistep.StateBag, config *AccessConfig, imageId string,
	target string, source string) (string, error) {

	// Connect to the region where the AMI will be copied to
	awsConfig, err := config.Config()
	if err != nil {
		return "", err
	}
	awsConfig.Region = target

	regionconn := ec2.New(awsConfig)
	resp, err := regionconn.CopyImage(&ec2.CopyImageInput{
		SourceRegion:  &source,
		SourceImageID: &imageId,
	})

	if err != nil {
		return "", fmt.Errorf("Error Copying AMI (%s) to region (%s): %s",
			imageId, target, 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, err)
	}

	return *resp.ImageID, nil
}
开发者ID:henrysher,项目名称:packer,代码行数:37,代码来源:step_ami_region_copy.go


示例19: GetRegionSnapshots

// GetRegionSnapshots returns a list of a regions Snapshots into the provided Snapshots slice that match the provided search term and optional completed flag
func GetRegionSnapshots(region string, snapList *Snapshots, search string, completed bool) error {
	svc := ec2.New(session.New(&aws.Config{Region: aws.String(region)}))
	result, err := svc.DescribeSnapshots(&ec2.DescribeSnapshotsInput{OwnerIds: []*string{aws.String("self")}})

	if err != nil {
		return err
	}

	snap := make(Snapshots, len(result.Snapshots))
	for i, snapshot := range result.Snapshots {
		snap[i].Marshal(snapshot, region)
	}

	if search != "" {
		term := regexp.MustCompile(search)
	Loop:
		for i, in := range snap {
			rInst := reflect.ValueOf(in)

			for k := 0; k < rInst.NumField(); k++ {
				sVal := rInst.Field(k).String()

				if term.MatchString(sVal) && ((completed && snap[i].State == "completed") || !completed) {
					*snapList = append(*snapList, snap[i])
					continue Loop
				}
			}
		}
	} else {
		*snapList = append(*snapList, snap[:]...)
	}

	return nil
}
开发者ID:murdinc,项目名称:awsm,代码行数:35,代码来源:snapshots.go


示例20: main

func main() {
	svc := ec2.New(session.New(), &aws.Config{Region: aws.String("us-east-1")})

	// Call the DescribeInstances Operation
	resp, err := svc.DescribeInstances(nil)
	if err != nil {
		panic(err)
	}

	fmt.Println("> Number of reservation sets: ", len(resp.Reservations))

	for idx := range resp.Reservations {
		for _, inst := range resp.Reservations[idx].Instances {
			// for each instance lets parse out the info we want
			instance := parseInstanceInfo(inst)
			fmt.Println("Processing: ", instance.name, " (", instance.ip, ")")
			scanHost(&instance)
			instance.parsedXmlScanResult, err = nmap.Parse([]byte(instance.rawXmlScanResult))
			if err != nil {
				fmt.Println(err.Error())
				return
			}
			parseOpenPorts(&instance)
			describeSecurityGroups(svc, &instance)
			//fmt.Println(instance.securityGroups)
		}
	}
}
开发者ID:Shadowssong,项目名称:go-aws-scanner,代码行数:28,代码来源:scanner.go



注:本文中的github.com/aws/aws-sdk-go/service/ec2.New函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang ec2.DescribeInstancesOutput类代码示例发布时间:2022-05-24
下一篇:
Golang dynamodbstreams.New函数代码示例发布时间:2022-05-24
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap