-
Notifications
You must be signed in to change notification settings - Fork 0
/
rotator.go
94 lines (77 loc) · 2.33 KB
/
rotator.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
package ark
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/iam"
)
// Create new access/secret keys
// following the best practice AWS
func CreateNewAccessKey(sess *session.Session, userName string) (*iam.AccessKey, error) {
svc := iam.New(sess)
listAccessKeys, err := svc.ListAccessKeys(&iam.ListAccessKeysInput{
UserName: aws.String(userName),
})
if err != nil {
return nil, err
}
err = deleteInactiveKey(svc, userName, listAccessKeys)
if err != nil {
return nil, err
}
result, err := svc.CreateAccessKey(&iam.CreateAccessKeyInput{
UserName: aws.String(userName),
})
if err != nil {
return nil, err
}
return result.AccessKey, nil
}
// if All active then delete the first key
// if found inactive then delete it
// for avoid creating new keys failure if IAM user is equal MAxIAMUser
// final result must be one accesKey with Inactive status
func deleteInactiveKey(svc *iam.IAM, userName string, listAccessKeys *iam.ListAccessKeysOutput) error {
var foundInactive bool
if len(listAccessKeys.AccessKeyMetadata) == MaxIAMUser {
for _, accessKey := range listAccessKeys.AccessKeyMetadata {
if *accessKey.Status == Inactive {
foundInactive = true
_, err := svc.DeleteAccessKey(&iam.DeleteAccessKeyInput{
AccessKeyId: accessKey.AccessKeyId,
UserName: aws.String(userName),
})
if err != nil {
return err
}
}
if *accessKey.Status == Active {
deactivateKey(svc, userName, *accessKey.AccessKeyId)
}
}
if !foundInactive {
_, err := svc.DeleteAccessKey(&iam.DeleteAccessKeyInput{
AccessKeyId: listAccessKeys.AccessKeyMetadata[0].AccessKeyId,
UserName: aws.String(userName),
})
deactivateKey(svc, userName, *listAccessKeys.AccessKeyMetadata[1].AccessKeyId)
if err != nil {
return err
}
}
} else if len(listAccessKeys.AccessKeyMetadata) == 1 {
deactivateKey(svc, userName, *listAccessKeys.AccessKeyMetadata[0].AccessKeyId)
}
return nil
}
// before creating new one deactivate last key
func deactivateKey(svc *iam.IAM, userName string, accessKeyId string) error {
_, err := svc.UpdateAccessKey(&iam.UpdateAccessKeyInput{
UserName: aws.String(userName),
Status: aws.String(Inactive),
AccessKeyId: aws.String(accessKeyId),
})
if err != nil {
return err
}
return nil
}