【问题标题】:How do I specify subnet and VPC IDs in AWS CloudFormation?如何在 AWS CloudFormation 中指定子网和 VPC ID?
【发布时间】:2017-03-12 11:37:34
【问题描述】:

我希望我的 CloudFormation 模板使用现有的子网和 VPC。我不想创建新的。

如何参数化这些?

当我查看AWS::EC2::VPCAWS::EC2::Subnet 的文档时,似乎这些资源仅用于创建 VPC 和子网。对吗?

我是否应该将实例资源直接指向我希望它使用的现有 VPC 和子网?

例如 - 如果我的模板中有一个实例资源,并且我将它直接指向现有子网,如下所示:

{
  "Resources": {
    "MyServer": {
      "Type": "AWS::EC2::Instance",
      "Properties": {
        "InstanceType": {
          "Ref": "InstanceType"
        },
"SubnetId": {
  "Ref": "subnet-abc123"
},
...

验证模板时出现此错误:

Template contains errors.: Template format error: Unresolved resource dependencies [subnet-abc123] in the Resources block of the template

我尝试使用映射执行此操作,但仍然出现错误:

  "Mappings": {
    "SubnetID": {
      "TopKey": {
        "Default": "subnet-abc123"
      }
    }

在实例资源中使用这个:

"SubnetId": {
  "Fn::FindInMap": [
    "SubnetID",
    {
      "Ref": "TopKey"
    },
    "Default"
  ]
}

我在尝试验证时收到此错误:

Template contains errors.: Template format error: Unresolved resource dependencies [TopKey] in the Resources block of the template

【问题讨论】:

    标签: amazon-web-services amazon-ec2 amazon-vpc amazon-cloudformation


    【解决方案1】:

    Parameters 部分中指定它们,并在Resources 部分中引用它们。 CF 会让您先选择 VPC,然后再选择 Subnet

      "Parameters" : {
    
        "VpcId" : {
          "Type" : "AWS::EC2::VPC::Id",
          "Description" : "VPCId of Virtual Private Cloud (VPC).",
          "Default" : ""
        },
    
        "VpcSubnet": {
          "Description" : "SubnetId in VPC",
          "Type" : "AWS::EC2::Subnet::Id",
          "Default" : ""
        },
    
    
      "Resources" : {
        ...
        "Ec2Instance" : {
          "Properties" : {
            "SubnetId" : { "Ref" : "VpcSubnet" },
    

    【讨论】:

    • 但是如何将它指向已经存在的 VPC 和子网?在您的示例中,我看不到可以插入现有子网和 VPC ID 的地方,例如 vpc-abc123 或 subnet-123456
    • 您将在参数中将它们指定为值。如果您使用 AWS 控制台尝试此操作,则 UI 实际上会以 HTML 表单向您显示选项。试试这个解决方案,你就会看到它是如何工作的。
    【解决方案2】:

    如果您希望使用特定的 VPC 和子网,只需插入它们的值:

    {
      "Resources": {
        "MyServer": {
          "Type": "AWS::EC2::Instance",
          "Properties": {
            "InstanceType": "t2.micro",
            "SubnetId": "subnet-abc123",
            "ImageId": "ami-abcd1234"
          }
        }
    }
    

    子网始终属于 VPC,因此指定子网将自动选择匹配的 VPC。

    【讨论】:

      猜你喜欢
      • 2018-02-05
      • 1970-01-01
      • 2021-11-26
      • 2015-08-13
      • 2022-11-18
      • 2018-03-16
      • 2020-05-03
      • 2017-12-03
      • 2021-06-10
      相关资源
      最近更新 更多