Передача параметров в функцию CloudFormation с помощью Nodejs - PullRequest
0 голосов
/ 07 февраля 2019

Я создал функцию Lambda, подписал ее на тему SNS и пытаюсь передать значение из сообщения SNS в функцию CloudFormation createStack в Nodejs.Сообщение SNS просто содержит число, которое преобразуется в переменную и передается в мою функцию create_stack_function.Оттуда я не уверен, как правильно пройти.В шаблоне требуется значение InstanceNumber, которое указывает количество создаваемых хостов.

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);
    }
}

Я бы хотел, чтобы эта лямбда-функция получала сообщение SNS, преобразовывала сообщение в переменную, создавала стек CloudFormationи отправьте сообщение SNS о создаваемом стеке.

1 Ответ

0 голосов
/ 07 февраля 2019

Согласно документам , вы передаете параметр Parameters, который представляет собой массив объектов, каждый из которых содержит хотя бы имя (ParameterKey) и значение (ParameterValue)параметра, который вы хотите передать в Cloudformation.

Попробуйте выполнить следующее:

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
  }]
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...