本文整理汇总了Golang中github.com/aws/aws-sdk-go/aws/session.New函数的典型用法代码示例。如果您正苦于以下问题:Golang New函数的具体用法?Golang New怎么用?Golang New使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了New函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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
}
示例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
}
}
示例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
}
示例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
}
示例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
}
示例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
}
示例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)
}
}
}
}
示例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: ®ion})
go serveHTTP(*port, *listen, svc)
select {}
}
示例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
}
示例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
}),
}
}
示例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
}
示例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,
}
}
示例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
}
示例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)}
}
示例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),
}
}