Question:
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):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
... 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?
Answer:
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
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 // ... |