Skip to content

Commit 20deb45

Browse files
committed
Use sts GetCallerIdentity as final fallback for AWS AccountId
1 parent ee4f1ec commit 20deb45

File tree

1 file changed

+20
-2
lines changed

1 file changed

+20
-2
lines changed

pkg/config/config.go

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@ import (
1717
"errors"
1818
"net/url"
1919

20+
"github.com/aws/aws-sdk-go/aws/session"
21+
"github.com/aws/aws-sdk-go/service/sts"
2022
"github.com/jaypipes/envutil"
2123
flag "github.com/spf13/pflag"
2224
"go.uber.org/zap/zapcore"
@@ -135,13 +137,29 @@ func (cfg *Config) SetupLogger() {
135137
ctrlrt.SetLogger(zap.New(zap.UseFlagOptions(&zapOptions)))
136138
}
137139

140+
// PopulateAccountIdIfMissing uses sts GetCallerIdentity API to find
141+
// AWS AccountId when Config.AccountId is empty
142+
func (cfg *Config) PopulateAccountIdIfMissing() error {
143+
if cfg.AccountID == "" {
144+
// use sts to find AWS AccountId
145+
session := session.Must(session.NewSession())
146+
client := sts.New(session)
147+
res, err := client.GetCallerIdentity(&sts.GetCallerIdentityInput{})
148+
if err == nil {
149+
cfg.AccountID = *res.Account
150+
}
151+
return err
152+
}
153+
return nil
154+
}
155+
138156
// Validate ensures the options are valid
139157
func (cfg *Config) Validate() error {
140158
if cfg.AccountID == "" {
141-
return errors.New("unable to start service controller as account ID is nil. Please pass --aws-account-id flag")
159+
return errors.New("unable to start service controller as account ID is missing. Please pass --aws-account-id flag or set AWS_ACCOUNT_ID environment variable")
142160
}
143161
if cfg.Region == "" {
144-
return errors.New("unable to start service controller as AWS region is nil. Please pass --aws-region flag")
162+
return errors.New("unable to start service controller as AWS region is missing. Please pass --aws-region flag or set AWS_REGION environment variable")
145163
}
146164

147165
if cfg.EndpointURL != "" {

0 commit comments

Comments
 (0)