使用cloudformation,我想给默认安全组和SSH安全组作为实例的安全组

Using cloudformation, I want to give default security group and SSH security group as the security group of the instance

我正在使用 cloudformation 构建基础设施。

我想给default安全组和SSH安全组作为实例的安全组

有 Network.yaml、Security.yaml、Application.yaml 个文件。

这是 Network.yaml 的一部分。

SampleVPC:
    Type: AWS::EC2::VPC
    Properties:
      CidrBlock: 10.0.0.0/16
      EnableDnsSupport: true
      Tags:
        - Key: Name
          Value: sample-vpc

这是 Security.yaml 的一部分。

Resources:
 BastionSecurityGroup:
  Type: AWS::EC2::SecurityGroup
  Properties:
   GroupName: sample-sg-bastion
   GroupDescription: for bastion
   VpcId: !ImportValue vpc-id
   SecurityGroupIngress:
   - CidrIp: 10.10.10.10/32
     FromPort: 22
     IpProtocol: tcp
     ToPort: 22
   Tags:
    - Key: Name
      Value: sample-sg-bastion
Outputs:
  BastionSecurityGroup:
    Description: The Security Group for bastion instance
    Value: !Ref BastionSecurityGroup
    Export:
      Name: Bastion-sg-id

这是 Application.yaml 的一部分。

Resources:
  BastionEC2Instance:
    Type: AWS::EC2::Instance
    Properties:
      KeyName: !Ref KeyName
      #DisableApiTermination: 
      ImageId: !FindInMap [AWSRegionAMI, !Ref 'AWS::Region', HVM64]
      InstanceType: t2.micro
      #Monitoring: true|false
      NetworkInterfaces:
        - AssociatePublicIpAddress: true
          SubnetId: !ImportValue pubsubnet-01a-id
          DeviceIndex: 0
          GroupSet:
           - !ImportValue Bastion-sg-id
           - ###I want to set DefaultSecurityGroup###
      UserData: !Base64 |
        #!/bin/bash -ex
        # put your script here
      Tags:
        - Key: Name
          Value: sample-ec2-bastion

实例绑定默认安全组怎么办?

##########修改############

效果不错!!感谢 Allan 的支持。

我将此代码添加到 Network.yaml。

DefaultNetworkSG:
    Value:
     !GetAtt SampleVPC.DefaultSecurityGroup
    Export:
      Name: default-sg-id

我将此代码添加到 Application.yaml。

  NetworkInterfaces:
    - AssociatePublicIpAddress: true
      SubnetId: !ImportValue pubsubnet-01a-id
      DeviceIndex: 0
      GroupSet:
       - !ImportValue Bastion-sg-id
       - !ImportValue default-sg-id

您只需在 EC2 定义的附加 SG 列表中添加安全组 ID,您可以通过从 security.yaml 导出安全组 ID 并从 application.yaml

Network.yaml

  SampleVPC:
    Type: AWS::EC2::VPC
    Properties:
      CidrBlock: 10.0.0.0/16
      EnableDnsSupport: true
      Tags:
        - Key: Name
          Value: sample-vpc
Outputs:
  DefaultNetworkSG:
    Value:
     !GetAtt SampleVPC.DefaultSecurityGroup
  

Security.yaml

Outputs:
  BastionSecurityGroupID:
    Value:
      Ref: BastionSecurityGroup

Application.yaml

  BastionEC2Instance:
    Type: AWS::EC2::Instance
    Properties:
      SecurityGroupIds:
      - !ImportValue: BastionSecurityGroupID
      - !ImportValue: DefaultNetworkSG