From 6694eabebd8b9d9eaca08f94a566d74723d4e8a0 Mon Sep 17 00:00:00 2001 From: Malte Poll Date: Wed, 3 May 2023 11:07:47 +0200 Subject: [PATCH] cli: allow any well formatted zone in iam create --- cli/internal/cmd/iamcreate.go | 29 +++++++++++++++++------------ cli/internal/cmd/iamcreate_test.go | 2 +- 2 files changed, 18 insertions(+), 13 deletions(-) diff --git a/cli/internal/cmd/iamcreate.go b/cli/internal/cmd/iamcreate.go index cb3c48d6e..fe3d1b04c 100644 --- a/cli/internal/cmd/iamcreate.go +++ b/cli/internal/cmd/iamcreate.go @@ -402,18 +402,9 @@ func (c *awsIAMCreator) parseFlagsAndSetupConfig(cmd *cobra.Command, flags iamFl zone: zone, } - if strings.HasPrefix(zone, "eu-central-1") { - flags.aws.region = "eu-central-1" - } else if strings.HasPrefix(zone, "eu-west-1") { - flags.aws.region = "eu-west-1" - } else if strings.HasPrefix(zone, "eu-west-3") { - flags.aws.region = "eu-west-3" - } else if strings.HasPrefix(zone, "us-east-2") { - flags.aws.region = "us-east-2" - } else if strings.HasPrefix(zone, "ap-south-1") { - flags.aws.region = "ap-south-1" - } else { - return iamFlags{}, fmt.Errorf("invalid AWS region, to find a correct region please refer to our docs and https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html#concepts-availability-zones") + flags.aws.region, err = awsZoneToRegion(zone) + if err != nil { + return iamFlags{}, fmt.Errorf("invalid AWS zone. To find a valid zone, please refer to our docs and https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html#concepts-availability-zones") } // Setup IAM config. @@ -610,3 +601,17 @@ func parseIDFile(serviceAccountKeyBase64 string) (map[string]string, error) { } return out, nil } + +// awsZoneToRegion converts an AWS zone string to a region string. +// Example: "us-east-1a" -> "us-east-1" +// It does not check against a list of valid zones. +// Instead, it just checks that the zone string is in the correct format: +// "The code for Availability Zone is its Region code followed by a letter identifier." +// https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html#concepts-availability-zones . +func awsZoneToRegion(zone string) (string, error) { + parts := strings.Split(zone, "-") + if len(parts) < 3 || len(parts[2]) < 1 { + return "", fmt.Errorf("invalid zone string: %s", zone) + } + return fmt.Sprintf("%s-%s-%c", parts[0], parts[1], parts[2][0]), nil +} diff --git a/cli/internal/cmd/iamcreate_test.go b/cli/internal/cmd/iamcreate_test.go index 341f627b8..429952b20 100644 --- a/cli/internal/cmd/iamcreate_test.go +++ b/cli/internal/cmd/iamcreate_test.go @@ -212,7 +212,7 @@ func TestIAMCreateAWS(t *testing.T) { setupFs: defaultFs, creator: &stubIAMCreator{id: validIAMIDFile}, provider: cloudprovider.AWS, - zoneFlag: "us-west-5b", + zoneFlag: "us-west", prefixFlag: "test", yesFlag: true, wantErr: true,