CloudFormation 在启动 EC2 实例时抛出 "Value () for parameter groupId is invalid. The value cannot be empty"

CloudFormation throws "Value () for parameter groupId is invalid. The value cannot be empty" when launching EC2 instance

我想为 public 子网中的单个 Linux EC2 实例编写完整的 CloudFormation 模板。我使用 AWS CloudFormation template for creating an EC2 Instance with a Security Group 作为起点。此模板在您的默认 VPC 中启动一个实例。

我的目标是拥有一个独立的模板,它可以在新堆栈中创建所需的一切,但不会创建到默认 VPC 中。我想要一个新的 VPC、安全组、路由 Table、互联网网关、子网并启动一个新的 Linux EC2 实例。

所以我使用了上面的模板并添加了所需的资源并使用 Ref 链接它们。一切都很好:VPC、子网、安全组、Internet GW、路由 Tables 等。但是我的 EC2 会出错并且堆栈会回滚。

状态原因是:

Value () for parameter groupId is invalid. The value cannot be empty (Service: AmazonEC2; Status Code: 400; Error Code: InvalidParameterValue; Request ID: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx)

CloudFormation 模板中的 EC2 资源如下所示:

"EC2Instance" : {
        "Type" : "AWS::EC2::Instance",
        "Properties" : {
          "InstanceType" : { "Ref" : "InstanceType" },
          "SecurityGroups" : [ { "Ref" : "InstanceSecurityGroup" } ],
          "KeyName" : { "Ref" : "KeyName" },
          "ImageId" : { "Fn::FindInMap" : [ "AWSRegionArch2AMI", { "Ref" : "AWS::Region" },
                            { "Fn::FindInMap" : [ "AWSInstanceType2Arch", { "Ref" : "InstanceType" }, "Arch" ] } ] }
          }
      }

错误消息不清楚要做什么。

搜索错误消息后,我发现很多人抱怨错误消息含糊不清,但没有针对 CloudFormation 模板中的 EC2 资源的具体修复。

有人提到当您不在默认 VPC 中启动 EC2 时,您需要指定安全组 ID 而不是安全组名称。

检查reference for the EC2 CloudFormation Resource type,有这个:

SecurityGroups

[EC2-Classic, default VPC] The names of the security groups. For a nondefault VPC, you must use security group IDs instead.

在页面顶部,为 EC2 指定了安全组 ID,如下所示:

"SecurityGroupIds" : [ String, ... ],

所以我将我的 EC2 资源更改为以下内容:

"EC2Instance" : {
        "Type" : "AWS::EC2::Instance",
        "Properties" : {
          "InstanceType" : { "Ref" : "InstanceType" },
          "SecurityGroupIds" : [ 
              { "Fn::GetAtt" : [ "InstanceSecurityGroup", "GroupId" ] }
            ],
          "SubnetId" : {"Ref":"TestSubnet"},
          "KeyName" : { "Ref" : "KeyName" },
          "ImageId" : { "Fn::FindInMap" : [ "AWSRegionArch2AMI", { "Ref" : "AWS::Region" },
                            { "Fn::FindInMap" : [ "AWSInstanceType2Arch", { "Ref" : "InstanceType" }, "Arch" ] } ] }
          }
      },

成功了。

当我在 EC2 实例资源声明中使用 属性 SecurityGroups 时,尝试在默认 VPC 中创建 EC2 实例时出现此错误。切换到 SecurityGroupIds 解决了我的问题。

如果您尝试使用 EC2 插件通过 jenkins 启动 EC2 实例,在云配置中,有一个部分 'Security group names'。

不要在此处提供安全组名称,而是输入安全组 ID (sg-xxxx),然后在 'Subnet IDs for VPC' 部分输入子网 ID (subnet-xxx)。