CloudFormation部署API Gateway报错:无效资源标识符的解决方法
问题
使用CloudFormation模板构建包含AWS API Gateway的栈时,持续遇到以下错误:
Resource handler returned message: "Invalid Resource identifier specified (Service: ApiGateway, Status Code: 404, Request ID: <snip>)" (RequestToken: <snip>, HandlerErrorCode: NotFound)
错误出现在名为MyApiAsyncResource的资源上,模板中API相关部分如下:
AWSTemplateFormatVersion: '2010-09-09' Description: <snip> Resources: MyApi: Type: AWS::ApiGateway::RestApi Properties: Name: "MyRestApi" EndpointConfiguration: Types: - REGIONAL MyApiResource: Type: AWS::ApiGateway::Resource Properties: ParentId: !GetAtt MyApi.RootResourceId PathPart: 'app' RestApiId: !Ref MyApi MyApiDummyMethod: Type: AWS::ApiGateway::Method Properties: HttpMethod: "GET" ResourceId: !Ref MyApiAsyncResource RestApiId: !Ref MyApi AuthorizationType: "NONE" MethodResponses: - StatusCode: '200' MyApiAsyncResource: Type: AWS::ApiGateway::Resource Properties: ParentId: !Ref MyApiResource PathPart: 'async' RestApiId: !Ref MyApi
模板目标是生成GET .../prod/app/async接口。更新的CloudTrail片段如下:
"userAgent": "cloudformation.amazonaws.com", "errorCode": "NotFoundException", "errorMessage": "Invalid Resource identifier specified", "requestParameters": { "parentId": "1p9c4w", "restApiId": "<snip>", "createResourceInput": { "pathPart": "async" }, "template": false },
其中1p9c4w是MyApiResource的物理ID,但该资源已不存在。
原因分析
- 资源创建顺序异常:模板中
MyApiDummyMethod定义在MyApiAsyncResource之前,尽管CloudFormation会自动推断依赖,但部分场景下仍可能出现顺序错误,导致创建MyApiAsyncResource时,其父资源MyApiResource的状态未完全同步。 - 栈状态与实际资源不一致:从CloudTrail日志可见,CloudFormation仍引用已失效的
MyApiResource物理ID,说明之前可能手动删除过API Gateway中的/app资源,或栈的状态已损坏,导致资源引用失效。
修复方案
方案一:显式修正资源依赖(优先推荐)
通过添加DependsOn属性强制指定创建顺序,避免依赖推断异常:
AWSTemplateFormatVersion: '2010-09-09' Description: <snip> Resources: MyApi: Type: AWS::ApiGateway::RestApi Properties: Name: "MyRestApi" EndpointConfiguration: Types: - REGIONAL MyApiResource: Type: AWS::ApiGateway::Resource Properties: ParentId: !GetAtt MyApi.RootResourceId PathPart: 'app' RestApiId: !Ref MyApi MyApiAsyncResource: Type: AWS::ApiGateway::Resource DependsOn: MyApiResource Properties: ParentId: !Ref MyApiResource PathPart: 'async' RestApiId: !Ref MyApi MyApiDummyMethod: Type: AWS::ApiGateway::Method DependsOn: MyApiAsyncResource Properties: HttpMethod: "GET" ResourceId: !Ref MyApiAsyncResource RestApiId: !Ref MyApi AuthorizationType: "NONE" MethodResponses: - StatusCode: '200'
方案二:重置栈状态
若栈状态已损坏(如手动修改过API Gateway资源),可直接删除当前栈(注意备份相关数据),再使用修正后的模板重新创建栈,彻底清理无效状态。
方案三:手动同步资源(临时应急)
若无法删除栈,可手动在API Gateway控制台创建/app/async资源,再更新栈让CloudFormation重新关联资源。此方式易导致后续状态不一致,仅作为临时解决方案。
内容的提问来源于stack exchange,提问作者jtlz2
相关产品推荐
相关产品推荐

