/
aws.go
65 lines (56 loc) · 1.63 KB
/
aws.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
package main
import (
"context"
"os"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/credentials/stscreds"
"github.com/aws/aws-sdk-go-v2/service/sts"
"github.com/crossplane/crossplane-runtime/pkg/errors"
)
const webIdentityTokenFileDefaultPath = "/var/run/secrets/upbound.io/provider/token"
func getWebidentityTokenFilePath() string {
if path := os.Getenv("AWS_WEB_IDENTITY_TOKEN_FILE"); path != "" {
return path
}
return webIdentityTokenFileDefaultPath
}
func initializeAWSSession(ctx context.Context, region, assumeRoleArn, assumeRoleWithWebIdentityArn string) (*aws.Config, error) {
cfg, _ := config.LoadDefaultConfig(ctx)
cfg.Region = region
stsclient := sts.NewFromConfig(cfg)
session, _ := config.LoadDefaultConfig(ctx)
var err error
if assumeRoleArn != "" {
session, err = config.LoadDefaultConfig(
ctx,
config.WithRegion(region),
config.WithCredentialsProvider(aws.NewCredentialsCache(
stscreds.NewAssumeRoleProvider(
stsclient,
assumeRoleArn,
)),
),
)
if err != nil {
return nil, errors.Wrap(err, "failed to load assumed role AWS config")
}
}
if assumeRoleWithWebIdentityArn != "" {
session, err = config.LoadDefaultConfig(
ctx,
config.WithRegion(region),
config.WithCredentialsProvider(aws.NewCredentialsCache(
stscreds.NewWebIdentityRoleProvider(
stsclient,
assumeRoleWithWebIdentityArn,
stscreds.IdentityTokenFile(getWebidentityTokenFilePath()),
)),
),
)
if err != nil {
return nil, errors.Wrap(err, "failed to load assumed with webidentity role AWS config")
}
}
return &session, nil
}