How to pass script to UserData field in EC2 creation on AWS Lambda?

人盡茶涼 提交于 2019-12-10 20:35:39

问题


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
// ...


来源:https://stackoverflow.com/questions/46490843/how-to-pass-script-to-userdata-field-in-ec2-creation-on-aws-lambda

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!