Serverless新手求助:无法在custom块引用Cognito UserPoolId配置AppSync
解决Serverless Custom块中引用Cognito UserPool ID的问题
没问题的,新手遇到这类配置很正常,我来帮你搞定!
因为custom块是Serverless框架直接解析的,不像Resources块是交给CloudFormation处理,所以没法直接用Ref或者Fn::GetAtt。不过我们可以通过CloudFormation输出+Serverless变量引用的方式来解决,步骤如下:
步骤1:在Resources中添加UserPool ID的输出
首先在你的resources部分里添加Outputs,把Cognito UserPool的ID导出:
resources: Resources: # Cognito - User pool CognitoUserPool: Type: AWS::Cognito::UserPool Properties: UserPoolName: abc_xyz_pool # Cognito - Client CognitoUserPoolClient: Type: AWS::Cognito::UserPoolClient Properties: ClientName: abc_xyz_pool GenerateSecret: false UserPoolId: Ref: CognitoUserPool # Cognito - Identity CognitoIdentityPool: Type: AWS::Cognito::IdentityPool Properties: IdentityPoolName: sc_identity_pool AllowUnauthenticatedIdentities: false CognitoIdentityProviders: - ClientId: Ref: CognitoUserPoolClient ProviderName: Fn::GetAtt: [CognitoUserPool, ProviderName] # 添加Outputs部分 Outputs: CognitoUserPoolId: Value: Ref: CognitoUserPool Export: Name: ${self:service}-${self:provider.stage}-userPoolId
这里的Export.Name结合了服务名和部署阶段名,能避免不同环境的输出冲突。
步骤2:在Custom块中引用输出的UserPool ID
现在你可以在custom块里用Serverless的变量语法来引用这个输出的ID了:
custom: accountId: 123xxxxxxxx appSync: apiId: 123xyzxxxxxxx # only required for update-appsync authenticationType: AMAZON_COGNITO_USER_POOLS userPoolConfig: awsRegion: ap-southeast-1 defaultAction: ALLOW userPoolId: ${cf:${self:service}-${self:provider.stage}.CognitoUserPoolId}
${cf:栈名.输出名}是Serverless用来引用CloudFormation栈输出的标准变量格式,其中${self:service}-${self:provider.stage}会自动替换成你的服务名和部署阶段(比如dev、prod),确保引用的是当前栈的正确输出。
测试一下部署,这样你的AppSync就能正确关联到你创建的Cognito UserPool啦!
内容的提问来源于stack exchange,提问作者Muhammad Shoaib
相关产品推荐
相关产品推荐

