Skip to content

Instantly share code, notes, and snippets.

@david-mcdonagh
Last active November 22, 2023 11:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save david-mcdonagh/8e4741d9b3f447a23bc3cbfa02368b70 to your computer and use it in GitHub Desktop.
Save david-mcdonagh/8e4741d9b3f447a23bc3cbfa02368b70 to your computer and use it in GitHub Desktop.
Go client to search KMS Keys in multiple profiles and mark keys that have tag ResourceIdentifier for deletion 'go run wd-aws-client.go <--dry-mode (optional> <profile_name> ...
package main
import (
"context"
"fmt"
"log"
"os"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/kms"
"github.com/aws/aws-sdk-go-v2/service/rds"
"github.com/aws/aws-sdk-go-v2/service/kms/types"
"github.com/aws/aws-sdk-go-v2/service/sts"
)
/*
Commands:
go run wd-aws-client.go --dry-mode mlsales custus1 custus2 custcanada1 custsingapore1 custus3 custsales custgermany1 mlengint s0003 s0004 s0005 s0006 s0008 s0009 s0010 s0001 s0002 wd101 wd10 wd102 wd103 wd105 wd106 wd99 wd12
go run wd-aws-client.go mlsales custus1 custus2 custcanada1 custsingapore1 custus3 custsales custgermany1 mlengint s0003 s0004 s0005 s0006 s0008 s0009 s0010 s0001 s0002 wd101 wd10 wd102 wd103 wd105 wd106 wd99 wd12
go run wd-aws-client.go mlsales-admin custus1-admin custus2-admin custcanada1-admin custsingapore1-admin custus3-admin custsales-admin custgermany1-admin mlengint-admin s0003-admin s0004-admin s0005-admin s0006-admin s0008-admin s0009-admin s0010-admin s0001-admin s0002-admin wd101-admin wd10-admin wd102-admin wd103-admin wd105-admin wd106-admin wd99-admin wd12-admin
*/
func main() {
ctx := context.TODO()
now := time.Now()
y, m, d := now.Date()
todayDate := fmt.Sprintf("%d-%d-%d", d, int(m), y)
var isDryMode bool
if len(os.Args) > 1 && os.Args[1] == "--dry-mode" {
isDryMode = true
log.Println("*** IMPORTANT - Executing in dry-mode = ", isDryMode, " Only listing keys. Nothing will be updated! ***")
}
var counter int // counter on number of keys
var totalKeyCount int
kmsKeyReports := make(map[string]string)
report := make(map[string]map[string]string)
for _, profile := range os.Args[1:] {
if os.Args[1] == "--dry-mode" {
continue
}
log.Println("*** Working Profile = ", profile)
// Using the SDK's default configuration, loading additional config
// and credentials values from the environment variables, shared
// credentials, and shared configuration files
cfg, err := config.LoadDefaultConfig(context.TODO(), config.WithRegion("us-west-2"), config.WithSharedConfigProfile(profile))
if err != nil {
log.Println(err)
continue
}
stgClient := sts.NewFromConfig(cfg)
identity, err := stgClient.GetCallerIdentity(ctx, &sts.GetCallerIdentityInput{})
if err != nil {
log.Println(err)
continue
}
log.Printf("Account: %s, Arn: %s", aws.ToString(identity.Account), aws.ToString(identity.Arn))
// Create an Amazon KMS service client
client := kms.NewFromConfig(cfg)
input := &kms.ListKeysInput{}
paginator := kms.NewListKeysPaginator(client, input)
totalKeyCount = 0
for {
keysResp, _ := paginator.NextPage(ctx)
// if err != nil {
// // log.Println(err)
// }
for _, key := range keysResp.Keys {
if key.KeyArn == nil {
continue
}
// describeResp, errDescribe := client.DescribeKey(ctx, &kms.DescribeKeyInput{KeyId: key.KeyArn})
// if errDescribe != nil {
// log.Fatal(errDescribe)
// }
listResTags := &kms.ListResourceTagsInput{
KeyId: aws.String(*key.KeyArn),
}
resTag, errLstTags := client.ListResourceTags(ctx, listResTags) // For each KMS retrieve tags
if errLstTags != nil {
//log.Println(errLstTags)
continue
}
for _, tag := range resTag.Tags {
if *tag.TagKey == "ResourceIdentifier" {
log.Println(*key.KeyArn, " ", *tag.TagKey, ":", *tag.TagValue)
if !isDryMode {
// Add tag with today date
resultTag, err := client.TagResource(ctx, &kms.TagResourceInput{ // adding additional tag to indicate its marking for deletion.
KeyId: aws.String(*key.KeyArn),
Tags: []types.Tag{
{
TagKey: aws.String("MarkDeletionOn"),
TagValue: aws.String(todayDate),
},
},
})
if err != nil {
log.Println("Got error tagging resource: ", err)
} else {
log.Println("Successfully Tag resource: ", resultTag)
}
// mark for deletion
deleteKey, err := client.ScheduleKeyDeletion(ctx, &kms.ScheduleKeyDeletionInput{
KeyId: aws.String(*key.KeyArn),
PendingWindowInDays: aws.Int32(7),
})
if err != nil {
log.Println("Got error scheduling delete key: ", err)
} else {
log.Println("Successfully scheduling delete key: ", deleteKey)
}
}
counter++
kmsKeyReports[*key.KeyArn] = *tag.TagValue
}
}
totalKeyCount++
}
if !paginator.HasMorePages() {
break
}
}
log.Println("Total number of KMS keys in profile ", totalKeyCount, " No marked for deletion: ", counter)
report[profile] = kmsKeyReports
// reset on each profile
counter = 0
kmsKeyReports = make(map[string]string)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment