Base64使用AWS Lambda编码EC2 RunInstances的UserData参数

时间:2015-06-22 08:37:20

标签: amazon-web-services amazon-ec2 aws-lambda aws-sdk

我在使用AWS Lambda传递用户数据以启动EC2实例时遇到问题。我想将它作为纯文本或以某种格式传递它可以将我的纯文本转换为Base64。当我将纯文本转换为Base64时,它正确传递并可以以所需格式检索。

请检查我的代码,并建议在启动实例时如何传递我的用户数据以正确检索它。

console.log('Loading function');
var AWS = require('aws-sdk');
var ec2 = new AWS.EC2();

exports.handler = function(event, context) {
  console.log('Received event:', JSON.stringify(event, null, 2));
  // Get the object from the event and show its content type
  var params = {
    ImageId: 'ami-******', // EC2 instance 
    MinCount: 1, 
    MaxCount: 1,
    DryRun: false,
    EbsOptimized: false,
    InstanceInitiatedShutdownBehavior: 'terminate',
    InstanceType: 't2.micro',
    KeyName: '*******',
    Monitoring: {
      Enabled: false /* required */
    },
    NetworkInterfaces: [
      {
        AssociatePublicIpAddress: true,
        DeleteOnTermination: true,
        Description: 'Primary network interface',
        DeviceIndex: 0,
        SubnetId: 'subnet-******'
      },
    ],
    Placement: {
      AvailabilityZone: 'us-****-**',
      Tenancy: 'default'
    },
    UserData: "requestid"
  };
  ec2.runInstances(params, function(err, data) {
    if (err) {
      console.log("Could not create instance", err);    
      context.fail('Error', "Error getting file: " + err);
      return;         
    } else {
      var instanceId = data.Instances[0].InstanceId;          
      console.log("Created instance", instanceId);   
      context.succeed("Created instance");
    }
  });
};

1 个答案:

答案 0 :(得分:1)

根据[AWS.EC2.runInstances()API文档],UserData参数需要是Base64编码的字符串。看起来你像普通文本一样传递它。

var params = {
...
  UserData: new Buffer('requestid').toString('base64')
...
};