使用AWS Node.js SDK分配API Key时提示‘无效使用计划ID’问题
问题
使用Node.js版AWS SDK创建API KEY并分配至AWS控制台创建的使用计划时,触发错误:Invalid Usage Plan ID specified。已确认传入的使用计划ID存在于AWS账户中,更换其他使用计划、指定stageKeys均未解决问题。相关代码如下:
export async function createApiKey() { try { const secretKey = crypto.randomUUID(); const params = { description: 'Secret key generate in AWS Apigateway', enabled: true, name: 'secret_key', value: secretKey, }; const Client = new AWS.APIGatewayClient({ region: process.env.AWS_REGION, credentials: { accessKeyId: process.env.AWS_ACCESS_KEY_ID!, secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY!, }, }); const createApiKeyCmd = new AWS.CreateApiKeyCommand(params); const data = await Client.send(createApiKeyCmd); const assignApiKeyCmd = new AWS.CreateUsagePlanKeyCommand({ keyId: data.id!, keyType: 'API_KEY', usagePlanId: process.env.AWS_USAGE_PLAN_ID!, }); await Client.send(assignApiKeyCmd); return { idApiKey: data.id!, secretKey: data.value!, }; } catch (error: any) { throw new Error(error.message); } }
解决方案
- 核对使用计划的区域与格式
确认process.env.AWS_USAGE_PLAN_ID的值是正确的短ID(如abc123xyz)或完整ARN,且该使用计划所在区域与API Gateway客户端配置的region完全一致,跨区域的使用计划ID会触发无效错误。 - 验证IAM权限完整性
确保当前AWS凭证拥有apigateway:CreateUsagePlanKey权限,且权限范围覆盖目标使用计划。可通过IAM策略模拟器验证权限是否生效。 - 排除环境变量读取异常
暂时将usagePlanId硬编码为控制台复制的有效ID,测试是否因环境变量未正确加载导致ID错误。 - 处理资源同步延迟
在创建API KEY后添加100-200ms的延迟再执行绑定操作,部分场景下AWS资源同步存在微小滞后,会导致刚创建的API KEY无法立即关联使用计划。 - 检查使用计划的关联配置
确认目标使用计划已关联至少一个API阶段(Stage),未关联任何阶段的空使用计划可能触发绑定API KEY时的无效ID错误。
内容的提问来源于stack exchange,提问作者José Thomaz Antunes Soares
相关产品推荐
相关产品推荐

