Skip to content

Commit

Permalink
resource: use regex replace to match the stack name for cloudformation
Browse files Browse the repository at this point in the history
  • Loading branch information
dschofie committed May 10, 2024
1 parent a613a99 commit 39b74f8
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
14 changes: 14 additions & 0 deletions resource/stack.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package resource

import (
"fmt"
"regexp"
"strings"
"time"

Expand Down Expand Up @@ -100,6 +101,9 @@ func (s Stack) CloudformationParametersType() ([]*cloudformation.Parameter, erro
return params, nil
}

// CloudformationStackName returns the corresponding stack name to create in cloudformation.
//
// The name needs to match [a-zA-Z][-a-zA-Z0-9]*|arn:[-a-zA-Z0-9:/._+]*
func (s Stack) CloudformationStackName() *string {
// Replace:
// - "/" with "-", "/" appears in the path
Expand All @@ -112,6 +116,16 @@ func (s Stack) CloudformationStackName() *string {
name = name + "-" + s.Region
}

// Stack name needs to start with [a-zA-Z]
// Remove leading characters that are not alphabetic
firstAlphaRegex := regexp.MustCompile(`^[^a-zA-Z]*`)
name = firstAlphaRegex.ReplaceAllString(name, "")

// Ensure the first character is alphabetic (already guaranteed by the previous step)
// Remove or replace all characters that do not match [-a-zA-Z0-9]
validCharsRegex := regexp.MustCompile(`[^-a-zA-Z0-9]+`)
name = validCharsRegex.ReplaceAllString(name, "-")

return &name
}

Expand Down
37 changes: 37 additions & 0 deletions resource/stack_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,40 @@ func setFields(s *Stack) {
}
}
}

func TestCloudformationStackName(t *testing.T) {
tests := []struct {
input Stack

want string
}{
{
input: Stack{
Name: "name",
Path: "path",
Region: "us-west-2",
},
want: "name-path-us-west-2",
},
{
input: Stack{
Path: "./path",
Region: "us-west-2",
},
want: "path-us-west-2",
},
{
input: Stack{
Name: "@danny",
Path: "./path",
Region: "us-west-2",
},
want: "danny---path-us-west-2",
},
}

for _, tc := range tests {
assert.Equal(t, tc.want, *tc.input.CloudformationStackName())
}

}

0 comments on commit 39b74f8

Please sign in to comment.