1

如何在 JavaScript 中启动带有附加(现有)IAM 角色的 EC2 实例?

我知道这个问题已被问到其他语言,但我找不到 JavaScript 的示例。

我的 JS Lambda 代码目前看起来像:

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();

文档:

https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-ec2/interfaces/runinstancescommandinput.html#iaminstanceprofile


"@aws-sdk/client-ec2": "^3.44.0",
"@aws-sdk/client-lambda": "^3.45.0",

上面的代码运行,但 EC2 > Instances > Security 选项卡下的 IAM Role 在我所有的尝试中都保持为空

4

1 回答 1

1

对于 IamInstanceProfile 字段,您需要指定 ARN 或名称。尝试使用以下任何选项:

const instanceParams = {
  ImageId: "ami-00a844bXXXXXXXXXX",
  InstanceType: "a1.xlarge",
  KeyName: "YourKeyName", 
  MinCount: 1,
  MaxCount: 1,
  SecurityGroupIds: ["sg-XXXXXXXXXXXXX"],
  IamInstanceProfile: 
  {
      Name: "NAME"
  }
};

或者

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

JavaScript SDK 运行实例

于 2021-12-29T17:41:17.613 回答