Skip to content

Instantly share code, notes, and snippets.

@niski84
Last active May 15, 2024 23:22
Show Gist options
  • Save niski84/e0a72cb87ede69e286764be58b152e52 to your computer and use it in GitHub Desktop.
Save niski84/e0a72cb87ede69e286764be58b152e52 to your computer and use it in GitHub Desktop.
re-encrypt aws secret using kms key name and secret path
package awsapi
import (
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/kms"
)
// LookupKMSKeyArn fetches the full ARN of a KMS key based on its alias name.
func LookupKMSKeyArn(sess *session.Session, keyAlias string) (string, error) {
svc := kms.New(sess)
input := &kms.ListAliasesInput{}
var keyID string
err := svc.ListAliasesPages(input, func(page *kms.ListAliasesOutput, lastPage bool) bool {
for _, alias := range page.Aliases {
if *alias.AliasName == fmt.Sprintf("alias/%s", keyAlias) {
keyID = *alias.TargetKeyId
return false // Stop paging as we found our key
}
}
return true // Continue paging
})
if err != nil {
return "", fmt.Errorf("failed to list aliases: %w", err)
}
if keyID == "" {
return "", fmt.Errorf("alias %s not found", keyAlias)
}
// Once we have the key ID, fetch the full ARN
describeInput := &kms.DescribeKeyInput{
KeyId: aws.String(keyID),
}
result, err := svc.DescribeKey(describeInput)
if err != nil {
return "", fmt.Errorf("failed to describe key: %w", err)
}
return *result.KeyMetadata.Arn, nil
}
package main
import (
"log"
"github.com/aws/aws-sdk-go/aws/session"
"path/to/your/project/awsapi"
)
func main() {
sess, err := session.NewSession(&aws.Config{Region: aws.String("us-west-2")})
if err != nil {
log.Fatalf("Failed to create AWS session: %v", err)
}
keyArn, err := awsapi.LookupKMSKeyArn(sess, "yourKeyAlias")
if err != nil {
log.Fatalf("Failed to find KMS key ARN: %v", err)
}
log.Printf("KMS Key ARN: %s", keyArn)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment