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

解决AWS多环境部署Serverless时的"Invalid API Key identifier specified"错误

多环境部署Serverless服务时API Key冲突导致部署失败

场景与配置

使用Serverless Framework将Lambda函数部署到AWS的prod和dev两个环境,通过SSM存储的API Key保护API接口,初始配置如下:

serverless.yml

service: my-service
frameworkVersion: "3"

provider:
  name: aws
  runtime: nodejs16.x
  region: eu-central-1
  apiGateway:
    apiKeys:
      - name: my-apikey
        value: ${ssm:my-apikey}

functions:
  v1_myfunc:
    handler: src/api/myfunc/get_func.get
    events:
      - http:
          path: /v1/myfunc
          method: get
          private: true

plugins:
  - serverless-esbuild
  - serverless-offline
  - serverless-dotenv-plugin

package.json 部署脚本

"scripts": {
  "deploy:dev": "serverless deploy --stage dev",
  "deploy:prod": "serverless deploy --stage prod"
}

问题现象

单独部署某一个环境时一切正常,但部署另一个环境(比如先部署prod再部署dev)时,会出现如下错误:

Deploying my-service to stage dev (eu-central-1)

✖ Stack my-service-dev failed to deploy (46s)
Environment: darwin, node 16.15.0, framework 3.23.0, plugin 6.2.2, SDK 4.3.2
Credentials: Local, "default" profile

Error:
Invalid API Key identifier specified
error Command failed with exit code 1.

查看AWS控制台发现两个环境生成的API Key ID相同,推测两个栈共用了同一个API Key实例。尝试为每个环境设置不同的API Key名称(name: my-apikey-${self:provider.stage})后,问题仍未解决。

解决方案

问题的核心是:AWS不允许两个不同的API Key实例使用相同的value值。之前仅修改了API Key的name,但value仍然指向同一个SSM参数,导致第二个环境部署时,AWS识别到该value已被另一个API Key占用,从而报错。

需要修改serverless.yml的API Key配置,让每个环境使用独立的SSM参数和API Key:

修改后的serverless.yml 关键配置

provider:
  # 其他配置不变
  apiGateway:
    apiKeys:
      - name: my-apikey-${self:provider.stage}
        value: ${ssm:my-apikey-${self:provider.stage}}

配套操作

  1. 在AWS SSM参数存储中,分别创建两个独立的参数:
    • my-apikey-dev:存入dev环境的API Key值
    • my-apikey-prod:存入prod环境的API Key值
  2. 重新执行对应环境的部署命令即可。

可选方案:自动生成API Key值

如果不需要自行指定固定的API Key值,可以让Serverless Framework自动为每个环境生成唯一的API Key,配置简化为:

provider:
  # 其他配置不变
  apiGateway:
    apiKeys:
      - name: my-apikey-${self:provider.stage}

部署完成后,可通过AWS控制台或CLI获取对应环境自动生成的API Key值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 05:50:27