You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过CloudFormation创建不同可用区的公有子网

解决CloudFormation自动在不同可用区创建子网的问题

你当前的Subnet1配置通过Fn::Select选取了可用区列表的第1个元素(索引0),如果第二个子网也用同样的索引,自然会落在同一个可用区。要实现自动分配不同可用区,只需要给第二个子网指定不同的索引值即可,无需手动写死可用区名称。

修改后的完整配置示例:

Subnet1:
  Type: AWS::EC2::Subnet
  DependsOn: NginxVPC
  Properties:
    VpcId: !Ref NginxVPC
    CidrBlock: !Ref Subnet1CidrBlock
    AvailabilityZone: 
      Fn::Select: 
        - 0
        - Fn::GetAZs: ""
    Tags:
      - Key: Name
        Value: !Sub ${AWS::StackName}-Subnet1

Subnet2:
  Type: AWS::EC2::Subnet
  DependsOn: NginxVPC
  Properties:
    VpcId: !Ref NginxVPC
    CidrBlock: !Ref Subnet2CidrBlock
    AvailabilityZone: 
      Fn::Select: 
        - 1
        - Fn::GetAZs: ""
    Tags:
      - Key: Name
        Value: !Sub ${AWS::StackName}-Subnet2

原理说明

  • Fn::GetAZs: ""会自动获取当前栈部署区域的所有可用区列表(比如us-east-1区域会返回["us-east-1a", "us-east-1b", ...])
  • Fn::Select通过索引值从列表中选取对应位置的可用区,Subnet1用索引0,Subnet2用索引1,就能保证两个子网落在不同的可用区,完全适配当前区域,无需手动指定。

内容的提问来源于stack exchange,提问作者MrTux01

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 19:57:22