diff --git a/sysvars/sysvars.go b/sysvars/sysvars.go index 4806cf04..cfd450f8 100644 --- a/sysvars/sysvars.go +++ b/sysvars/sysvars.go @@ -101,7 +101,7 @@ func Init(ll *logger.Logger, userVars map[string]string) error { hostname, err := os.Hostname() if err != nil { - return fmt.Errorf("utils.SystemVars: error getting local hostname: %v", err) + return fmt.Errorf("sysvars.Init(): error getting local hostname: %v", err) } sysVars["hostname"] = hostname @@ -110,6 +110,15 @@ func Init(ll *logger.Logger, userVars map[string]string) error { if err := gceVars(sysVars); err != nil { return err } + } else { + // Note: ec2Vars doesn't return an error when not running on AWS. We still + // ignore errors as we don't want other platforms to be impacted if + // behavior of the underlying AWS libraries changes. + // TODO: Add a function to check if running on AWS, and then stop ignoring + // errors from ec2Vars. + if err := ec2Vars(sysVars); err != nil { + l.Warningf("sysvars.Init(): error getting ec2 metadata, ignoring: %v", err) + } } for k, v := range userVars { diff --git a/sysvars/sysvars_ec2.go b/sysvars/sysvars_ec2.go new file mode 100644 index 00000000..a0137f65 --- /dev/null +++ b/sysvars/sysvars_ec2.go @@ -0,0 +1,54 @@ +// Copyright 2019 Google Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package sysvars + +import ( + "fmt" + + "github.com/aws/aws-sdk-go/aws/ec2metadata" + "github.com/aws/aws-sdk-go/aws/session" +) + +func ec2Vars(sysVars map[string]string) error { + s, err := session.NewSession() + if err != nil { + return fmt.Errorf("ec2Vars: could not create session %v", err) + } + + md := ec2metadata.New(s) + // Doing the availability check in module since we need a session + if md.Available() == false { + sysVars["EC2_METADATA_Available"] = "false" + return nil + } + + id, err := md.GetInstanceIdentityDocument() + if err != nil { + sysVars["EC2_METADATA_Available"] = "false" + return fmt.Errorf("ec2Vars: could not get instance document %v", err) + } + + sysVars["EC2_METADATA_Available"] = "true" + sysVars["EC2_AvailabilityZone"] = id.AvailabilityZone + sysVars["EC2_PrivateIP"] = id.PrivateIP + sysVars["EC2_Region"] = id.Region + sysVars["EC2_InstanceID"] = id.InstanceID + sysVars["EC2_InstanceType"] = id.InstanceType + sysVars["EC2_ImageID"] = id.ImageID + sysVars["EC2_KernelID"] = id.KernelID + sysVars["EC2_RamdiskID"] = id.RamdiskID + sysVars["EC2_Architecture"] = id.Architecture + return nil +}