如何在新 SecurityGroup 的 AWS CloudFormation 模板中使用现有 VPC

How to use existing VPC in AWS CloudFormation template for new SecurityGroup

我正在尝试 EC2 实例(新)、安全组(新)和 VPC(现有)。这是我的 cloudformation 模板。

当我 运行 Stack 中的模板时,出现错误 *"Value () for parameter groupId is invalid. The value cannot be empty"*。如何解决?

模板:

Parameters:
  VPCID:
    Description: Name of an existing VPC
    Type: AWS::EC2::VPC::Id
  KeyName:
    Description: Name of an existing EC2 KeyPair to enable SSH access to the instance
    Type: AWS::EC2::KeyPair::KeyName
    ConstraintDescription: must be the name of an existing EC2 KeyPair.
  InstanceType:
    Description: EC2 instance type
    Type: String
    Default: t2.medium
    AllowedValues:
      - t2.medium
      - t2.large
  AccessLocation:
    Description: The IP address range that can be used to access to the EC2 instances
    Type: String
Resources:
  EC2Instance:
    Type: AWS::EC2::Instance
    Properties:
      InstanceType: !Ref 'InstanceType'
      SecurityGroups:
        - !Ref 'InstanceSecurityGroup'
      KeyName: !Ref 'KeyName'
      ImageId: !Ref 'ImageId'   
  InstanceSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      VpcId: !Ref VPCID
      GroupDescription: Enable SSH 
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: '22'
          ToPort: '22'
          CidrIp: !Ref 'AccessLocation'

EC2Instance 资源 SecurityGroups 属性中的错误。 SecurityGroups 需要一个 GroupId 的数组,但是当您使用 !Ref InstanceSecurityGroup 时,这个 returns ResourceId。所以你需要使用 GetAtt 而不是得到 GroupId.

Parameters:
  VPCID:
    Description: Name of an existing VPC
    Type: AWS::EC2::VPC::Id
  KeyName:
    Description: Name of an existing EC2 KeyPair to enable SSH access to the instance
    Type: AWS::EC2::KeyPair::KeyName
    ConstraintDescription: must be the name of an existing EC2 KeyPair.
  InstanceType:
    Description: EC2 instance type
    Type: String
    Default: t2.medium
    AllowedValues:
      - t2.medium
      - t2.large
  AccessLocation:
    Description: The IP address range that can be used to access to the EC2 instances
    Type: String
Resources:
  EC2Instance:
    Type: AWS::EC2::Instance
    Properties:
      InstanceType: !Ref 'InstanceType'
      SecurityGroups:
        - !GetAtt InstanceSecurityGroup.GroupId
      KeyName: !Ref 'KeyName'
      ImageId: !Ref 'ImageId'   
  InstanceSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      VpcId: !Ref VPCID
      GroupDescription: Enable SSH 
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: '22'
          ToPort: '22'
          CidrIp: !Ref 'AccessLocation'

https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group.html

SecurityGroups 可以 仅用于默认 VPC。由于您明确将 VPCID 分配给 InstanceSecurityGroup,这将被视为非默认值,从而导致部署失败。

必须在您的情况下使用SecurityGroupIds(而不是SecurityGroups),因为您的VPC使用将被视为非默认:

      SecurityGroupIds:
        - !GetAtt 'InstanceSecurityGroup.GroupId'