Skip to content

Instantly share code, notes, and snippets.

@pda
Last active September 14, 2020 04:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pda/dcecf06b8d7dcb67aea8a4b6c5949f3f to your computer and use it in GitHub Desktop.
Save pda/dcecf06b8d7dcb67aea8a4b6c5949f3f to your computer and use it in GitHub Desktop.
A basic !InlineFile YAML tag/function resolver for inlining Lambda into CloudFormation; assumes two-space indentation
PATTERN = %r{
^
(?<indent>\s*)
(?<key>\S+):
\s*
!InlineFile
\s*
(?<file>.*)
$
}x
def inline_file(match)
puts "#{match[:indent]}#{match[:key]}: |"
File.open(match[:file]) do |f|
f.each_line do |line|
puts(match[:indent] + " " + line)
end
end
end
File.open(ARGV[0]) do |template|
template.each_line do |line|
if match = PATTERN.match(line)
inline_file(match)
else
puts line
end
end
end
AWSTemplateFormatVersion: '2010-09-09'
Description: Lambda function with cfn-response.
Resources:
primer:
Type: AWS::Lambda::Function
Properties:
Runtime: nodejs12.x
Role: arn:aws:iam::123456789012:role/lambda-role
Handler: index.handler
Code:
ZipFile: !InlineFile lambda.js
Description: Invoke a function during stack creation.
TracingConfig:
Mode: Active
AWSTemplateFormatVersion: '2010-09-09'
Description: Lambda function with cfn-response.
Resources:
primer:
Type: AWS::Lambda::Function
Properties:
Runtime: nodejs12.x
Role: arn:aws:iam::123456789012:role/lambda-role
Handler: index.handler
Code:
ZipFile: |
var aws = require('aws-sdk')
var response = require('cfn-response')
exports.handler = function(event, context) {
console.log("REQUEST RECEIVED:\n" + JSON.stringify(event))
// For Delete requests, immediately send a SUCCESS response.
if (event.RequestType == "Delete") {
response.send(event, context, "SUCCESS")
return
}
var responseStatus = "FAILED"
var responseData = {}
var functionName = event.ResourceProperties.FunctionName
var lambda = new aws.Lambda()
lambda.invoke({ FunctionName: functionName }, function(err, invokeResult) {
if (err) {
responseData = {Error: "Invoke call failed"}
console.log(responseData.Error + ":\n", err)
}
else responseStatus = "SUCCESS"
response.send(event, context, responseStatus, responseData)
})
}
Description: Invoke a function during stack creation.
TracingConfig:
Mode: Active
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment