-
Notifications
You must be signed in to change notification settings - Fork 48
/
util.go
241 lines (224 loc) · 7.94 KB
/
util.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
package cloudformation
import (
"bytes"
"encoding/json"
"fmt"
gocf "github.com/crewjam/go-cloudformation"
"io"
"io/ioutil"
"regexp"
"strings"
"text/template"
)
////////////////////////////////////////////////////////////////////////////////
// Private
////////////////////////////////////////////////////////////////////////////////
func toExpressionSlice(input interface{}) ([]string, error) {
var expressions []string
slice, sliceOK := input.([]interface{})
if !sliceOK {
return nil, fmt.Errorf("Failed to convert to slice")
}
for _, eachValue := range slice {
switch str := eachValue.(type) {
case string:
expressions = append(expressions, str)
}
}
return expressions, nil
}
func parseFnJoinExpr(data map[string]interface{}) (*gocf.StringExpr, error) {
if len(data) <= 0 {
return nil, fmt.Errorf("FnJoinExpr data is empty")
}
for eachKey, eachValue := range data {
switch eachKey {
case "Ref":
return gocf.Ref(eachValue.(string)).String(), nil
case "Fn::GetAtt":
attrValues, attrValuesErr := toExpressionSlice(eachValue)
if nil != attrValuesErr {
return nil, attrValuesErr
}
if len(attrValues) != 2 {
return nil, fmt.Errorf("Invalid params for Fn::GetAtt: %s", eachValue)
}
return gocf.GetAtt(attrValues[0], attrValues[1]).String(), nil
case "Fn::FindInMap":
attrValues, attrValuesErr := toExpressionSlice(eachValue)
if nil != attrValuesErr {
return nil, attrValuesErr
}
if len(attrValues) != 3 {
return nil, fmt.Errorf("Invalid params for Fn::FindInMap: %s", eachValue)
}
return gocf.FindInMap(attrValues[0], gocf.String(attrValues[1]), gocf.String(attrValues[2])), nil
}
}
return nil, fmt.Errorf("Unsupported AWS Function detected: %#v", data)
}
////////////////////////////////////////////////////////////////////////////////
// Public
////////////////////////////////////////////////////////////////////////////////
// S3AllKeysArnForBucket returns a CloudFormation-compatible Arn expression
// (string or Ref) for all bucket keys (`/*`). The bucket
// parameter may be either a string or an interface{} ("Ref: "myResource")
// value
func S3AllKeysArnForBucket(bucket interface{}) *gocf.StringExpr {
arnParts := []gocf.Stringable{gocf.String("arn:aws:s3:::")}
switch bucket.(type) {
case string:
// Don't be smart if the Arn value is a user supplied literal
arnParts = append(arnParts, gocf.String(bucket.(string)))
case *gocf.StringExpr:
arnParts = append(arnParts, bucket.(*gocf.StringExpr))
case gocf.RefFunc:
arnParts = append(arnParts, bucket.(gocf.RefFunc).String())
default:
panic(fmt.Sprintf("Unsupported SourceArn value type: %+v", bucket))
}
arnParts = append(arnParts, gocf.String("/*"))
return gocf.Join("", arnParts...).String()
}
// S3ArnForBucket returns a CloudFormation-compatible Arn expression
// (string or Ref) suitable for template reference. The bucket
// parameter may be either a string or an interface{} ("Ref: "myResource")
// value
func S3ArnForBucket(bucket interface{}) *gocf.StringExpr {
arnParts := []gocf.Stringable{gocf.String("arn:aws:s3:::")}
switch bucket.(type) {
case string:
// Don't be smart if the Arn value is a user supplied literal
arnParts = append(arnParts, gocf.String(bucket.(string)))
case *gocf.StringExpr:
arnParts = append(arnParts, bucket.(*gocf.StringExpr))
case gocf.RefFunc:
arnParts = append(arnParts, bucket.(gocf.RefFunc).String())
default:
panic(fmt.Sprintf("Unsupported SourceArn value type: %+v", bucket))
}
return gocf.Join("", arnParts...).String()
}
// MapToResourceTags transforms a go map[string]string to a CloudFormation-compliant
// Tags representation. See http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html
func MapToResourceTags(tagMap map[string]string) []interface{} {
var tags []interface{}
for eachKey, eachValue := range tagMap {
tags = append(tags, map[string]interface{}{
"Key": eachKey,
"Value": eachValue,
})
}
return tags
}
// Struct to encapsulate transforming data into
type templateConverter struct {
templateReader io.Reader
additionalTemplateProps map[string]interface{}
// internals
expandedTemplate string
contents []gocf.Stringable
conversionError error
}
func (converter *templateConverter) expandTemplate() *templateConverter {
if nil != converter.conversionError {
return converter
}
templateDataBytes, templateDataErr := ioutil.ReadAll(converter.templateReader)
if nil != templateDataErr {
converter.conversionError = templateDataErr
return converter
}
templateData := string(templateDataBytes)
parsedTemplate, templateErr := template.New("CloudFormation").Parse(templateData)
if nil != templateErr {
converter.conversionError = templateDataErr
return converter
}
output := &bytes.Buffer{}
executeErr := parsedTemplate.Execute(output, converter.additionalTemplateProps)
if nil != executeErr {
converter.conversionError = executeErr
return converter
}
converter.expandedTemplate = output.String()
return converter
}
func (converter *templateConverter) parseData() *templateConverter {
if converter.conversionError != nil {
return converter
}
reAWSProp := regexp.MustCompile("\\{\\s*\"([Ref|Fn\\:\\:\\w+])")
splitData := strings.Split(converter.expandedTemplate, "\n")
splitDataLineCount := len(splitData)
for eachLineIndex, eachLine := range splitData {
curContents := eachLine
for len(curContents) != 0 {
matchInfo := reAWSProp.FindStringSubmatchIndex(curContents)
if nil != matchInfo {
// If there's anything at the head, push it.
if matchInfo[0] != 0 {
head := curContents[0:matchInfo[0]]
converter.contents = append(converter.contents, gocf.String(fmt.Sprintf("%s", head)))
curContents = curContents[len(head):]
}
// There's at least one match...find the closing brace...
var parsed map[string]interface{}
for indexPos, eachChar := range curContents {
if string(eachChar) == "}" {
testBlock := curContents[0 : indexPos+1]
err := json.Unmarshal([]byte(testBlock), &parsed)
if err == nil {
parsedContents, parsedContentsErr := parseFnJoinExpr(parsed)
if nil != parsedContentsErr {
converter.conversionError = parsedContentsErr
return converter
}
converter.contents = append(converter.contents, parsedContents)
curContents = curContents[indexPos+1:]
if len(curContents) <= 0 && (eachLineIndex < (splitDataLineCount - 1)) {
converter.contents = append(converter.contents, gocf.String("\n"))
}
break
}
}
}
if nil == parsed {
// We never did find the end...
converter.conversionError = fmt.Errorf("Invalid CloudFormation JSON expression on line: %s", eachLine)
return converter
}
} else {
// No match, just include it iff there is another line afterwards
newlineValue := ""
if eachLineIndex < (splitDataLineCount - 1) {
newlineValue = "\n"
}
// Always include a newline at a minimum
appendLine := fmt.Sprintf("%s%s", curContents, newlineValue)
if len(appendLine) != 0 {
converter.contents = append(converter.contents, gocf.String(appendLine))
}
break
}
}
}
return converter
}
func (converter *templateConverter) results() (*gocf.StringExpr, error) {
if nil != converter.conversionError {
return nil, converter.conversionError
}
return gocf.Join("", converter.contents...), nil
}
// ConvertToTemplateExpression transforms the templateData contents into
// an Fn::Join- compatible representation for template serialization.
// The templateData contents may include both golang text/template properties
// and single-line JSON Fn::Join supported serializations.
func ConvertToTemplateExpression(templateData io.Reader, additionalUserTemplateProperties map[string]interface{}) (*gocf.StringExpr, error) {
converter := &templateConverter{
templateReader: templateData,
additionalTemplateProps: additionalUserTemplateProperties,
}
return converter.expandTemplate().parseData().results()
}