本文整理匯總了Golang中github.com/aws/aws-sdk-go/aws/ec2metadata.New函數的典型用法代碼示例。如果您正苦於以下問題:Golang New函數的具體用法?Golang New怎麽用?Golang New使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了New函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的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
}
示例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
}
示例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.")
}
示例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
}
示例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)
}
}
}
}
示例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
}
示例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
}
示例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
}
}
示例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
}
示例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())
}
示例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
}
示例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 {}
}
示例13: TestMetadataNotAvailable
func TestMetadataNotAvailable(t *testing.T) {
c := ec2metadata.New(nil)
available := c.Available()
assert.False(t, available)
}
示例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)
}
示例15: New
func New(debug bool) MetadataFetcher {
c := ec2metadata.Config{}
if debug {
c.LogLevel = aws.LogLevel(aws.LogDebug)
}
return ec2metadata.New(&c)
}