AWS CloudFormation如何配置条件跳过已存在的VPCEndpoint创建
CloudFormation VPC Endpoint重复部署问题解决方案
CloudFormation本身不提供原生的资源存在性自动检测能力,你可以通过以下两种方案实现按需创建VPC Endpoint:
方案一:参数手动控制(稳定无额外依赖,生产环境推荐)
1. 新增控制参数与条件规则
在模板头部新增参数和条件定义:
Parameters: CreateNewVPCEndpoint: Type: String AllowedValues: ["true", "false"] Default: "true" Description: 标记是否需要创建新的execute-api类型VPC Endpoint ExistingVPCEndpointId: Type: String Default: "" Description: 已存在的同类型VPC Endpoint ID,CreateNewVPCEndpoint为false时必填 Conditions: NeedCreateVPCE: !Equals [!Ref CreateNewVPCEndpoint, "true"] UseExistingVPCE: !Equals [!Ref CreateNewVPCEndpoint, "false"]
2. 给VPC Endpoint资源添加创建条件
在原有VPCEndpoint资源配置中新增Condition字段,只有满足条件时才会创建该资源:
VPCEndpoint: Type: AWS::EC2::VPCEndpoint Condition: NeedCreateVPCE # 新增该行控制创建逻辑 Properties: ServiceName: !Join - '' - - com.amazonaws. - !Ref 'AWS::Region' - .execute-api PrivateDnsEnabled: true SecurityGroupIds: - !Ref 9SecurityGroupId SubnetIds: Ref: 8SubnetIds VpcEndpointType: Interface VpcId: Ref: 7VpcId
3. 适配APIGateway的引用逻辑
用!If函数动态选择使用新建的还是已有的VPC Endpoint ID:
APIGateway: Type: AWS::ApiGateway::RestApi Properties: Name: !Ref 1Name EndpointConfiguration: Types: - PRIVATE VpcEndpointIds: - !If [NeedCreateVPCE, !Ref VPCEndpoint, !Ref ExistingVPCEndpointId] Policy: Statement: - Action: 'execute-api:Invoke' Effect: Allow Principal: '*' Resource: 'execute-api:/*' - Action: 'execute-api:Invoke' Condition: StringNotEquals: 'aws:SourceVpce': !If [NeedCreateVPCE, !Ref VPCEndpoint, !Ref ExistingVPCEndpointId] Effect: Deny Principal: '*' Resource: 'execute-api:/*' Version: 2012-10-17
使用时,首次部署设置CreateNewVPCEndpoint=true,后续同VPC同区域部署时设置CreateNewVPCEndpoint=false,传入已创建的VPC Endpoint ID即可。
方案二:自动检测存在性(无需手动传参)
添加自定义Lambda资源,调用EC2的describe_vpc_endpoints接口,查询当前VPC下指定ServiceName的VPC Endpoint是否存在,将查询结果作为条件判断依据,自动跳过已存在资源的创建步骤。
使用该方案需要为Lambda配置EC2资源查询的IAM权限。
内容的提问来源于stack exchange,提问作者Daniel Fulgido
相关产品推荐
相关产品推荐

