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

AWS SAM模板中从Secrets Manager取密钥作为全局变量失败求助

解决AWS SAM模板中从Secrets Manager获取密钥作为Lambda全局环境变量的问题

错误原因

你的问题出在AesKey参数的Default字段使用了!Ref函数——CloudFormation要求参数的默认值必须是静态字符串,不能用函数引用,这就是报错"Every default member must be a string"的直接原因。

正确实现方案

方案一:直接在Lambda环境变量中引用Secrets Manager密钥(推荐)

无需额外定义参数,直接用!GetSecretValue函数从Secrets Manager拉取纯文本密钥,同时必须给Lambda配置读取密钥的权限:

Globals:
  Function:
    Tracing: Active
    Timeout: 60
    Environment:
      Variables:
        AES_KEY: !GetSecretValue
          SecretId: mysecretarn  # 替换为你的密钥ARN或名称
    Policies:
      - SecretsManagerReadPolicy:
          SecretArn: mysecretarn  # 授予Lambda读取该密钥的权限

方案二:通过参数传递密钥ARN(适合动态配置场景)

如果需要用参数传递密钥标识,需将参数默认值设为静态ARN字符串,再在环境变量中用!GetSecretValue引用该参数:

Parameters:
  AesKeySecretArn:
    Type: String
    Default: "arn:aws:secretsmanager:us-east-1:123456789012:secret:mysecret-xxxxxx"  # 静态ARN字符串

Globals:
  Function:
    Tracing: Active
    Timeout: 60
    Environment:
      Variables:
        AES_KEY: !GetSecretValue
          SecretId: !Ref AesKeySecretArn
    Policies:
      - SecretsManagerReadPolicy:
          SecretArn: !Ref AesKeySecretArn

额外注意事项

  • 若密钥是JSON格式(非纯文本),需结合!Sub提取具体字段,示例:
    AES_KEY: !Sub '{{resolve:secretsmanager:${AesKeySecretArn}:SecretString:aes_key}}'
    
  • 确保SAM部署的IAM角色拥有创建Lambda执行角色的权限,否则无法自动配置Secrets Manager访问策略
  • 生产环境建议避免硬编码ARN,可通过SSM参数或外部配置管理密钥标识,提升灵活性

内容的提问来源于stack exchange,提问作者Dāvis Zemītis

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 08:40:22