本文介绍了如何在AWS Lambda上的EC2创建中将脚本传递给UserData字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在由AWS Lambda创建的新EC2实例的Userdata字段中传递脚本(使用适用于Java的AWS开发工具包,Node.js 6.10)

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

我尝试了几种方法,例如: -创建一个字符串并将该字符串传递给UserData-不起作用-创建一个字符串并将其编码为base64并将该字符串传递给UserData-不起作用-粘贴base64编码的字符串-不起作用

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

您能帮助我了解如何在UserData中传递脚本吗?缺少AWS开发工具包文档.

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

是否还可以将S3存储桶中的脚本传递给UserData?

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

推荐答案

首先,您的示例中需要base64编码 .尽管文档指出这是为您自动完成的,但我的lambda函数始终需要使用用户数据来创建ec2实例,但我始终需要这样做.其次,从ES6开始,只要在lambda函数中添加脚本,多行字符串就可以使您的生活更轻松.

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

这篇关于如何在AWS Lambda上的EC2创建中将脚本传递给UserData字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 14:03