Base64 encode UserData parameter for EC2 RunInstances using AWS Lambda

1.5k views Asked by At

I am having a problem when passing user data to launch an EC2 instance using AWS Lambda. I want to pass it as plain text or in some format it can convert my plain text to Base64. When I converted my plain text to Base64 it was passing correctly and could retrieve in desired format.

Please review my code and suggest how I could pass my user data to retrieve it properly when the instance is launched.

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

There are 1 answers

0
Aditya Manohar On BEST ANSWER

As per the [AWS.EC2.runInstances() API documentation] it the UserData parameter needs to be a Base64 encoded string. It looks like you're passing it in as plain text.

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