仅使用 cloudformation 在默认 public 子网中创建 EC2

Create EC2 in default public subnet only using cloudformation

我有正在创建 EC2 机器的 CF 模板。

AWSTemplateFormatVersion: 2010-09-09

Mappings:
  InstanceAMI:
  # ubuntu 18.04
    us-west-2:
      ami: 'ami-0bbe6b35405ecebdb'
    us-east-1:
      ami: 'ami-0ac019f4fcb7cb7e6'

Parameters:
  Endpoint:
    Type: String
    # TODO edit the default value
    Description:

Resources:
  NodeInstanceProfile:
    Type: AWS::IAM::InstanceProfile
    Properties:
      Path: "/"
      Roles:
      - !Ref NodeInstanceRole

  NodeInstanceRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
        - Effect: Allow
          Principal:
            Service:
            - ec2.amazonaws.com
          Action:
          - sts:AssumeRole
      Path: "/"
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/AdministratorAccess

  CdpDeplSvcSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: Access Deployment service
      SecurityGroupIngress:
      - IpProtocol: tcp
        FromPort: 443
        ToPort: 443
        CidrIp: 0.0.0.0/0
      - IpProtocol: tcp
        FromPort: 8080
        ToPort: 8080
        CidrIp: 0.0.0.0/0
      - IpProtocol: tcp
        FromPort: 22
        ToPort: 22
        CidrIp: 0.0.0.0/0
      Tags:
      - Key: Name
        Value: 'Access Deployment'

  DeploymentMachine:
    Type: AWS::EC2::Instance
    Properties:
      # AvailabilityZone: us-east-1a
      ImageId: !FindInMap [InstanceAMI, !Ref "AWS::Region", ami]
      InstanceType: 't2.small'
      KeyName: 'key'
      Tags:
        - Key: Name
          Value: 'Deployment'
      BlockDeviceMappings:
        - DeviceName: "/dev/sda1"
          Ebs:
            # VolumeType: "io1"
            # Iops: "200"
            DeleteOnTermination: "true"
            VolumeSize: "30"
      NetworkInterfaces:
        - DeviceIndex: 0
          AssociatePublicIpAddress: 'true'
          DeleteOnTermination: 'true'
          GroupSet:
            - !GetAtt CdpDeplSvcSecurityGroup.GroupId
      IamInstanceProfile: !Ref NodeInstanceProfile

它执行正确。但我面临的问题是有时它在默认私有子网中创建,有时在默认 public 子网中创建。 我只想在 默认 public 子网 中部署此机器。我不想将 VPC id 或子网 id 作为参数传递。为此,我在这里进行了更改。

这只会将其放入一个随机子网中 - 您需要对子网进行硬编码,或者通过参数指定子网然后引用该参数 - 这可以为您提供一些灵活性来改变每个客户的子网。

可能,在堆栈部署期间,您可以编写部署脚本,使用 AWS CLI 获取所有 public 个子网,并将其中一个作为参数传递到您的 cloudformation 堆栈中。