本文整理汇总了Golang中github.com/aws/aws-sdk-go/aws/ec2metadata.New函数的典型用法代码示例。如果您正苦于以下问题:Golang New函数的具体用法?Golang New怎么用?Golang New使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了New函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: 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
示例2: 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
示例3: TestEC2RoleProviderExpiryWindowIsExpired
func TestEC2RoleProviderExpiryWindowIsExpired(t *testing.T) {
server := initTestServer("2014-12-16T01:51:37Z", false)
defer server.Close()
p := &ec2rolecreds.EC2RoleProvider{
Client: ec2metadata.New(&ec2metadata.Config{Endpoint: aws.String(server.URL + "/latest")}),
ExpiryWindow: time.Hour * 1,
}
p.CurrentTime = func() time.Time {
return time.Date(2014, 12, 15, 0, 51, 37, 0, time.UTC)
}
assert.True(t, p.IsExpired(), "Expect creds to be expired before retrieve.")
_, err := p.Retrieve()
assert.Nil(t, err, "Expect no error")
assert.False(t, p.IsExpired(), "Expect creds to not be expired after retrieve.")
p.CurrentTime = func() time.Time {
return time.Date(2014, 12, 16, 0, 55, 37, 0, time.UTC)
}
assert.True(t, p.IsExpired(), "Expect creds to be expired.")
}
开发者ID:ManifoldMike,项目名称:coreos-kubernetes,代码行数:25,代码来源:ec2_role_provider_test.go
示例4: getRegion
func (p *amazon) getRegion() (string, error) {
if len(p.c.Region) == 0 {
meta := ec2metadata.New(&ec2metadata.Config{})
return meta.Region()
}
return p.c.Region, nil
}
开发者ID:roboll,项目名称:disco,代码行数:7,代码来源:aws.go
示例5: 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
示例6: 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
示例7: 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
示例8: 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
示例9: Retrieve
// Retrieve retrieves credentials from the EC2 service.
// Error will be returned if the request fails, or unable to extract
// the desired credentials.
func (m *EC2RoleProvider) Retrieve() (credentials.Value, error) {
if m.Client == nil {
m.Client = ec2metadata.New(nil)
}
credsList, err := requestCredList(m.Client)
if err != nil {
return credentials.Value{}, err
}
if len(credsList) == 0 {
return credentials.Value{}, awserr.New("EmptyEC2RoleList", "empty EC2 Role list", nil)
}
credsName := credsList[0]
roleCreds, err := requestCred(m.Client, credsName)
if err != nil {
return credentials.Value{}, err
}
m.SetExpiration(roleCreds.Expiration, m.ExpiryWindow)
return credentials.Value{
AccessKeyID: roleCreds.AccessKeyID,
SecretAccessKey: roleCreds.SecretAccessKey,
SessionToken: roleCreds.Token,
}, nil
}
开发者ID:ManifoldMike,项目名称:coreos-kubernetes,代码行数:31,代码来源:ec2_role_provider.go
示例10: TestGetUserData_Error
func TestGetUserData_Error(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
reader := strings.NewReader(`<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>404 - Not Found</title>
</head>
<body>
<h1>404 - Not Found</h1>
</body>
</html>`)
w.Header().Set("Content-Type", "text/html")
w.Header().Set("Content-Length", fmt.Sprintf("%d", reader.Len()))
w.WriteHeader(http.StatusNotFound)
io.Copy(w, reader)
}))
defer server.Close()
c := ec2metadata.New(unit.Session, &aws.Config{Endpoint: aws.String(server.URL + "/latest")})
resp, err := c.GetUserData()
assert.Error(t, err)
assert.Empty(t, resp)
aerr, ok := err.(awserr.Error)
assert.True(t, ok)
assert.Equal(t, "NotFoundError", aerr.Code())
}
开发者ID:xibz,项目名称:aws-sdk-go,代码行数:30,代码来源:api_test.go
示例11: Config
// Config returns a valid aws.Config object for access to AWS services, or
// an error if the authentication and region couldn't be resolved
func (c *AccessConfig) Config() (*aws.Config, error) {
var creds *credentials.Credentials
region, err := c.Region()
if err != nil {
return nil, err
}
config := aws.NewConfig().WithRegion(region).WithMaxRetries(11)
if c.ProfileName != "" {
profile, err := NewFromProfile(c.ProfileName)
if err != nil {
return nil, err
}
creds, err = profile.CredentialsFromProfile(config)
if err != nil {
return nil, err
}
} else {
sess := session.New(config)
creds = credentials.NewChainCredentials([]credentials.Provider{
&credentials.StaticProvider{Value: credentials.Value{
AccessKeyID: c.AccessKey,
SecretAccessKey: c.SecretKey,
SessionToken: c.Token,
}},
&credentials.EnvProvider{},
&credentials.SharedCredentialsProvider{Filename: "", Profile: ""},
&ec2rolecreds.EC2RoleProvider{
Client: ec2metadata.New(sess),
},
})
}
return config.WithCredentials(creds), nil
}
开发者ID:lvjp,项目名称:packer,代码行数:36,代码来源:access_config.go
示例12: 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 {}
}
开发者ID:BashtonLtd,项目名称:varnish-purge-proxy,代码行数:30,代码来源:varnish-purge-proxy.go
示例13: TestMetadataNotAvailable
func TestMetadataNotAvailable(t *testing.T) {
c := ec2metadata.New(nil)
available := c.Available()
assert.False(t, available)
}
开发者ID:jkakar,项目名称:aws-sdk-go,代码行数:7,代码来源:api_test.go
示例14: main
func main() {
meta := ec2metadata.New(session.New())
if meta.Available() == false {
fmt.Println("Not an EC2 instance or Metadata service unavailable")
os.Exit(2)
}
if len(os.Args) < 2 {
fmt.Println("Please supply an attribute to query or -h for help")
os.Exit(1)
}
if os.Args[1] == "-h" || os.Args[1] == "--help" {
showHelp(meta)
os.Exit(0)
}
var result string
var err error
if strings.ToLower(os.Args[1]) == "region" {
result, err = meta.Region()
} else {
result, err = meta.GetMetadata(strings.ToLower(os.Args[1]))
}
if err != nil {
fmt.Println("Problem querying metadata service.")
os.Exit(2)
}
fmt.Println(result)
}
开发者ID:louism517,项目名称:go-ec2meta,代码行数:35,代码来源:main.go
示例15: New
func New(debug bool) MetadataFetcher {
c := ec2metadata.Config{}
if debug {
c.LogLevel = aws.LogLevel(aws.LogDebug)
}
return ec2metadata.New(&c)
}
开发者ID:daichenge,项目名称:AWSnycast,代码行数:7,代码来源:instancemetadata.go
示例16: NewEC2Info
func NewEC2Info(route *router.Route) (EC2Info, error) {
_, skip_ec2 := route.Options[`NOEC2`]
if skip_ec2 || (os.Getenv(`NOEC2`) != "") {
return EC2Info{}, nil
}
// get my instance ID
mySession := session.New()
metadataSvc := ec2metadata.New(mySession)
if !metadataSvc.Available() {
log.Println("cloudwatch: WARNING EC2 Metadata service not available")
return EC2Info{}, nil
}
instance_id, err := metadataSvc.GetMetadata(`instance-id`)
if err != nil {
return EC2Info{}, fmt.Errorf("ERROR getting instance ID: %s", err)
}
region, err := metadataSvc.Region()
if err != nil {
return EC2Info{}, fmt.Errorf("ERROR getting EC2 region: %s", err)
}
return EC2Info{
InstanceID: instance_id,
Region: region,
}, nil
}
开发者ID:benton,项目名称:logspout-cloudwatch,代码行数:25,代码来源:ec2info.go
示例17: 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
示例18: New
func New(debug bool) MetadataFetcher {
sess := session.New()
if debug {
sess.Config.LogLevel = aws.LogLevel(aws.LogDebug)
}
return ec2metadata.New(sess)
}
开发者ID:venkat434,项目名称:AWSnycast,代码行数:7,代码来源:instancemetadata.go
示例19: getAWSConfig
func (g *S3Getter) getAWSConfig(region string, creds *credentials.Credentials) *aws.Config {
conf := &aws.Config{}
if creds == nil {
// Grab the metadata URL
metadataURL := os.Getenv("AWS_METADATA_URL")
if metadataURL == "" {
metadataURL = "http://169.254.169.254:80/latest"
}
creds = credentials.NewChainCredentials(
[]credentials.Provider{
&credentials.EnvProvider{},
&credentials.SharedCredentialsProvider{Filename: "", Profile: ""},
&ec2rolecreds.EC2RoleProvider{
Client: ec2metadata.New(session.New(&aws.Config{
Endpoint: aws.String(metadataURL),
})),
},
})
}
conf.Credentials = creds
if region != "" {
conf.Region = aws.String(region)
}
return conf
}
开发者ID:PagerDuty,项目名称:nomad,代码行数:28,代码来源:get_s3.go
示例20: getAwsMetadata
func getAwsMetadata(name string) string {
client := ec2metadata.New(session.New(&aws.Config{}))
data, err := client.GetMetadata(name)
if err != nil {
return info.UnknownInstance
}
return data
}
开发者ID:Clarifai,项目名称:kubernetes,代码行数:8,代码来源:aws.go
注:本文中的github.com/aws/aws-sdk-go/aws/ec2metadata.New函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论