如何在 YAML CloudFormation 模板中的特定 VPC 中启动 Amazon EC2



如何使用 CloudFormation 中的 YAML 模板在 VPC 的特定子网中启动 Amazon EC2 实例?

如果将来有人访问它,我可以通过指定以下内容来解决这个问题:可用性区域、安全组 ID(不是安全组(和子网 ID。

Resources:
    EC2Instance: 
        Properties:
          AvailabilityZone: us-east-1b
          ImageId: ami-Id
          InstanceType: 
            Ref: InstanceType
          KeyName: 
            Ref: KeyName
          Tags:
              -
                Key: "Name"
                Value:
                  Ref: InstanceName
          SecurityGroupIds:
              - sg-idHere
          SubnetId: subnet-idHere
        Type: "AWS::EC2::Instance" 

确保您尝试使用的 VPC 可以使用该安全组。子网 ID 应代表 VPC。

等级制度:VPC->子网ID->安全组ID

以下是在新加坡区域创建 ec2 实例的 CF 模板。我刚刚使用了这个模板。如果您在其他地区运行,请将 ImageId 名称更改为与您所在地区会面

---
AWSTemplateFormatVersion: '2010-09-09'
Description: 'VPC with private subnets in two availability zones'
Parameters:
  PrivateSubnet:
    Description: Private Subnet to Attach NAT Gateway.
    Type: AWS::EC2::Subnet::Id
  InstanceType:
    Description: EC2 instance type
    Type: String
    Default: t2.micro
    AllowedValues: [t2.micro, t2.small, t2.medium, t2.large, m3.medium, m3.large,
      m3.xlarge, m3.2xlarge, m4.large, m4.xlarge, m4.2xlarge, m4.4xlarge, m4.10xlarge,
      c4.large, c4.xlarge, c4.2xlarge, c4.4xlarge, c4.8xlarge, c3.large, c3.xlarge,
      c3.2xlarge, c3.4xlarge, c3.8xlarge, r3.large, r3.xlarge, r3.2xlarge, r3.4xlarge,
      r3.8xlarge, i2.xlarge, i2.2xlarge, i2.4xlarge, i2.8xlarge]
    ConstraintDescription: Please choose a valid instance type.
  SSHKeyName:
    Description: EC2 instance type
    Type: String
    ConstraintDescription: Please choose a valid KeyName
  VolumeSize:
    Description: size of volume
    Type: Number
    Default: 20
    ConstraintDescription: Please choose a valid Number
    AllowedValues: [20, 30, 40, 50]
  IOPS:
    Description: total ipos
    Type: Number
    Default: 100
    ConstraintDescription: Please choose a valid Number
    AllowedValues: [100, 200, 500, 1000]
  ImageId:
    Type: String
    Description: 'value for region singapore. If you using other version please choose right'
    Default: 'ami-33e4bc49'

Resources:
  EC2Example:
    Type: "AWS::EC2::Instance"
    Properties:
      SubnetId: !Ref PrivateSubnet
      ImageId: !Ref ImageId
      InstanceType: !Ref InstanceType
      KeyName: !Ref SSHKeyName
      BlockDeviceMappings:
        -
          DeviceName: /dev/sda1
          Ebs:
            VolumeType: io1
            Iops: !Ref IOPS
            DeleteOnTermination: false
            VolumeSize: !Ref VolumeSize
Outputs:
  EC2Example:
    Description: 'Ec2 instance EC2Example'
    Value: !Ref EC2Example
    Export:
      Name: !Sub '${AWS::StackName}-EC2Example'

CloudFormation 模板包含一个SubnetId参数:

Type: "AWS::EC2::Instance"
Properties: 
  SubnetId: String

只需插入现有子网的 ID(例如 subnet-1234abcd (。

最新更新