Serverless.yml中SSM动态路径创建解析报错如何解决?
Serverless框架动态SSM参数路径解析报错解决方案
问题复现
需求为生成动态SSM路径作为自定义变量,给Lambda函数填充安全组配置值,原有配置如下:
自定义变量块:
custom securityGroupSsmPath: dev: "${self:service}/${self:custom.stage}/rds/lambdasecuritygroup" other: "${self:service}/${env:SHARED_INFRASTRUCTURE_ENV}/rds/lambdasecuritygroup" securityGroupId: ${ssm:, "${self:custom.securityGroupSsmPath.${env:SHARED_INFRASTRUCTURE_ENV}, self:custom.securityGroupSsmPath.other}"}
函数引用配置:
functions: someLambda: handler: build/handlers/someLambda/handler.handler timeout: 60 memorySize: 256 vpc: securityGroupIds: - ${self:custom.securityGroupId}
部署时报错:
Serverless Error ---------------------------------------- Cannot resolve serverless.yml: Variables resolution errored with: - Cannot resolve variable at "custom.securityGroupId": Parameter name: can't be prefixed with "ssm" (case-insensitive). If formed as a path, it can consist of sub-paths divided by slash symbol; each sub-path can be formed as a mix of letters, numbers and the following 3 symbols .-_
错误原因
两个核心语法问题:
- YAML基础语法错误:
custom作为顶级键后面漏了冒号,本身就不符合YAML格式规范 - SSM变量插值语法完全错位:
${ssm:xxx}的格式要求ssm:后直接跟合法的参数路径,你在ssm:后多写了逗号、手动加了双引号,这些符号都会被解析器当成SSM参数路径的一部分,直接触发参数名校验失败的报错。另外你把路径fallback逻辑和SSM取值逻辑混写在同一个插值块里,嵌套顺序完全错了。
修正后的配置
把路径解析和SSM取值拆成两层,去掉多余的符号即可:
custom: # 建议给stage加默认值,避免本地不传stage参数时解析失败 stage: ${opt:stage, 'dev'} securityGroupSsmPath: dev: "${self:service}/${self:custom.stage}/rds/lambdasecuritygroup" other: "${self:service}/${env:SHARED_INFRASTRUCTURE_ENV}/rds/lambdasecuritygroup" # 第一步:先解析出最终要取的SSM参数路径 resolvedSecurityGroupPath: ${self:custom.securityGroupSsmPath.${env:SHARED_INFRASTRUCTURE_ENV}, self:custom.securityGroupSsmPath.other} # 第二步:把解析好的路径传入ssm变量取值,不要加多余引号、逗号 securityGroupId: ${ssm:${self:custom.resolvedSecurityGroupPath}}
排查提示
- Serverless的变量插值不需要手动加引号,所有引号都会被当做值的一部分参与解析,很容易触发格式错误
- 如果修正后报参数不存在,先单独输出
resolvedSecurityGroupPath的值,确认和AWS Parameter Store里存储的参数路径完全一致 - 提前确认Lambda执行角色已经绑定了对应SSM参数的读取权限,避免部署后运行时拿不到参数值
内容的提问来源于stack exchange,提问作者SamBrick
相关产品推荐
相关产品推荐

