How to pass script to UserData field in EC2 creati

2020-07-18 03:15发布

问题:

I'm trying to pass a script in Userdata field of a new EC2 instance created by an AWS Lambda (using AWS SDK for Javascript, Node.js 6.10):

...
var paramsEC2 = {
   ImageId: 'ami-28c90151', 
   InstanceType: 't1.micro',
   KeyName: 'myawesomekwy',
   MinCount: 1,
   MaxCount: 1,
   SecurityGroups: [groupname],
   UserData:'#!/bin/sh \n echo "Hello Lambda"'
};

// Create the instance
ec2.runInstances(paramsEC2, function(err, data) {
   if (err) {
      console.log("Could not create instance", err);
      return;
   }
   var instanceId = data.Instances[0].InstanceId;
   console.log("Created instance", instanceId);
   // Add tags to the instance
   params = {Resources: [instanceId], Tags: [
      {
         Key: 'Name',
         Value: 'taggggg'
      }
   ]};
   ec2.createTags(params, function(err) {
      console.log("Tagging instance", err ? "failure" : "success");
   });
});
...

I tried several things like: - create a string and pass the string to the UserData - not working - create a string and encode it to base64 and pass the string to the UserData - not working - paste base64 encoded string - not working

Could you help me understanding how to pass a script in the UserData? The AWS SDK documentation is a bit lacking.

Is it also possible to pass a script put in an S3 bucket to the UserData?

回答1:

Firstly, base64 encoding is required in your example. Although the docs state that this is done for you automatically, I always need it in my lambda functions creating ec2 instances with user data. Secondly, as of ES6, multi-line strings can make your life easier as long as you add scripts within your lambda function.

So try the following:

var userData= `#!/bin/bash
echo "Hello World"
touch /tmp/hello.txt
`

var userDataEncoded = new Buffer(userData).toString('base64');

var paramsEC2 = {
    ImageId: 'ami-28c90151',
    InstanceType: 't1.micro',
    KeyName: 'AWSKey3',
    MinCount: 1,
    MaxCount: 1,
    SecurityGroups: [groupname],
    UserData: userDataEncoded
};

// Create the instance
// ...