Serverless部署AWS应用时引用账号ID遇类型错误的解决咨询
That error pops up because !Ref "AWS::AccountId" is a CloudFormation intrinsic function, but Serverless Framework doesn’t parse CloudFormation functions directly in the custom block. It treats that !Ref as a YAML object instead of a string, which triggers the "non string value" mismatch when you try to reference it later.
Here are the most straightforward fixes:
1. Use Serverless’s Built-in aws.accountId Variable
Serverless automatically pulls your current AWS account ID during deployment, so you can skip defining it in custom entirely and use this built-in variable directly:
provider: name: aws runtime: go1.x stage: dev region: us-east-1 environment: ACCOUNT_ID: ${aws.accountId} myRoleArn: arn:aws:iam::${aws.accountId}:role/xxxxxxxx
This is the simplest approach—no extra setup required, and aws.accountId is guaranteed to be a string, so you won’t hit type issues.
2. Keep It in the custom Block (If Needed)
If you specifically want to retain the account ID in your custom section, use Serverless’s cf variable syntax to resolve the CloudFormation reference properly:
custom: accountId: ${cf:AWS::AccountId} provider: name: aws runtime: go1.x stage: dev region: us-east-1 environment: ACCOUNT_ID: ${self:custom.accountId} myRoleArn: arn:aws:iam::${self:custom.accountId}:role/xxxxxxxx
Quick Note:
CloudFormation functions like !Ref work perfectly in the resources block (where you define native CloudFormation resources), but in Serverless’s top-level config areas (like custom, provider.environment, or custom ARN fields), you need to use Serverless’s own variable resolution system instead of raw CloudFormation syntax.
内容的提问来源于stack exchange,提问作者Dattatray

