-
Notifications
You must be signed in to change notification settings - Fork 0
/
cfn-inline-1.0.yaml
314 lines (272 loc) · 11.5 KB
/
cfn-inline-1.0.yaml
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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
AWSTemplateFormatVersion: 2010-09-09
# Copyright (c) 2021, Viasat, Inc
# License under MPL 2.0
#
# This template defines the InlineJS and InlinePy cloudformation
# macros that allows macro and function definitions to be declared and
# used inline in the same cloudformation template.
#
# See README.md for more information
#
Resources:
MacroExecutionRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Action: ['sts:AssumeRole']
Effect: Allow
Principal:
Service: [lambda.amazonaws.com, cloudformation.amazonaws.com]
MacroLogPolicy:
Type: AWS::IAM::Policy
Properties:
PolicyName: !Sub "LogPolicy-Inline-Macros"
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action: ['logs:*']
Resource: 'arn:aws:logs:*:*:*'
Roles:
- !Ref MacroExecutionRole
InlineJSFunction:
Type: AWS::Lambda::Function
Properties:
Handler: index.handler
Runtime: nodejs10.x
Role: !GetAtt MacroExecutionRole.Arn
Code:
ZipFile: |
// Call f on every node of obj. Depth first unless bf is
// true. The arguments to f depend on the element type:
// - array element: f(val, idx, arr)
// - object key: f(key)
// - object value: f(val, key, keyIdx, keyList)
function walk(f, obj, bf=false) {
let x
if (!obj || typeof(obj) !== 'object') { return obj }
return bf
? Array.isArray(obj)
? obj.map((v, i, arr) => f(v, i, arr))
.map((v) => walk(f, v, bf))
: Object.keys(obj)
.map((k) => f(k))
.map((k, i, arr) => [k, f(obj[k], k, i, arr)])
.reduce((a, [k, v]) => (a[k] = walk(f, v, bf), a), {})
: Array.isArray(obj)
? obj.map((v, i, arr) => f(walk(f, v, bf), i, arr))
: Object.keys(obj).reduce((a, k, i, arr) =>
(x = f(walk(f, obj[k], bf), k, i, arr), a[f(k)] = x, a), {})
}
// Merge using f(v1, v2) for keys that occur in both maps
function mergeWith(f, a, b) {
return Object.entries(b).reduce((m, [k, v]) =>
(m[k] = k in m ? f(m[k], v) : v, m), Object.assign({}, a))
}
// Deep merge two maps
function deepMerge(a, b) {
return (a && a.constructor === Object) ? mergeWith(deepMerge, a, b) : b
}
// If obj contains 'Fn::Macro', invoke the macros using
// the current fragment and substitute resulting fragment
// Fn::Macro can contain one call (map) or multiple (list)
function doMacro(ns, event, context, obj) {
while (obj && typeof(obj) === 'object' && 'Fn::Macro' in obj) {
const {['Fn::Macro']: mc, ...rest} = obj // split out calls
let res = walk(v => v, rest) // deep copy
obj = (Array.isArray(mc) ? mc : [mc])
.reduce((res, call) =>
ns[call.Name](Object.assign({}, event, {
params: call.Parameters || {},
fragment: res
}), context),
res)
}
return obj
}
// If obj contains 'Fn::Function', call the first argument
// as a function using the remaining arguments.
function doFunction(ns, obj) {
if (obj && typeof(obj) === 'object' && 'Fn::Function' in obj) {
const [fname, ...fargs] = obj['Fn::Function']
return ns[fname](...fargs)
}
return obj
}
exports.handler = function(event, context, callback) {
console.log('event:', JSON.stringify(event))
try {
let frag = event.fragment
if (!('AWSTemplateFormatVersion' in frag)) {
throw new Error('AWSTemplateFormatVersion missing')
}
const initDef = frag.Metadata && frag.Metadata.JSInit
const macroDefs = frag.Metadata && frag.Metadata.JSMacros || {}
// Expose utility functions in global scope
Object.assign(global, {walk, mergeWith, deepMerge})
let ns = {} // user macro and function definitions
// Run initDef with exports set to ns
if (initDef) {
const initFn = new Function('event', 'context', 'exports', initDef)
initFn(event, context, ns)
}
// Instantiate macros in ns
Object.entries(macroDefs).forEach(([k, v]) =>
ns[k] = new Function('event', 'context', v))
// Do breadth first macro invocation (outside in). This
// is unlike standard CFN macros which are depth first,
// but more similar to Lisp macros.
frag = walk(doMacro.bind(null, ns, event, context),
[frag], true)[0]
// Do depth first invocation of functions
frag = walk(doFunction.bind(null, ns), [frag], false)[0]
// Response object with new fragment
console.log('new fragment:', JSON.stringify(frag))
callback(null, { requestId: event.requestId,
status: 'success',
fragment: frag })
} catch (e) {
console.error('caught error:', e)
callback(e)
}
}
InlinePyFunction:
Type: AWS::Lambda::Function
Properties:
Handler: index.handler
Runtime: python3.7
Role: !GetAtt MacroExecutionRole.Arn
Code:
ZipFile: |
import copy, functools, importlib, json, math, os, re, string, sys, time, traceback, types
# Call f on every node of obj. Depth first unless bf is
# true. The arguments to f depend on the element type:
# - array element: f(val, idx, arr)
# - object key: f(key)
# - object value: f(val, key, keyIdx, keyList)
def walk(f, obj, bf=False):
if not isinstance(obj, (dict, list)): return obj
if bf: # breadth first walk
if isinstance(obj, list):
newList = [f(v, i, obj) for [i, v] in enumerate(obj)]
return [walk(f, v, bf) for v in newList]
elif isinstance(obj, dict):
keys = [f(k) for k in sorted(obj.keys())]
kvs = [(k, f(obj[k], k, i, keys)) for [i, k] in enumerate(keys)]
return {k:walk(f, v, bf) for [k, v] in kvs}
else: # depth first walk
if isinstance(obj, list):
return [f(walk(f, v, bf), i, obj) for [i, v] in enumerate(obj)]
elif isinstance(obj, dict):
keys = sorted(obj.keys())
m = {}
for [i, k] in enumerate(keys):
x = f(walk(f, obj[k], bf), k, i, keys)
m[f(k)] = x
return m
# Merge using f(v1, v2) for keys that occur in both maps
def mergewith(f, a, b):
return {**a, **{k: (f(a[k], v) if k in a else v)
for k,v in b.items()}}
# Deep merge two maps
def deepmerge(a, b):
return mergewith(deepmerge, a, b) if isinstance(a, dict) else b
# If obj contains 'Fn::Macro', invoke the macros using
# the current fragment and substitute resulting fragment
# Fn::Macro can contain one call (map) or multiple (list)
def doMacro(ns, event, context, obj):
while isinstance(obj, dict) and 'Fn::Macro' in obj:
mc = obj['Fn::Macro']
res = walk(lambda v, *a: v, obj) # deep copy
del res['Fn::Macro']
for call in [mc] if isinstance(mc, dict) else mc:
event = {**event,
**{'params': call.get('Parameters', {}), 'fragment': res}}
res = ns[call['Name']](event, context)
obj = res
return obj
# If obj contains 'Fn::Function', call the first argument
# as a function using the remaining arguments.
def doFunction(ns, obj, *a):
if isinstance(obj, dict) and 'Fn::Function' in obj:
fname, *fargs = obj['Fn::Function']
return ns[fname](*fargs)
return obj
def handler(event, context):
print('event:', json.dumps(event))
resp = {'requestId': event['requestId'], 'status': 'success'}
try:
frag = event['fragment']
assert 'AWSTemplateFormatVersion' in frag, 'AWSTemplateFormatVersion missing'
meta = frag.get('Metadata', {})
importDef = meta.get('PyImports', [])
initDef = meta.get('PyInit', None)
macroDefs = meta.get('PyMacros', {})
ns = {} # user macro and function definitions
# Additional imports
for imp in importDef:
globals()[imp] = importlib.import_module(imp)
# Run initDef with locals set to ns
if initDef:
gtmp = {**globals(), **{'event': event, 'context': context}}
exec(compile(initDef, '', 'exec'), gtmp, ns)
# Instantiate macros in ns
for [k, v] in macroDefs.items():
code = "def %s(event, context):\n" % k
code += re.sub(r'^', ' ', v, flags=re.MULTILINE)
exec(compile(code, '', 'exec'))
ns[k] = locals()[k]
# Do breadth first macro invocation (outside in). This
# is unlike standard CFN macros which are depth first,
# but more similar to Lisp macros.
frag = walk(lambda obj, *a: doMacro(ns, event, context, obj),
[frag], True)[0]
# Do depth first invocation of functions
frag = walk(lambda *a: doFunction(ns, *a), [frag], False)[0]
# Response object with new fragment
print('new fragment:', json.dumps(frag))
resp['fragment'] = frag
except Exception as e:
traceback.print_exc()
resp['status'] = 'failure'
resp['errorMessage'] = str(e)
return resp
InlineJSMacro:
Type: AWS::CloudFormation::Macro
Properties:
Name: !Sub 'InlineJS-1_0'
Description: !Sub 'Macro definition of InlineJS-1_0'
FunctionName: !GetAtt InlineJSFunction.Arn
InlinePyMacro:
Type: AWS::CloudFormation::Macro
Properties:
Name: !Sub 'InlinePy-1_0'
Description: !Sub 'Macro definition of InlinePy-1_0'
FunctionName: !GetAtt InlinePyFunction.Arn
InlineJSFunctionPermissions:
Type: AWS::Lambda::Permission
Properties:
Action: 'lambda:InvokeFunction'
FunctionName: !GetAtt InlineJSFunction.Arn
Principal: 'cloudformation.amazonaws.com'
InlinePyFunctionPermissions:
Type: AWS::Lambda::Permission
Properties:
Action: 'lambda:InvokeFunction'
FunctionName: !GetAtt InlinePyFunction.Arn
Principal: 'cloudformation.amazonaws.com'
Outputs:
InlineJSFunction:
Value: !Ref InlineJSFunction
InlinePyFunction:
Value: !Ref InlinePyFunction
InlineJSMacro:
Value: !Ref InlineJSMacro
InlinePyMacro:
Value: !Ref InlinePyMacro
MacroExecutionRole:
Value: !Ref MacroExecutionRole
MacroLogPolicy:
Value: !Ref MacroLogPolicy