使用 CloudFormation 启动 EC2 实例的安全组问题

Security Group Issue with launching an EC2 instance with CloudFormation

我正在尝试将 EC2 实例启动到 public 子网中,但是当我尝试启动 CF 模板时,我不断收到错误消息:

The parameter groupName cannot be used with the parameter subnet

这是子网、EC2 实例和安全组的 CF 模板。

# VPC
  VPC:
    Type: "AWS::EC2::VPC"
    Properties:
      CidrBlock: 10.0.0.0/24
      EnableDnsSupport: true
      InstanceTenancy: "default"

# Public subnet
  PublicSubnet:
    Type: "AWS::EC2::Subnet"
    Properties:
      AvailabilityZone: "us-east-1a"
      CidrBlock: 10.0.0.0/28
      VpcId: !Ref VPC

# EC2 Security Group
  SecurityGroupForEC2:
    Type: "AWS::EC2::SecurityGroup"
    Properties:
      GroupDescription: "This security group allows SSH access into the bastion hosts from your personal IP"
      GroupName: "SecurityGroup-For-Public-Subnet"
      SecurityGroupIngress:
        - CidrIp: My IP
          Description: "Allows SSH Access into the bastion Hosts"
          FromPort: 22
          IpProtocol: 6
          ToPort: 22
      VpcId: !Ref VPC


# EC2 Instances for bastion hosts
  BastionHostEC2:
    Type: "AWS::EC2::Instance"
    Properties:
      AvailabilityZone: "us-east-1a"
      InstanceType: "t2.micro"
      ImageId: ami-0be2609ba883822ec # Amazon Linux 2
      KeyName: My-Keys
      SecurityGroups:
        - !Ref SecurityGroupForPublicSubnet
      SourceDestCheck: false
      SubnetId: !Ref PublicSubnet

当 CF 堆栈尝试创建实例时,错误不断出现。 我不确定在这里做什么,因为我应该能够将安全组与正确的 ec2 实例相关联?这是安全组已经与VPC关联的结果吗?任何建议将不胜感激。

代码中至少有两个问题:

  1. SecurityGroupForPublicSubnet 不存在。我猜应该是SecurityGroupForEC2。我想是的。

  2. SecurityGroups 不能用于 非默认 VPC。由于您正在创建自己的 VPC,因此它失败了。您应该使用 SecurityGroupIds,如下面的固定代码所示

Resources:

  VPC:
    Type: "AWS::EC2::VPC"
    Properties:
      CidrBlock: 10.0.0.0/24
      EnableDnsSupport: true
      InstanceTenancy: "default"

# Public subnet
  PublicSubnet:
    Type: "AWS::EC2::Subnet"
    Properties:
      AvailabilityZone: "us-east-1a"
      CidrBlock: 10.0.0.0/28
      VpcId: !Ref VPC

# EC2 Security Group
  SecurityGroupForEC2:
    Type: "AWS::EC2::SecurityGroup"
    Properties:
      GroupDescription: "This security group allows SSH access into the bastion hosts from your personal IP"
      GroupName: "SecurityGroup-For-Public-Subnet"
      SecurityGroupIngress:
        - CidrIp: 0.0.0.0/0
          Description: "Allows SSH Access into the bastion Hosts"
          FromPort: 22
          IpProtocol: 6
          ToPort: 22
      VpcId: !Ref VPC


# EC2 Instances for bastion hosts
  BastionHostEC2:
    Type: "AWS::EC2::Instance"
    Properties:
      AvailabilityZone: "us-east-1a"
      InstanceType: "t2.micro"
      ImageId: ami-0be2609ba883822ec # Amazon Linux 2
      #KeyName: My-Keys
      SecurityGroupIds:
        - !GetAtt SecurityGroupForEC2.GroupId
      SourceDestCheck: false
      SubnetId: !Ref PublicSubnet