github.com/darmach/terratest@v0.34.8-0.20210517103231-80931f95e3ff/modules/aws/account.go (about) 1 package aws 2 3 import ( 4 "errors" 5 "strings" 6 7 "github.com/aws/aws-sdk-go/aws" 8 "github.com/aws/aws-sdk-go/service/sts" 9 10 "github.com/gruntwork-io/terratest/modules/testing" 11 ) 12 13 // GetAccountId gets the Account ID for the currently logged in IAM User. 14 func GetAccountId(t testing.TestingT) string { 15 id, err := GetAccountIdE(t) 16 if err != nil { 17 t.Fatal(err) 18 } 19 return id 20 } 21 22 // GetAccountIdE gets the Account ID for the currently logged in IAM User. 23 func GetAccountIdE(t testing.TestingT) (string, error) { 24 stsClient, err := NewStsClientE(t, defaultRegion) 25 if err != nil { 26 return "", err 27 } 28 29 identity, err := stsClient.GetCallerIdentity(&sts.GetCallerIdentityInput{}) 30 if err != nil { 31 return "", err 32 } 33 34 return aws.StringValue(identity.Account), nil 35 } 36 37 // An IAM arn is of the format arn:aws:iam::123456789012:user/test. The account id is the number after arn:aws:iam::, 38 // so we split on a colon and return the 5th item. 39 func extractAccountIDFromARN(arn string) (string, error) { 40 arnParts := strings.Split(arn, ":") 41 42 if len(arnParts) < 5 { 43 return "", errors.New("Unrecognized format for IAM ARN: " + arn) 44 } 45 46 return arnParts[4], nil 47 } 48 49 // NewStsClientE creates a new STS client. 50 func NewStsClientE(t testing.TestingT, region string) (*sts.STS, error) { 51 sess, err := NewAuthenticatedSession(region) 52 if err != nil { 53 return nil, err 54 } 55 return sts.New(sess), nil 56 }