From 0b13d44a2391b45b52b1e80f5fd29148834fa4da Mon Sep 17 00:00:00 2001 From: Dany Garcia Date: Mon, 23 Nov 2020 09:21:22 -0800 Subject: [PATCH] exporting reusable validatekmskey function --- builder/amazon/chroot/builder.go | 21 +-------------------- builder/amazon/common/ami_config.go | 4 ++-- 2 files changed, 3 insertions(+), 22 deletions(-) diff --git a/builder/amazon/chroot/builder.go b/builder/amazon/chroot/builder.go index 23b7c1ada..e06740e50 100644 --- a/builder/amazon/chroot/builder.go +++ b/builder/amazon/chroot/builder.go @@ -350,7 +350,7 @@ func (b *Builder) Prepare(raws ...interface{}) ([]string, []string, error) { if b.config.RootVolumeEncryptBoot.False() { errs = packer.MultiErrorAppend( errs, errors.New("If you have set root_volume_kms_key_id, root_volume_encrypt_boot must also be true.")) - } else if b.config.RootVolumeEncryptBoot.True() && !validateKmsKey(b.config.RootVolumeKmsKeyId) { + } else if b.config.RootVolumeEncryptBoot.True() && !awscommon.ValidateKmsKey(b.config.RootVolumeKmsKeyId) { errs = packer.MultiErrorAppend( errs, fmt.Errorf("%q is not a valid KMS Key Id.", b.config.RootVolumeKmsKeyId)) } @@ -537,22 +537,3 @@ func (b *Builder) Run(ctx context.Context, ui packersdk.Ui, hook packersdk.Hook) return artifact, nil } - -func validateKmsKey(kmsKey string) (valid bool) { - kmsKeyIdPattern := `[a-f0-9-]+$` - aliasPattern := `alias/[a-zA-Z0-9:/_-]+$` - kmsArnStartPattern := `^arn:aws(-us-gov)?:kms:([a-z]{2}-(gov-)?[a-z]+-\d{1})?:(\d{12}):` - if regexp.MustCompile(fmt.Sprintf("^%s", kmsKeyIdPattern)).MatchString(kmsKey) { - return true - } - if regexp.MustCompile(fmt.Sprintf("^%s", aliasPattern)).MatchString(kmsKey) { - return true - } - if regexp.MustCompile(fmt.Sprintf("%skey/%s", kmsArnStartPattern, kmsKeyIdPattern)).MatchString(kmsKey) { - return true - } - if regexp.MustCompile(fmt.Sprintf("%s%s", kmsArnStartPattern, aliasPattern)).MatchString(kmsKey) { - return true - } - return false -} diff --git a/builder/amazon/common/ami_config.go b/builder/amazon/common/ami_config.go index d224b91df..801160bf3 100644 --- a/builder/amazon/common/ami_config.go +++ b/builder/amazon/common/ami_config.go @@ -215,7 +215,7 @@ func (c *AMIConfig) Prepare(accessConfig *AccessConfig, ctx *interpolate.Context } for _, kmsKey := range kmsKeys { - if !validateKmsKey(kmsKey) { + if !ValidateKmsKey(kmsKey) { errs = append(errs, fmt.Errorf("%q is not a valid KMS Key Id.", kmsKey)) } } @@ -289,7 +289,7 @@ func (c *AMIConfig) prepareRegions(accessConfig *AccessConfig) (errs []error) { } // See https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CopyImage.html -func validateKmsKey(kmsKey string) (valid bool) { +func ValidateKmsKey(kmsKey string) (valid bool) { kmsKeyIdPattern := `[a-f0-9-]+$` aliasPattern := `alias/[a-zA-Z0-9:/_-]+$` kmsArnStartPattern := `^arn:aws(-us-gov)?:kms:([a-z]{2}-(gov-)?[a-z]+-\d{1})?:(\d{12}):`