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

Golang session.New函数代码示例

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

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



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

示例1: SetAwsInfo

func (t *TextDetail) SetAwsInfo(region string) error {
	meta := ec2metadata.New(session.New(), &aws.Config{Region: aws.String(region)})
	instance_id, err := meta.GetMetadata("instance-id")

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

	res, err := svc.DescribeInstances(nil)
	if err != nil {
		return err
	}

	tag_name := ""

	for _, r := range res.Reservations {
		for _, i := range r.Instances {
			if *i.InstanceId == instance_id {
				tag_name = *i.Tags[0].Value
			}
		}
	}

	t.AwsInstanceId = instance_id
	t.AwsTagName = tag_name

	return nil
}
开发者ID:ngc224,项目名称:loose-watcher,代码行数:26,代码来源:main.go


示例2: initAWS

func initAWS() {
	defer Track("initAWS", Now(), debugOut)

	AWSSession = session.New()

	// Region
	if GlobalConfig.Get("awsRegion") != "" {
		// CLI trumps
		AWSSession.Config.Region = aws.String(GlobalConfig.Get("awsRegion"))
	} else if os.Getenv("AWS_REGION") == "" {
		// Grab it from this EC2 instace
		region, err := ec2metadata.New(session.New()).Region()
		if err != nil {
			fmt.Printf("Cannot set AWS region: '%v'\n", err)
			os.Exit(1)
		}
		AWSSession.Config.Region = aws.String(region)
	}

	// Creds
	if GlobalConfig.Get("awsAccessKey") != "" && GlobalConfig.Get("awsSecretKey") != "" {
		// CLI trumps
		creds := credentials.NewStaticCredentials(
			GlobalConfig.Get("awsAccessKey"),
			GlobalConfig.Get("awsSecretKey"),
			"")
		AWSSession.Config.Credentials = creds
	}

}
开发者ID:cognusion,项目名称:post2s3,代码行数:30,代码来源:aws.go


示例3: NewEBSService

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

	s := &ebsService{}
	s.metadataClient = ec2metadata.New(session.New())
	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(session.New(), config)

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


示例4: NewAwsAsgEbs

func NewAwsAsgEbs(maxRetries int) *AwsAsgEbs {
	awsAsgEbs := &AwsAsgEbs{}

	metadata := ec2metadata.New(session.New())

	region, err := metadata.Region()
	if err != nil {
		log.WithFields(log.Fields{"error": err}).Fatal("Failed to get region from instance metadata")
	}
	log.WithFields(log.Fields{"region": region}).Info("Setting region")
	awsAsgEbs.Region = region

	availabilityZone, err := metadata.GetMetadata("placement/availability-zone")
	if err != nil {
		log.WithFields(log.Fields{"error": err}).Fatal("Failed to get availability zone from instance metadata")
	}
	log.WithFields(log.Fields{"az": availabilityZone}).Info("Setting availability zone")
	awsAsgEbs.AvailabilityZone = availabilityZone

	instanceId, err := metadata.GetMetadata("instance-id")
	if err != nil {
		log.WithFields(log.Fields{"error": err}).Fatal("Failed to get instance id from instance metadata")
	}
	log.WithFields(log.Fields{"instance_id": instanceId}).Info("Setting instance id")
	awsAsgEbs.InstanceId = instanceId

	awsAsgEbs.AwsConfig = aws.NewConfig().
		WithRegion(region).
		WithCredentials(ec2rolecreds.NewCredentials(session.New())).
		WithMaxRetries(maxRetries)

	return awsAsgEbs
}
开发者ID:fstehle,项目名称:asg-ebs,代码行数:33,代码来源:main.go


示例5: NewDynamoModule

// here, support a function that maps a given redis key to a dynamodb table key and value field
func NewDynamoModule(keymap KeyMapper) *DynamoModule {

	module := &DynamoModule{}
	cfgdir := "/etc"
	cfg := &module.config
	ok := logging.ReadModuleConfig(cfg, cfgdir, "dynamo") || logging.ReadModuleConfig(cfg, ".", "dynamo")

	sess := session.New(&aws.Config{Region: aws.String("ap-southeast-1")})

	if !ok {
		log.Println("failed to read dynamo config, using defaults")
	} else {
		sess = session.New(&aws.Config{
			Region:     aws.String(cfg.Server.Region),
			Endpoint:   aws.String(cfg.Server.Endpoint),
			DisableSSL: aws.Bool(cfg.Server.DisableSSL),
		})
	}

	module.client = dynamodb.New(sess)
	if keymap != nil {
		module.keyMapper = keymap
	} else {
		module.keyMapper = module.defaultMapper
	}

	if cfg.Server.CacheDuration > 0 {
		logging.Debug.Println("activiating cache, TTL", cfg.Server.CacheDuration)
		module.cache = cache.NewMemoryWithTTL(time.Duration(cfg.Server.CacheDuration) * time.Second)
	}

	return module
}
开发者ID:qzaidi,项目名称:redamo,代码行数:34,代码来源:dynamo.go


示例6: Connect

func (c *CloudWatch) Connect() error {
	Config := &aws.Config{
		Region: aws.String(c.Region),
		Credentials: credentials.NewChainCredentials(
			[]credentials.Provider{
				&ec2rolecreds.EC2RoleProvider{Client: ec2metadata.New(session.New())},
				&credentials.EnvProvider{},
				&credentials.SharedCredentialsProvider{},
			}),
	}

	svc := cloudwatch.New(session.New(Config))

	params := &cloudwatch.ListMetricsInput{
		Namespace: aws.String(c.Namespace),
	}

	_, err := svc.ListMetrics(params) // Try a read-only call to test connection.

	if err != nil {
		log.Printf("cloudwatch: Error in ListMetrics API call : %+v \n", err.Error())
	}

	c.svc = svc

	return err
}
开发者ID:skwong2,项目名称:telegraf,代码行数:27,代码来源:cloudwatch.go


示例7: main

func main() {
	kingpin.Parse()

	me := ec2metadata.New(session.New(), &aws.Config{})
	region, err := me.Region()
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	cw := cloudwatch.New(session.New(&aws.Config{Region: aws.String(region)}))
	as := autoscaling.New(session.New(&aws.Config{Region: aws.String(region)}))

	// Get the name of this instance.
	instance, err := me.GetMetadata("instance-id")
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	log.Printf("Instance: %s", instance)

	// Check if this instance is in an auto scaling group.
	gps, err := as.DescribeAutoScalingInstances(&autoscaling.DescribeAutoScalingInstancesInput{
		InstanceIds: []*string{
			aws.String(instance),
		},
	})
	if err == nil && len(gps.AutoScalingInstances) > 0 {
		group = *gps.AutoScalingInstances[0].AutoScalingGroupName
		log.Printf("AutoScaling group: %s", group)
	}

	// Loop and send to the backend.
	limiter := time.Tick(time.Second * 60)
	for {
		<-limiter

		// Submit all the values.
		for _, mn := range strings.Split(*cliMetrics, ",") {
			m, err := metric.New(mn)
			if err != nil {
				log.Printf("Cannot find metric: %s" + mn)
				continue
			}

			v, err := m.Value()
			if err != nil {
				log.Println("Cannot get metric.")
			}

			// Send the instance metrics.
			Send(cw, "InstanceId", instance, m.Name(), v)

			// Send the autoscaling.
			if group != "" {
				Send(cw, "AutoScalingGroupName", group, m.Name(), v)
			}
		}
	}
}
开发者ID:nickschuch,项目名称:metrics,代码行数:60,代码来源:main.go


示例8: main

func main() {
	kingpin.Version("2.1.0")
	kingpin.Parse()

	sl, err := syslog.New(syslog.LOG_NOTICE|syslog.LOG_LOCAL0, "[varnish-purge-proxy]")
	defer sl.Close()
	if err != nil {
		log.Println("Error writing to syslog")
	} else {
		log.SetFlags(0)
		log.SetOutput(sl)
	}

	if len(*tags) == 0 {
		fmt.Println("No tags specified")
		return
	}

	region, err = ec2metadata.New(session.New()).Region()
	if err != nil {
		log.Printf("Unable to retrieve the region from the EC2 instance %v\n", err)
	}

	// Set up access to ec2
	svc := ec2.New(session.New(), &aws.Config{Region: &region})

	go serveHTTP(*port, *listen, svc)

	select {}
}
开发者ID:BashtonLtd,项目名称:varnish-purge-proxy,代码行数:30,代码来源:varnish-purge-proxy.go


示例9: discoverEc2Hosts

// discoverEc2Hosts searches an AWS region, returning a list of instance ips
// where EC2TagKey = EC2TagValue
func (c *Config) discoverEc2Hosts(logger *log.Logger) ([]string, error) {
	config := c.RetryJoinEC2

	ec2meta := ec2metadata.New(session.New())
	if config.Region == "" {
		logger.Printf("[INFO] agent: No EC2 region provided, querying instance metadata endpoint...")
		identity, err := ec2meta.GetInstanceIdentityDocument()
		if err != nil {
			return nil, err
		}
		config.Region = identity.Region
	}

	awsConfig := &aws.Config{
		Region: &config.Region,
		Credentials: credentials.NewChainCredentials(
			[]credentials.Provider{
				&credentials.StaticProvider{
					Value: credentials.Value{
						AccessKeyID:     config.AccessKeyID,
						SecretAccessKey: config.SecretAccessKey,
					},
				},
				&credentials.EnvProvider{},
				&credentials.SharedCredentialsProvider{},
				defaults.RemoteCredProvider(*(defaults.Config()), defaults.Handlers()),
			}),
	}

	svc := ec2.New(session.New(), awsConfig)

	resp, err := svc.DescribeInstances(&ec2.DescribeInstancesInput{
		Filters: []*ec2.Filter{
			{
				Name: aws.String("tag:" + config.TagKey),
				Values: []*string{
					aws.String(config.TagValue),
				},
			},
		},
	})

	if err != nil {
		return nil, err
	}

	var servers []string
	for i := range resp.Reservations {
		for _, instance := range resp.Reservations[i].Instances {
			// Terminated instances don't have the PrivateIpAddress field
			if instance.PrivateIpAddress != nil {
				servers = append(servers, *instance.PrivateIpAddress)
			}
		}
	}

	return servers, nil
}
开发者ID:luizbafilho,项目名称:fusis,代码行数:60,代码来源:command.go


示例10: newS3Client

// newS3Client returns S3 service client
func newS3Client(cfg *aws.Config) *s3Client {
	return &s3Client{
		region: *cfg.Region,
		client: s3.New(session.New(cfg)),
		uploader: s3manager.NewUploader(session.New(cfg), func(u *s3manager.Uploader) {
			u.PartSize = 64 * 1024 * 1024
		}),
	}
}
开发者ID:lucmichalski,项目名称:s3secrets,代码行数:10,代码来源:s3.go


示例11: newConfigProvider

func newConfigProvider(c *cli.Context) client.ConfigProvider {
	p := session.New()

	if c.Bool(FlagAWSDebug) {
		config := &aws.Config{}
		config.WithLogLevel(1)
		p = session.New(config)
	}

	return p
}
开发者ID:frewsxcv,项目名称:empire,代码行数:11,代码来源:factories.go


示例12: NewKWriter

func NewKWriter(awsArn, awsRegion, stream *string, retries int) *KWriter {
	s := session.New(&aws.Config{
		Credentials: stscreds.NewCredentials(session.New(&aws.Config{}), *awsArn),
		Region:      awsRegion,
	})
	client := kinesis.New(s)
	return &KWriter{
		Client:     client,
		MaxRetries: retries,
		StreamName: stream,
	}
}
开发者ID:stojg,项目名称:classis,代码行数:12,代码来源:kinesis.go


示例13: NewAWSCloud

func NewAWSCloud(region string, tags map[string]string) (*AWSCloud, error) {
	c := &AWSCloud{Region: region}

	config := aws.NewConfig().WithRegion(region)
	c.EC2 = ec2.New(session.New(), config)
	c.IAM = iam.New(session.New(), config)
	c.ELB = elb.New(session.New(), config)
	c.Autoscaling = autoscaling.New(session.New(), config)
	c.Route53 = route53.New(session.New(), config)

	c.tags = tags
	return c, nil
}
开发者ID:crohling,项目名称:kops,代码行数:13,代码来源:aws_cloud.go


示例14: NewS3

func NewS3(filename, profile, region string) *S3 {
	var creds *credentials.Credentials
	if _, err := os.Stat(filename); err == nil {
		log.Printf("Connecting to AWS using credentials from '%s'", filename)
		creds = credentials.NewSharedCredentials(filename, profile)
	} else {
		log.Printf("AWS credentials file '%s' dosen't exists, I will be using EC2 Role credentials", filename)
		sess := session.New()
		creds = credentials.NewCredentials(&ec2rolecreds.EC2RoleProvider{Client: ec2metadata.New(sess)})
	}
	sess := session.New(&aws.Config{Credentials: creds, Region: aws.String(region)})
	return &S3{svc: s3.New(sess)}
}
开发者ID:dzlab,项目名称:qbench,代码行数:13,代码来源:aws.go


示例15: NewS3Client

func NewS3Client() *S3Client {
	var svc s3iface.S3API
	if log.IsDebug {
		svc = s3.New(session.New(), aws.NewConfig().WithLogLevel(aws.LogDebug))
	} else {
		svc = s3.New(session.New())
	}
	return &S3Client{
		svc:        svc,
		uploader:   newS3Uploader(svc),
		downloader: newS3Downloader(svc),
	}
}
开发者ID:varung,项目名称:droot,代码行数:13,代码来源:s3.go


示例16: CreateImageRepo

// CreateImageRepo create a repository for the image on amazon's ECR(EC2 Container Repository)
// if it doesn't exist as repository needs to be present before pushing and image into it.
func CreateImageRepo(reponame string, params map[string]string) error {
	var (
		accessKey  string
		secretKey  string
		regionName string
		ok         bool
	)

	accessKey, ok = params["accesskey"]
	if !ok {
		accessKey = ""
	}
	secretKey, ok = params["secretkey"]
	if !ok {
		secretKey = ""
	}
	regionName, ok = params["region"]
	if !ok || fmt.Sprint(regionName) == "" {
		return fmt.Errorf("No region parameter provided")
	}
	region := fmt.Sprint(regionName)
	creds := credentials.NewChainCredentials([]credentials.Provider{
		&credentials.StaticProvider{
			Value: credentials.Value{
				AccessKeyID:     accessKey,
				SecretAccessKey: secretKey,
			},
		},
		&credentials.EnvProvider{},
		&credentials.SharedCredentialsProvider{},
		&ec2rolecreds.EC2RoleProvider{Client: ec2metadata.New(session.New())},
	})
	awsConfig := aws.NewConfig()
	awsConfig.WithCredentials(creds)
	awsConfig.WithRegion(region)
	svc := ecr.New(session.New(awsConfig))

	repoInput := &ecr.CreateRepositoryInput{
		RepositoryName: aws.String(reponame),
	}

	_, err := svc.CreateRepository(repoInput)
	if err != nil {
		if s3Err, ok := err.(awserr.Error); ok && s3Err.Code() == "RepositoryAlreadyExistsException" {
			return nil
		}
		return err
	}
	return nil
}
开发者ID:bacongobbler,项目名称:builder,代码行数:52,代码来源:image_repo.go


示例17: Info

//TODO: validate cluster
func (c *Cluster) Info() (*ClusterInfo, error) {
	resources, err := getStackResources(cloudformation.New(session.New(c.aws)), c.stackName())
	if err != nil {
		return nil, err
	}

	info, err := mapStackResourcesToClusterInfo(ec2.New(session.New(c.aws)), resources)
	if err != nil {
		return nil, err
	}

	info.Name = c.cfg.ClusterName
	return info, nil
}
开发者ID:colhom,项目名称:coreos-kubernetes,代码行数:15,代码来源:cluster.go


示例18: Run

func (input *Sqs3Input) Run(runner pipeline.InputRunner,
    helper pipeline.PluginHelper) error {

    // initialize
    input.runner = runner
    input.sqs = sqs.New(session.New())
    input.s3 = s3.New(session.New())
    queue_url, err := get_queue(input.sqs, input.SqsQueue)
    if err != nil { return err }
    input.queue_url = queue_url
    //input.hostname = helper.PipelineConfig().Hostname()
    tickChan := runner.Ticker()
    sRunner := runner.NewSplitterRunner("")
    if !sRunner.UseMsgBytes() {
        sRunner.SetPackDecorator(input.packDecorator)
    }
    defer sRunner.Done()

    for {
        select {
        case <-input.stop:
            return nil
        case <-tickChan:
        }

        receipt_handle, bucket, key, err := receive_from_queue(input.sqs, input.queue_url)
        if err != nil {
            runner.LogError(fmt.Errorf("Error reading queue: %s", err.Error()))
            continue
        }

        o, _, err := get_object(input.s3, bucket, key)
        if err != nil {
            runner.LogError(fmt.Errorf("Error opening file: %s", err.Error()))
            if aws_err := awserr.Error(err); aws_err != nil {
                f aws_err.Code == "NoSuchBucket" or aws_err.Code == "NoSuchKey" {
                    delete_message(input.sqs, input.queue_url, receipt_handle)
                }
            }
            continue
        }
        for err == nil {
            err = sRunner.SplitStream(o, nil)
            if err != io.EOF && err != nil {
                runner.LogError(fmt.Errorf("Error reading file: %s", err.Error()))
            }
        }
        o.Close()
    }
}
开发者ID:relud,项目名称:heka_plugin_sqs3,代码行数:50,代码来源:sqs3_input.go


示例19: handleDescribeInstances

func handleDescribeInstances(req *cwRequest, c *middleware.Context) {
	sess := session.New()
	creds := credentials.NewChainCredentials(
		[]credentials.Provider{
			&credentials.EnvProvider{},
			&credentials.SharedCredentialsProvider{Filename: "", Profile: req.DataSource.Database},
			&ec2rolecreds.EC2RoleProvider{Client: ec2metadata.New(sess), ExpiryWindow: 5 * time.Minute},
		})

	cfg := &aws.Config{
		Region:      aws.String(req.Region),
		Credentials: creds,
	}

	svc := ec2.New(session.New(cfg), cfg)

	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
	}

	var resp ec2.DescribeInstancesOutput
	err := svc.DescribeInstancesPages(params,
		func(page *ec2.DescribeInstancesOutput, lastPage bool) bool {
			reservations, _ := awsutil.ValuesAtPath(page, "Reservations")
			for _, reservation := range reservations {
				resp.Reservations = append(resp.Reservations, reservation.(*ec2.Reservation))
			}
			return !lastPage
		})
	if err != nil {
		c.JsonApiErr(500, "Unable to call AWS API", err)
		return
	}

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


示例20: TestOutputService9ProtocolTestSupportsHeaderMapsCase1

func TestOutputService9ProtocolTestSupportsHeaderMapsCase1(t *testing.T) {
	sess := session.New()
	svc := NewOutputService9ProtocolTest(sess, &aws.Config{Endpoint: aws.String("https://test")})

	buf := bytes.NewReader([]byte("{}"))
	req, out := svc.OutputService9TestCaseOperation1Request(nil)
	req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}}

	// set headers
	req.HTTPResponse.Header.Set("Content-Length", "10")
	req.HTTPResponse.Header.Set("X-Bam", "boo")
	req.HTTPResponse.Header.Set("X-Foo", "bar")

	// unmarshal response
	restjson.UnmarshalMeta(req)
	restjson.Unmarshal(req)
	assert.NoError(t, req.Error)

	// assert response
	assert.NotNil(t, out) // ensure out variable is used
	assert.Equal(t, "10", *out.AllHeaders["Content-Length"])
	assert.Equal(t, "boo", *out.AllHeaders["X-Bam"])
	assert.Equal(t, "bar", *out.AllHeaders["X-Foo"])
	assert.Equal(t, "boo", *out.PrefixedHeaders["Bam"])
	assert.Equal(t, "bar", *out.PrefixedHeaders["Foo"])

}
开发者ID:mattmcclean,项目名称:amazon-ecs-cli,代码行数:27,代码来源:unmarshal_test.go



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Golang session.NewSession函数代码示例发布时间:2022-05-24
下一篇:
Golang service.Request类代码示例发布时间: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