在特定子网和安全组 cloudformation 中创建实例

Create instance in specific subnet and security group cloudformation

我正在尝试使用 cfn 启动实例 template.The 实例需要在特定的现有子网上以及在模板中创建的安全组中启动。

我有以下参数来获取子网列表:

"Subnet": {
  "Description": "Subnet to put Instance",
  "Type": "AWS::EC2::Subnet::Id",
},

我有以下资源来创建安全组:

"InstanceSecurityGroup": {
      "Type": "AWS::EC2::SecurityGroup",
      "Properties": {
        "GroupDescription": "Enables access to instance by port 80",
        "SecurityGroupIngress": [
          {
            "IpProtocol": "tcp",
            "FromPort": "80",
            "ToPort": "80",
            "CidrIp": {
              "Ref": "ClientCIDR"
            }
          }
        ]
      },

我有以下资源来创建实例:

"WebServer": {
  "Type": "AWS::EC2::Instance",
  "Properties": {
    "IamInstanceProfile": "access-profile",
    "SecurityGroupIds": [
      { "Fn::GetAtt": [
          "InstanceSecurityGroup",
          "GroupId"
        ]
      }
    ],
    "SubnetId": {
      "Ref": "Subnet"
    },

当我尝试创建实例并选择现有子网时出现以下错误:

Security group sg-**** and subnet subnet-**** belong to different networks. 

请帮忙解决这个问题..

AWS::EC2::Subnet your are adding to the AWS::EC2::Instance is in a different AWS::EC2::VPC to the AWS::EC2::SecurityGroup

创建 InstanceSecurityGroup 资源时,您应该使用 AWS::EC2::SecurityGroup VpcId property to create the AWS::EC2::SecurityGroup in a particular AWS::EC2::VPC。此 属性 的文档说明

VpcId

The physical ID of the VPC. Can be obtained by using a reference to an AWS::EC2::VPC, such as: { "Ref" : "myVPC" }.

For more information about using the Ref function, see Ref.

Required: Yes, for VPC security groups

您的账户使用的是EC2-VPC,如果您使用的是ec2-classic,则只能省略VpcId参数,here are the differences介于ec2-classic和ec2-vpc之间。

Cloud Formation 模板可以接受 AWS 特定 Parameter 类型 AWS::EC2::VPC::Id 例如

"VPCId": {
    "Type":  "AWS::EC2::VPC::Id"
    "Description": "The VPC Id to where this instance is being created"
}

并且此 Parameter 然后可以使用内部 Ref 函数 来引用 AWS::EC2 中的 VPCId 参数: :安全组

"InstanceSecurityGroup": {
    "Type": "AWS::EC2::SecurityGroup",
    "Properties": {
        "GroupDescription": "Enables access to instance by port 80",
        "VPCId": {
            "Ref": "VPCId"
        },
        "SecurityGroupIngress": [
            {
                "IpProtocol": "tcp",
                "FromPort": "80",
                "ToPort": "80",
                "CidrIp": {
                    "Ref": "ClientCIDR"
                }
            }
        ]
    }
}