diff --git a/staging/src/k8s.io/legacy-cloud-providers/aws/aws.go b/staging/src/k8s.io/legacy-cloud-providers/aws/aws.go index 3a972b6a8f9..4a3b2307ee1 100644 --- a/staging/src/k8s.io/legacy-cloud-providers/aws/aws.go +++ b/staging/src/k8s.io/legacy-cloud-providers/aws/aws.go @@ -25,6 +25,7 @@ import ( "io" "net" "path" + "regexp" "sort" "strconv" "strings" @@ -1202,7 +1203,13 @@ func azToRegion(az string) (string, error) { if len(az) < 1 { return "", fmt.Errorf("invalid (empty) AZ") } - region := az[:len(az)-1] + + r := regexp.MustCompile(`^([a-zA-Z]+-)+\d+`) + region := r.FindString(az) + if region == "" { + return "", fmt.Errorf("invalid AZ: %s", az) + } + return region, nil } diff --git a/staging/src/k8s.io/legacy-cloud-providers/aws/aws_test.go b/staging/src/k8s.io/legacy-cloud-providers/aws/aws_test.go index f4c1294694a..0cfe6645dcf 100644 --- a/staging/src/k8s.io/legacy-cloud-providers/aws/aws_test.go +++ b/staging/src/k8s.io/legacy-cloud-providers/aws/aws_test.go @@ -1982,3 +1982,23 @@ func newMockedFakeAWSServices(id string) *FakeAWSServices { s.elb = &MockedFakeELB{FakeELB: s.elb.(*FakeELB)} return s } + +func TestAzToRegion(t *testing.T) { + testCases := []struct { + az string + region string + }{ + {"us-west-2a", "us-west-2"}, + {"us-west-2-lax-1a", "us-west-2"}, + {"ap-northeast-2a", "ap-northeast-2"}, + {"us-gov-east-1a", "us-gov-east-1"}, + {"us-iso-east-1a", "us-iso-east-1"}, + {"us-isob-east-1a", "us-isob-east-1"}, + } + + for _, testCase := range testCases { + result, err := azToRegion(testCase.az) + assert.NoError(t, err) + assert.Equal(t, testCase.region, result) + } +}