-
Notifications
You must be signed in to change notification settings - Fork 2
/
assume.go
79 lines (71 loc) · 1.85 KB
/
assume.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
// Cross account logic, forked from https://maori.geek.nz/assuming-roles-in-aws-with-go-aeeb28fab418
package main
import (
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials/stscreds"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/aws/aws-sdk-go/service/organizations"
)
// Clients Struct to store the session with custom parameters
type Clients struct {
session *session.Session
configs map[string]*aws.Config
}
// Session Func to start a session
func (c Clients) Session() *session.Session {
if c.session != nil {
return c.session
}
sess := session.Must(session.NewSession())
c.session = sess
return sess
}
// Config custom func
func (c Clients) Config(
region *string,
accountID *string,
role *string) *aws.Config {
// return no config for nil inputs
if accountID == nil || region == nil || role == nil {
return nil
}
arn := fmt.Sprintf(
"arn:aws:iam::%v:role/%v",
*accountID,
*role,
)
// include region in cache key otherwise concurrency errors
key := fmt.Sprintf("%v::%v", *region, arn)
// check for cached config
if c.configs != nil && c.configs[key] != nil {
return c.configs[key]
}
// new creds
creds := stscreds.NewCredentials(c.Session(), arn)
// new config
config := aws.NewConfig().
WithCredentials(creds).
WithRegion(*region).
WithMaxRetries(10)
if c.configs == nil {
c.configs = map[string]*aws.Config{}
}
c.configs[key] = config
return config
}
// Organization Create client
func (c *Clients) Organization(
region string,
accountID string,
role string) *organizations.Organizations {
return organizations.New(c.Session(), c.Config(®ion, &accountID, &role))
}
// EC2 Create client
func (c *Clients) EC2(
region string,
accountID string,
role string) *ec2.EC2 {
return ec2.New(c.Session(), c.Config(®ion, &accountID, &role))
}