Skip to content

Instantly share code, notes, and snippets.

@allenheltondev
Last active January 25, 2021 13:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save allenheltondev/1281088e952ef428e7971ffd0b7ec1af to your computer and use it in GitHub Desktop.
Save allenheltondev/1281088e952ef428e7971ffd0b7ec1af to your computer and use it in GitHub Desktop.
CloudFormation Macro Example
AWSTemplateFormatVersion: '2010-09-09'
Transform: [AWS::Serverless-2016-10-31, AddSSMParametersMacro]
Description: SAM template for consuming a CloudFormation Macro
Resources:
ExampleWithEnvVarFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: example-with-env-var
Handler: function.handler
Environment:
Variables:
LAMBDA_VALUE: ExampleFunction
ExampleWithoutEnvVarFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: example-without-env-var
Handler: function.handler
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: SAM template for creating a CloudFormation Macro
Resources:
AddSSMParametersFunction:
Type: AWS::Serverless::Function
Properties:
Description: CFN Macro function to automatically add action parameters based on the presence environment variables
CodeUri: auto-add-ssm-parameter
Handler: function.handler
AddSSMParametersMacro:
Type: AWS::CloudFormation::Macro
Properties:
Name: AddSSMParameters
Description: Adds SSM Parameters for lambdas with the LAMBDA_VALUE env var
FunctionName:
Ref: AddSSMParametersFunction
exports.handler = async function(event, context) {
const lambdas = [];
const resourceKeys = Object.keys(resources);
for (let i = 0; i < resourceKeys.length; i++) {
const resource = resources[resourceKeys[i]];
if (resource.Type === 'AWS::Serverless::Function' && resource.Properties.Environment.Variables.LAMBDA_VALUE) {
lambdas.push({
name: resourceKeys[i],
details: resource
});
}
}
lambdas.forEach((lambda) => {
event.fragment.Resources[`${lambda.name}Parameter`] = {
Type: 'AWS::SSM::Parameter',
Properties: {
Name: `${lambda.name}Parameter`,
Type: 'String',
Value: lambda.Properties.Environment.Variables.LAMBDA_VALUE
}
};
});
return {
requestId: event.requestId,
status: 'success',
fragment: event.fragment
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment