forked from gruntwork-io/terratest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
account.go
45 lines (36 loc) · 1.01 KB
/
account.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package aws
import (
"errors"
"strings"
"testing"
"github.com/aws/aws-sdk-go/service/iam"
)
// GetAccountId gets the Account ID for the currently logged in IAM User.
func GetAccountId(t *testing.T) string {
id, err := GetAccountIdE(t)
if err != nil {
t.Fatal(err)
}
return id
}
// GetAccountIdE gets the Account ID for the currently logged in IAM User.
func GetAccountIdE(t *testing.T) (string, error) {
iamClient, err := NewIamClientE(t, defaultRegion)
if err != nil {
return "", err
}
user, err := iamClient.GetUser(&iam.GetUserInput{})
if err != nil {
return "", err
}
return extractAccountIDFromARN(*user.User.Arn)
}
// An IAM arn is of the format arn:aws:iam::123456789012:user/test. The account id is the number after arn:aws:iam::,
// so we split on a colon and return the 5th item.
func extractAccountIDFromARN(arn string) (string, error) {
arnParts := strings.Split(arn, ":")
if len(arnParts) < 5 {
return "", errors.New("Unrecognized format for IAM ARN: " + arn)
}
return arnParts[4], nil
}