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

Posted

技术标签:

【中文标题】在特定子网和安全组 cloudformation 中创建实例【英文标题】:Create instance in specific subnet and security group cloudformation 【发布时间】:2017-02-09 19:38:17 【问题描述】:

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

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

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

请帮忙解决这个问题..

【问题讨论】:

【参考方案1】:

您添加到AWS::EC2::Instance 的AWS::EC2::Subnet 与AWS::EC2::SecurityGroup 位于不同的AWS::EC2::VPC 中。

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

VpcId

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

有关使用 Ref 函数的更多信息,请参阅参考。

必需:是,对于 VPC 安全组

您的账户使用 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 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"
                
            
        ]
    

【讨论】:

以上是关于在特定子网和安全组 cloudformation 中创建实例的主要内容,如果未能解决你的问题,请参考以下文章

实例无法通信 - 相同的 VPC 和子网,不同的安全组

AWS 中的 cloudformation 最佳实践

数据库实例和EC2安全组在不同的VPC,cloudFormation错误

如何使用 CloudFormation 将安全组添加到现有 EC2 实例

如何在 CloudFormation 模板中为 Elastic Beanstalk 启动配置指定安全组?

如何指定安全组中的所有端口 - CloudFormation