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

能否在CloudFormation模板中通过VpcId参数自动查找IGW?

基于VpcId自动关联InternetGateway的CloudFormation实现方案

可以实现无需手动传入InternetGateway参数,核心是通过**自定义资源(Custom Resource)**调用EC2 API查询指定VpcId关联的IGW ID,具体改造步骤如下:

1. 移除冗余参数

删除原模板中的InternetGateway参数,仅保留VpcId参数:

Parameters:
  VpcId:
    Type: AWS::EC2::VPC::Id
    Description: Enter the Existing Landing Zone VPC ID.

2. 添加自定义资源组件

新增Lambda函数用于查询IGW、对应的IAM角色,以及调用该Lambda的自定义资源:

Resources:
  # Lambda函数:查询指定VPC关联的IGW
  GetIGWFunction:
    Type: AWS::Lambda::Function
    Properties:
      Runtime: python3.9
      Handler: index.lambda_handler
      Role: !GetAtt GetIGWFunctionRole.Arn
      Code:
        ZipFile: |
          import boto3
          import json

          ec2 = boto3.client('ec2')

          def lambda_handler(event, context):
              vpc_id = event['ResourceProperties']['VpcId']
              try:
                  # 查询关联目标VPC的IGW
                  response = ec2.describe_internet_gateways(
                      Filters=[{'Name': 'attachment.vpc-id', 'Values': [vpc_id]}]
                  )
                  # 取第一个匹配的IGW(确保VPC仅关联一个IGW)
                  igw_id = response['InternetGateways'][0]['InternetGatewayId']
                  return {
                      'Status': 'SUCCESS',
                      'PhysicalResourceId': igw_id,
                      'Data': {'InternetGatewayId': igw_id}
                  }
              except Exception as e:
                  return {
                      'Status': 'FAILED',
                      'Reason': str(e),
                      'PhysicalResourceId': context.log_stream_name
                  }

  # Lambda执行角色:授予查询IGW的权限
  GetIGWFunctionRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              Service: lambda.amazonaws.com
            Action: sts:AssumeRole
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
      Policies:
        - PolicyName: EC2DescribeIGW
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Effect: Allow
                Action: ec2:DescribeInternetGateways
                Resource: '*'

  # 自定义资源:触发Lambda获取IGW ID
  VpcIGW:
    Type: AWS::CloudFormation::CustomResource
    Properties:
      ServiceToken: !GetAtt GetIGWFunction.Arn
      VpcId: !Ref VpcId

3. 修改路由资源的IGW引用

更新DefaultRoute的GatewayId属性,改为引用自定义资源返回的IGW ID:

DefaultRoute:
    Type: AWS::EC2::Route
    Properties: 
      DestinationCidrBlock: 0.0.0.0/0
      GatewayId: !GetAtt VpcIGW.InternetGatewayId
      RouteTableId: !Ref RouteTable

注意事项

  • 确保目标VPC仅关联一个IGW,否则Lambda会返回第一个匹配的结果,可能不符合预期
  • Lambda角色的权限可根据实际场景限制资源范围,无需全局*权限
  • 若VPC未关联任何IGW,自定义资源会返回错误,栈创建会失败

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 06:50:31