Passing Data From A Cloudformation Template To A NodeJS Or Python Function
Recently I had the task of moving a lot of our setup from the AWS PHP SDK to simple Cloudformation templates.
One issue that I had to resolve was passing data from the Cloudformation template Parameters to the Lambda function.
Here is just a simple example to demonstrate the process we will be using environment variables that we are setting in our Cloudformation template.
Here is a basic NodeJS Lambda function.
exports.handler = (event, context, callback) => { const https = require('https'); const options = { hostname: process.env.ApiUrl, port: 443, path: '/todos', method: 'GET' }; const req = https.request(options, (res) => { console.log('statusCode:', res.statusCode); console.log('headers:', res.headers); res.on('data', (d) => { process.stdout.write(d); }); }); req.on('error', (e) => { console.error(e); }); req.end(); };
Very simple just gets data from a dummy api. You should notice the hostname has an environmental variable set.
process.env.ApiUrl
This is getting passed from our Cloudformation template.
{ "AWSTemplateFormatVersion": "2010-09-09", "Description": "ApiWorkflow", "Metadata": { }, "Parameters": { "ApiUrl": { "Description": "Specify the api url", "Type": "String", "Default": "jsonplaceholder.typicode.com" }, }, "Mappings": { }, "Conditions": { }, "Resources": { "lambdaVodFunction": { "Type": "AWS::Lambda::Function", "Properties": { "Code": { "S3Bucket": "lamdba-exec-tests", "S3Key": "index.js.zip" }, "Handler": "index.handler", "Role": "arn:aws:iam::000000000:role/BasicLambdaExecRole", "Runtime": "nodejs10.x", "FunctionName": "ApiWorkflow", "MemorySize": 128, "Timeout": 5, "Description": "Texting Lambda", "Environment": { "Variables": { "ApiUrl": { "Ref": "ApiUrl" } } } } } }, "Outputs": { "ApiUrl": { "Description": "Set api url", "Value": { "Ref": "ApiUrl" } } } }
If you login to your AWS console and navigate to your NodeJS Lambda function you should see all your environmental variables that are set.
Now you can pass data through makes Cloudformation and Lambda very powerful.
Also, just to note from the template above the NodeJS Lambda function is zipped and uploaded to a bucket that is referenced in the Cloudformation template.
Going to have quite a few of these type of post as I am moving a lot of functionality over to Lambda and Cloudformation.
Quick Update
I recently had to also pass the environmental variables through to a python function you can do this with the following code.
import os os.environ['ApiUrl']