在AWS CloudFormation中如何指定子网和VPC ID?

3
我希望我的CloudFormation模板使用现有的子网和VPC,不想创建新的。如何设置参数?当我查看AWS :: EC2 :: VPC和AWS :: 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
2个回答

10

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

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

子网总是属于一个VPC,因此指定子网将自动选择匹配的VPC。


5

参数部分指定它们,并在资源部分引用它们。CF将首先让您选择VPC,然后再选择子网

  "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" },

1
但是我该如何将它指向已经存在的VPC和子网呢?在你的例子中,我看不到可以插入我的现有子网和VPC ID(例如vpc-abc123或subnet-123456)的地方。 - red888
您将在参数中指定它们作为值。如果您尝试使用AWS控制台,则UI实际上会在HTML表单中向您呈现选项。只需尝试此解决方案,您就会看到它的工作原理。 - George Whitaker

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接