/
cloudwatch_logs.go
82 lines (72 loc) · 2.44 KB
/
cloudwatch_logs.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
package helpers
import (
"fmt"
"log"
"os"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/cloudwatchlogs"
)
// GetCloudwatchGroups getting all cloudwatch groups in a region
func GetCloudwatchGroups(region string) []*cloudwatchlogs.LogGroup {
log.Printf("Running on region: %v", region)
awsSession, _ := InitAwsSession(region)
svc := cloudwatchlogs.New(awsSession)
// default empty input before retrieving next tokens
input := &cloudwatchlogs.DescribeLogGroupsInput{}
// get all cloudwatch log groups
result, err := svc.DescribeLogGroups(input)
if err != nil {
log.Println(err)
os.Exit(1)
}
cloudwatchGroups := result.LogGroups
for result.NextToken != nil {
input = &cloudwatchlogs.DescribeLogGroupsInput{
NextToken: result.NextToken,
}
result, err = svc.DescribeLogGroups(input)
if err != nil {
log.Println(err)
os.Exit(1)
}
// for _, group := range result.LogGroups {
// cloudwatchGroups = append(cloudwatchGroups, group)
// }
cloudwatchGroups = append(cloudwatchGroups, result.LogGroups...)
}
return cloudwatchGroups
}
// SetCloudwatchGroupsExpiry Set expiry on a cloudwatch group
func SetCloudwatchGroupsExpiry(region string, retention int64, cloudwatchGroups []*cloudwatchlogs.LogGroup, apply bool, override bool) {
awsSession, _ := InitAwsSession(region)
svc := cloudwatchlogs.New(awsSession)
var totalLogByteSize int64
noRetentionSet := false
for _, group := range cloudwatchGroups {
if group.RetentionInDays == nil || override {
totalLogByteSize = totalLogByteSize + *group.StoredBytes
noRetentionSet = true
if apply && override {
// set input filter
input := &cloudwatchlogs.PutRetentionPolicyInput{
LogGroupName: aws.String(*group.LogGroupName),
RetentionInDays: aws.Int64(retention),
}
// put retention policy
_, err := svc.PutRetentionPolicy(input)
if err != nil {
log.Println(err)
return
}
log.Printf("Retention policy for %s was set to %v", *group.LogGroupName, retention)
} else {
log.Printf("Group %s retention policy would be set to %d (size is %v Bytes), --yes to apply", *group.LogGroupName, retention, *group.StoredBytes)
}
}
}
if noRetentionSet {
log.Printf("Region %s total log size:", region)
log.Printf("Total log size in with no retention policy is: %v bytes", totalLogByteSize)
}
fmt.Println("=====================================================================================================")
}