/
iam_instance_profile.go
93 lines (74 loc) · 2.73 KB
/
iam_instance_profile.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
package aws
import (
"github.com/Qovery/pleco/pkg/common"
"github.com/aws/aws-sdk-go/service/iam"
log "github.com/sirupsen/logrus"
"time"
)
type InstanceProfile struct {
common.CloudProviderResource
InstanceProfileName string
Roles []*iam.Role
}
func getInstanceProfiles(iamSession *iam.IAM, tagName string) []InstanceProfile {
var instanceProfiles []InstanceProfile
var token *string
for {
result, err := iamSession.ListInstanceProfiles(&iam.ListInstanceProfilesInput{
Marker: token,
})
if err != nil {
log.Error(err)
}
token = result.Marker
for _, instanceProfile := range result.InstanceProfiles {
essentialTags := common.GetEssentialTags(instanceProfile.Tags, tagName)
instanceProfiles = append(instanceProfiles, InstanceProfile{
CloudProviderResource: common.CloudProviderResource{
Identifier: *instanceProfile.InstanceProfileId,
Description: "IAM instance profile: " + *instanceProfile.InstanceProfileName,
CreationDate: instanceProfile.CreateDate.UTC(),
TTL: essentialTags.TTL,
Tag: essentialTags.Tag,
IsProtected: essentialTags.IsProtected,
},
InstanceProfileName: *instanceProfile.InstanceProfileName,
Roles: instanceProfile.Roles,
})
}
if result.Marker == nil {
break
}
}
return instanceProfiles
}
func getExpiredInstanceProfiles(iamSession *iam.IAM, options *AwsOptions) []InstanceProfile {
instanceProfiles := getInstanceProfiles(iamSession, options.TagName)
var expiredInstanceProfiles []InstanceProfile
for _, instanceProfile := range instanceProfiles {
if (len(instanceProfile.Roles) == 0 && time.Now().UTC().After(instanceProfile.CreationDate.Add(4*time.Hour))) || instanceProfile.IsResourceExpired(options.TagValue, options.DisableTTLCheck) {
expiredInstanceProfiles = append(expiredInstanceProfiles, instanceProfile)
}
}
return expiredInstanceProfiles
}
func DeleteExpiredInstanceProfiles(sessions *AWSSessions, options *AwsOptions) {
expiredInstanceProfiles := getExpiredInstanceProfiles(sessions.IAM, options)
count, start := common.ElemToDeleteFormattedInfos("expired instance profile", len(expiredInstanceProfiles), "Global")
log.Info(count)
if options.DryRun || len(expiredInstanceProfiles) == 0 {
return
}
log.Info(start)
for _, expiredInstanceProfile := range expiredInstanceProfiles {
_, err := sessions.IAM.DeleteInstanceProfile(
&iam.DeleteInstanceProfileInput{
InstanceProfileName: &expiredInstanceProfile.InstanceProfileName,
})
if err != nil {
log.Errorf("Can't delete instace profile %s : %s", expiredInstanceProfile.InstanceProfileName, err.Error())
} else {
log.Debugf("Instance profile %s deleted.", expiredInstanceProfile.InstanceProfileName)
}
}
}