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

AWS CloudFormation中用参数创建Secrets Manager密钥遇变量替换问题

问题解答

核心结论

AWS CloudFormation的AWS::SecretsManager::Secret资源中,GenerateSecretString的SecretStringTemplate字段不支持直接使用CloudFormation参数变量(如${Username})进行替换。原因是该模板字符串由Secrets Manager服务端解析处理,无法识别CloudFormation的参数语法,因此你写的${Username}会被当作普通字符串存入密钥,而不会替换为参数值。

替代方案

根据你的需求场景,有两种可行的替代方案:

方案1:直接使用用户输入的用户名和密码

如果密码是用户提前输入的(而非Secrets Manager自动生成),不需要使用GenerateSecretString,改用SecretString属性,配合CloudFormation的!Sub函数完成变量替换:

AWSTemplateFormatVersion: '2010-09-09'
Resources:
  MySecret:
    Type: 'AWS::SecretsManager::Secret'
    Properties:
      Description: 'My example secret'
      # 用!Sub解析参数,生成最终的JSON字符串
      SecretString: !Sub '{"username": "${Username}", "password": "${Password}"}'
      Tags:
        - Key: 'Name'
          Value: 'MySecret'
Parameters:
  Username:
    Type: String
    Description: 'Username for the secret'
  Password:
    Type: String
    Description: 'Password for the secret'

方案2:指定用户名,让Secrets Manager自动生成密码

如果希望密码由Secrets Manager自动生成,仅需要传入用户名参数,可以结合!Sub和GenerateSecretString的GenerateStringKey属性:

AWSTemplateFormatVersion: '2010-09-09'
Resources:
  MySecret:
    Type: 'AWS::SecretsManager::Secret'
    Properties:
      Description: 'My example secret'
      GenerateSecretString:
        # 先用!Sub替换用户名参数
        SecretStringTemplate: !Sub '{"username": "${Username}"}'
        # 指定要自动生成的密钥字段
        GenerateStringKey: 'password'
        PasswordLength: 16
        ExcludePunctuation: true
      Tags:
        - Key: 'Name'
          Value: 'MySecret'
Parameters:
  Username:
    Type: String
    Description: 'Username for the secret'

关键说明

所有需要替换CloudFormation参数的字符串,都必须通过CloudFormation的内置函数(如!Sub、!Join)预先处理,再传递给Secrets Manager的属性,这样才能确保参数被正确解析替换。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 17:41:22