1
votes

I've created a Lambda function, subscribed it to an SNS topic, and I'm trying to pass a value from an SNS message to a CloudFormation createStack function in Nodejs. The SNS message just contains a number which is converted to a variable and passed to my create_stack_function. From there, I'm not sure how to pass it correctly. The template wants a value called InstanceNumber which tells it the number of hosts to create.

topic_arn = "arn:aws:sns:us-west-2:xxxxxxxxxxxx:xxxxxxxxxxxxxxx";
var AWS = require('aws-sdk'); 
AWS.config.region_array = topic_arn.split(':'); // splits the ARN in to and array 
AWS.config.region = AWS.config.region_array[3];  // makes the 4th variable in the array (will always be the region)


// Searches SNS messages for number of hosts to create
exports.handler = function (event, context) {
    const message = event.Records[0].Sns.Message;
        var NumberOfHosts = message;

        return create_stack_function(NumberOfHosts);

    // Might change return value, but all code branches should return.
    return true;
};

// Creates stack and publishes number of instances to the send_SNS_notification function
async function create_stack_function(NumberOfHosts) {
    const cloudformation = new AWS.CloudFormation();

    try {
        const resources = await cloudformation.createStack({
            StackName: "Launch-Test",
            TemplateURL: "https://s3-us-west-2.amazonaws.com/cf-templates-xxxxxxxxxxx-us-west-2/xxxinstances.yaml",
            InstanceNumber: NumberOfHosts,
        }).promise();
        return send_SNS_notification(NumberOfHosts);
    } catch(err) {
        console.log(err, err.stack);
    }
}
// Publishes message to SNS
async function send_SNS_notification(NumberOfHosts) {
    const sns = new AWS.SNS();
    const resources_str = JSON.stringify(NumberOfHosts);

    try {
        const data = await sns.publish({
            Subject: "CloudFormation Stack Created",
            Message:  "A new stack was created containing" + NumberOfHosts + "host(s).",
            TopicArn: topic_arn
        }).promise();

        console.log('push sent');
        console.log(data);
    } catch (err) {
        console.log(err.stack);
    }
}

I'd like this Lambda function to receive an SNS message, convert the message into a variable, create a CloudFormation stack, and send an SNS message about the stack being created.

1

1 Answers

0
votes

According to the docs, you pass in a Parameters parameter, which is an array of objects, each object containing at least the name (ParameterKey) and the value (ParameterValue) of a parameter you want to pass in to Cloudformation.

Try the following:

cloudformation.createStack({
  StackName: "Launch-Test",
  TemplateURL: "https://s3-us-west-2.amazonaws.com/cf-templates-xxxxxxxxxxx-us-west-2/xxxinstances.yaml",
  Parameters: [{
    ParameterKey: "InstanceNumber", // name of the Cloudformation parameter
    ParameterValue: String(NumberOfHosts) // its value, as a String
  }]
});