github.com/google/cloudprober@v0.11.3/sysvars/sysvars_ec2.go (about)

     1  // Copyright 2019-2020 The Cloudprober Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package sysvars
    16  
    17  import (
    18  	"fmt"
    19  
    20  	"github.com/aws/aws-sdk-go/aws"
    21  	"github.com/aws/aws-sdk-go/aws/ec2metadata"
    22  	"github.com/aws/aws-sdk-go/aws/session"
    23  	"github.com/google/cloudprober/logger"
    24  )
    25  
    26  var ec2Vars = func(sysVars map[string]string, l *logger.Logger) (bool, error) {
    27  	s, err := session.NewSession(&aws.Config{
    28  		MaxRetries: aws.Int(0),
    29  	})
    30  	if err != nil {
    31  		// We ignore session errors. It's not clear what can cause them.
    32  		l.Warningf("sysvars_ec2: could not create AWS session: %v", err)
    33  		return false, nil
    34  	}
    35  
    36  	md := ec2metadata.New(s)
    37  	// Doing the availability check in module since we need a session
    38  	if md.Available() == false {
    39  		return false, nil
    40  	}
    41  
    42  	id, err := md.GetInstanceIdentityDocument()
    43  	if err != nil {
    44  		sysVars["EC2_METADATA_Available"] = "false"
    45  		return true, fmt.Errorf("sysvars_ec2: could not get instance identity document %v", err)
    46  	}
    47  
    48  	sysVars["EC2_METADATA_Available"] = "true"
    49  	sysVars["EC2_AvailabilityZone"] = id.AvailabilityZone
    50  	sysVars["EC2_PrivateIP"] = id.PrivateIP
    51  	sysVars["EC2_Region"] = id.Region
    52  	sysVars["EC2_InstanceID"] = id.InstanceID
    53  	sysVars["EC2_InstanceType"] = id.InstanceType
    54  	sysVars["EC2_ImageID"] = id.ImageID
    55  	sysVars["EC2_KernelID"] = id.KernelID
    56  	sysVars["EC2_RamdiskID"] = id.RamdiskID
    57  	sysVars["EC2_Architecture"] = id.Architecture
    58  	return true, nil
    59  }