forked from docker/machine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
awscredentials.go
63 lines (53 loc) · 1.72 KB
/
awscredentials.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
package amazonec2
import (
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
)
type awsCredentials interface {
Credentials() *credentials.Credentials
}
type ProviderFactory interface {
NewStaticProvider(id, secret, token string) credentials.Provider
}
type defaultAWSCredentials struct {
AccessKey string
SecretKey string
SessionToken string
providerFactory ProviderFactory
fallbackProvider awsCredentials
}
func NewAWSCredentials(id, secret, token string) *defaultAWSCredentials {
creds := defaultAWSCredentials{
AccessKey: id,
SecretKey: secret,
SessionToken: token,
fallbackProvider: &AwsDefaultCredentialsProvider{},
providerFactory: &defaultProviderFactory{},
}
return &creds
}
func (c *defaultAWSCredentials) Credentials() *credentials.Credentials {
providers := []credentials.Provider{}
if c.AccessKey != "" && c.SecretKey != "" {
providers = append(providers, c.providerFactory.NewStaticProvider(c.AccessKey, c.SecretKey, c.SessionToken))
}
if c.fallbackProvider != nil {
fallbackCreds, err := c.fallbackProvider.Credentials().Get()
if err == nil {
providers = append(providers, &credentials.StaticProvider{Value: fallbackCreds})
}
}
return credentials.NewChainCredentials(providers)
}
type AwsDefaultCredentialsProvider struct{}
func (c *AwsDefaultCredentialsProvider) Credentials() *credentials.Credentials {
return session.New().Config.Credentials
}
type defaultProviderFactory struct{}
func (c *defaultProviderFactory) NewStaticProvider(id, secret, token string) credentials.Provider {
return &credentials.StaticProvider{Value: credentials.Value{
AccessKeyID: id,
SecretAccessKey: secret,
SessionToken: token,
}}
}