How can I launch an EC2 instance with attached (existing) IAM Role in JavaScript?
I know this question has been asked for other languages, but I couldn't find an example for JavaScript.
My JS Lambda code currently looks like:
const { EC2Client } = require( "@aws-sdk/client-ec2");
const ec2Client = new EC2Client({ region: "eu-central-1" });
const {
CreateTagsCommand,
RunInstancesCommand,
TerminateInstancesCommand,
RunInstancesRequest
} = require("@aws-sdk/client-ec2");
const instanceParams = {
ImageId: "ami-00a844bXXXXXXXXXX",
InstanceType: "a1.xlarge",
KeyName: "YourKeyName",
MinCount: 1,
MaxCount: 1,
SecurityGroupIds: ["sg-XXXXXXXXXXXXX"],
IamInstanceProfile: "arn:aws:iam::390000000000:instance-profile/NAME" // doesn't work
};
const run = async () => {
try {
const data = await ec2Client.send(new RunInstancesCommand(instanceParams));
console.log(data.Instances[0].InstanceId);
} catch (err) {
console.log("Error", err);
}
}
var ret = await run();
Documentation:
"@aws-sdk/client-ec2": "^3.44.0",
"@aws-sdk/client-lambda": "^3.45.0",
The code above runs, but the IAM Role under the EC2 > Instances > Security tab remains empty in all my tries.
CodePudding user response:
For IamInstanceProfile field you need to specify the ARN or name. Try with any of these options:
const instanceParams = {
ImageId: "ami-00a844bXXXXXXXXXX",
InstanceType: "a1.xlarge",
KeyName: "YourKeyName",
MinCount: 1,
MaxCount: 1,
SecurityGroupIds: ["sg-XXXXXXXXXXXXX"],
IamInstanceProfile:
{
Name: "NAME"
}
};
or
const instanceParams = {
ImageId: "ami-00a844bXXXXXXXXXX",
InstanceType: "a1.xlarge",
KeyName: "YourKeyName",
MinCount: 1,
MaxCount: 1,
SecurityGroupIds: ["sg-XXXXXXXXXXXXX"],
IamInstanceProfile:
{
Arn: "arn:aws:iam::390000000000:instance-profile/NAME"
}
};