Check ec2 instance metadata for region (#6025)

This commit is contained in:
Becca Petrin 2019-01-18 14:49:24 -08:00 committed by GitHub
parent 58dfd8aa68
commit 83e0c5e5e6
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -8,6 +8,7 @@ import (
"sync/atomic"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/ec2metadata"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/kms"
"github.com/aws/aws-sdk-go/service/kms/kmsiface"
@ -98,6 +99,21 @@ func (k *AWSKMSSeal) SetConfig(config map[string]string) (map[string]string, err
k.region = region
default:
k.region = "us-east-1"
// If available, get the region from EC2 instance metadata
sess, err := session.NewSession(nil)
if err != nil {
k.logger.Warn(fmt.Sprintf("unable to begin session: %s, defaulting region to %s", err, k.region))
break
}
// This will hang for ~10 seconds if the agent isn't running on an EC2 instance
region, err := ec2metadata.New(sess).Region()
if err != nil {
k.logger.Warn(fmt.Sprintf("unable to retrieve region from ec2 instance metadata: %s, defaulting region to %s", err, k.region))
break
}
k.region = region
}
// Check and set AWS access key, secret key, and session token