简体   繁体   English

如何在AWS Lambda上创建EC2时将脚本传递给UserData字段?

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

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): 我正在尝试在AWS Lambda创建的新EC2实例的Userdata字段中传递脚本(使用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 我尝试了几样的事情: - 创建一个字符串并将字符串传递给UserData - 不工作 - 创建一个字符串并将其编码为base64并将字符串传递给UserData - 不工作 - 粘贴base64编码的字符串 - 不工作

Could you help me understanding how to pass a script in the UserData? 你能帮我理解如何在UserData中传递脚本吗? The AWS SDK documentation is a bit lacking. AWS SDK文档有点缺乏。

Is it also possible to pass a script put in an S3 bucket to the UserData? 是否也可以将放入S3存储桶的脚本传递给UserData?

Firstly, base64 encoding is required in your example. 首先,base64编码需要在你的榜样。 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. 尽管文档声明这是自动完成的,但我总是需要在我的lambda函数中创建带有用户数据的ec2实例。 Secondly, as of ES6, multi-line strings can make your life easier as long as you add scripts within your lambda function. 其次,从ES6开始,只要在lambda函数中添加脚本,多行字符串就可以让您的生活更轻松。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM