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

时间:2016-10-01 09:07:50

标签: amazon-ec2 amazon-cloudformation

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

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

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

我有以下reosurce来创建安全组:

"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. 

请帮助解决这个问题..

1 个答案:

答案 0 :(得分:3)

您要添加到AWS::EC2::SubnetAWS::EC2::InstanceAWS::EC2::VPCAWS::EC2::SecurityGroup不同。

创建InstanceSecurityGroup资源时,您应使用AWS::EC2::SecurityGroup VpcId属性在特定AWS::EC2::SecurityGroup中创建AWS::EC2::VPC。该属性的文档说明

  

VpcId

     

VPC的物理ID。可以通过使用参考获得   到AWS :: EC2 :: VPC,例如:{" Ref" :" myVPC" }。

     

有关使用Ref功能的更多信息,请参阅参考

     

必需:是,适用于VPC安全组

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

云端形成模板可以接受特定于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 function来引用AWS::EC2::SecurityGroup

中的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"
                }
            }
        ]
    }
}