-
Notifications
You must be signed in to change notification settings - Fork 1
/
organization.go
100 lines (88 loc) · 2.15 KB
/
organization.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
96
97
98
99
100
package acos
import (
"context"
"errors"
"github.com/aws/aws-sdk-go-v2/service/organizations"
"github.com/aws/aws-sdk-go-v2/service/organizations/types"
)
var (
// AWS clients
organizationsClient *organizations.Client
)
func init() {
organizationsClient = organizations.NewFromConfig(cfg)
}
// Account wraps up AWS Organization Account struct.
type Account types.Account
type Accounts map[string]Account // map[accountId]Account
// AccountIds returns a list of account IDs.
func (a *Accounts) AccountIds() []string {
accountIds := make([]string, len(*a))
i := 0
for key := range *a {
accountIds[i] = key
i++
}
return accountIds
}
// ListAccounts returns a list of AWS accounts within an AWS Organization organization.
func ListAccounts(ctx context.Context) (Accounts, error) {
var nextToken *string
accnts := make(map[string]Account)
for {
out, err := organizationsClient.ListAccounts(
ctx,
&organizations.ListAccountsInput{
NextToken: nextToken,
},
)
if err != nil {
return nil, err
}
for _, acc := range out.Accounts {
accnts[*acc.Id] = Account(acc)
}
nextToken = out.NextToken
if nextToken == nil {
break
}
}
return accnts, nil
}
// ListAccountsByOu returns a list of direct-children AWS accounts of an AWS Organization OU.
func ListAccountsByOu(ctx context.Context, ouId string) (Accounts, error) {
var nextToken *string
accnts := make(map[string]Account)
for {
out, err := organizationsClient.ListAccountsForParent(
ctx,
&organizations.ListAccountsForParentInput{
ParentId: &ouId,
NextToken: nextToken,
},
)
if err != nil {
return nil, err
}
for _, acc := range out.Accounts {
accnts[*acc.Id] = Account(acc)
}
nextToken = out.NextToken
if nextToken == nil {
break
}
}
return accnts, nil
}
func IsOrganizationEnabled(err error) bool {
var errType *types.AWSOrganizationsNotInUseException
return !errors.As(err, &errType)
}
func HasPermissionToOrganizationsApi(err error) bool {
var errType *types.AccessDeniedException
return !errors.As(err, &errType)
}
func OuExists(err error) bool {
var errType *types.ParentNotFoundException
return !errors.As(err, &errType)
}