forked from rebuy-de/aws-nuke
-
Notifications
You must be signed in to change notification settings - Fork 0
/
account.go
95 lines (78 loc) · 2.25 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package awsutil
import (
"strings"
"github.com/aws/aws-sdk-go/service/iam"
"github.com/aws/aws-sdk-go/service/sts"
"github.com/dngferreira/aws-nuke/v2/pkg/config"
"github.com/pkg/errors"
)
type Account struct {
Credentials
id string
aliases []string
}
func NewAccount(creds Credentials, endpoints config.CustomEndpoints) (*Account, error) {
creds.CustomEndpoints = endpoints
account := Account{
Credentials: creds,
}
customStackSupportSTSAndIAM := true
if endpoints.GetRegion(DefaultRegionID) != nil {
if endpoints.GetURL(DefaultRegionID, "sts") == "" {
customStackSupportSTSAndIAM = false
} else if endpoints.GetURL(DefaultRegionID, "iam") == "" {
customStackSupportSTSAndIAM = false
}
}
if !customStackSupportSTSAndIAM {
account.id = "account-id-of-custom-region-" + DefaultRegionID
account.aliases = []string{account.id}
return &account, nil
}
defaultSession, err := account.NewSession(DefaultRegionID, "")
if err != nil {
return nil, errors.Wrapf(err, "failed to create default session in %s", DefaultRegionID)
}
identityOutput, err := sts.New(defaultSession).GetCallerIdentity(nil)
if err != nil {
return nil, errors.Wrap(err, "failed get caller identity")
}
globalSession, err := account.NewSession(GlobalRegionID, "")
if err != nil {
return nil, errors.Wrapf(err, "failed to create global session in %s", GlobalRegionID)
}
aliasesOutput, err := iam.New(globalSession).ListAccountAliases(nil)
if err != nil {
return nil, errors.Wrap(err, "failed get account alias")
}
aliases := []string{}
for _, alias := range aliasesOutput.AccountAliases {
if alias != nil {
aliases = append(aliases, *alias)
}
}
account.id = *identityOutput.Account
account.aliases = aliases
return &account, nil
}
func (a *Account) ID() string {
return a.id
}
func (a *Account) Alias() string {
return a.aliases[0]
}
func (a *Account) Aliases() []string {
return a.aliases
}
func (a *Account) ResourceTypeToServiceType(regionName, resourceType string) string {
customRegion := a.CustomEndpoints.GetRegion(regionName)
if customRegion == nil {
return "-" // standard public AWS.
}
for _, e := range customRegion.Services {
if strings.HasPrefix(strings.ToLower(resourceType), e.Service) {
return e.Service
}
}
return ""
}