Skip to content

Commit

Permalink
Merge pull request kubernetes-sigs#2217 from Shreya027/main
Browse files Browse the repository at this point in the history
Add code for acquiring region from env; Refactor code to reduce EC2 c…
  • Loading branch information
k8s-ci-robot authored Sep 20, 2021
2 parents 4749148 + 4744674 commit 2a1a0a3
Showing 1 changed file with 17 additions and 8 deletions.
25 changes: 17 additions & 8 deletions pkg/aws/cloud.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"github.com/aws/aws-sdk-go/aws/session"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
"os"
"sigs.k8s.io/aws-load-balancer-controller/pkg/aws/metrics"
"sigs.k8s.io/aws-load-balancer-controller/pkg/aws/services"
"sigs.k8s.io/aws-load-balancer-controller/pkg/aws/throttle"
Expand Down Expand Up @@ -44,14 +45,6 @@ type Cloud interface {
func NewCloud(cfg CloudConfig, metricsRegisterer prometheus.Registerer) (Cloud, error) {
metadataSess := session.Must(session.NewSession(aws.NewConfig()))
metadata := services.NewEC2Metadata(metadataSess)
if len(cfg.Region) == 0 {
region, err := metadata.Region()
if err != nil {
return nil, errors.Wrap(err, "failed to introspect region from EC2Metadata, specify --aws-region instead if EC2Metadata is unavailable")
}
cfg.Region = region
}

if len(cfg.VpcID) == 0 {
vpcId, err := metadata.VpcID()
if err != nil {
Expand All @@ -60,6 +53,22 @@ func NewCloud(cfg CloudConfig, metricsRegisterer prometheus.Registerer) (Cloud,
cfg.VpcID = vpcId
}

if len(cfg.Region) == 0 {
region := os.Getenv("AWS_DEFAULT_REGION")
if region == "" {
region = os.Getenv("AWS_REGION")
}

if region == ""{
err := (error)(nil)
region, err = metadata.Region()
if err != nil {
return nil, errors.Wrap(err, "failed to introspect region from EC2Metadata, specify --aws-region instead if EC2Metadata is unavailable")
}
}
cfg.Region = region
}

awsCFG := aws.NewConfig().WithRegion(cfg.Region).WithSTSRegionalEndpoint(endpoints.RegionalSTSEndpoint).WithMaxRetries(cfg.MaxRetries)
sess := session.Must(session.NewSession(awsCFG))
injectUserAgent(&sess.Handlers)
Expand Down

0 comments on commit 2a1a0a3

Please sign in to comment.