使用Python CDK向AWS DocumentDB传递密钥值时遇JSON解析错误求助
问题根源与解决方法
你遇到的Could not parse SecretString JSON错误,核心原因是:generated_database_password是单值密钥,它的SecretString是纯密码字符串,而非JSON格式,但你错误地用secret_value_from_json("database_password")去解析它,导致JSON解析失败。
直接修正:获取单值密钥的正确方式
修改CfnCluster中admin_user_password的赋值逻辑,直接取单值Secret的原始值即可:
cluster = docdbelastic.CfnCluster( self, "MongoDbCluster", admin_user_name=f"{props.customer}", auth_type="PLAIN_TEXT", cluster_name=f"{props.customer}-mongodb-cluster", shard_capacity=2, shard_count=4, # 去掉secret_value_from_json,直接用secret_value.unsafe_unwrap() admin_user_password=generated_database_password.secret_value.unsafe_unwrap(), subnet_ids=application_subnet, )
你创建generated_database_password时,仅用SecretStringGenerator生成纯密码,没有指定JSON模板,所以SecretString就是纯文本密码,不需要JSON解析步骤。
可选优化:合并Secret存储
如果不需要单独的密码Secret,可以直接把密码生成到cluster_secret_manager中,减少冗余资源:
import json excluded_characters = "!@#$%^&*()`~,}{[]_=+'?\/<>:-" + '"' # 直接在DbSecrets中生成包含账号和密码的JSON格式Secret cluster_secret_manager = secretsmanager.Secret( self, "DbSecrets", secret_name="db_secret", generate_secret_string=secretsmanager.SecretStringGenerator( password_length=8, exclude_characters=excluded_characters, exclude_punctuation=True, # 指定JSON模板,将生成的密码插入到db_pw字段 secret_string_template=json.dumps({"db_admin": "admin"}), generate_string_key="db_pw" ), ) # 此时用secret_value_from_json提取密码是正确的 cluster = docdbelastic.CfnCluster( self, "MongoDbCluster", admin_user_name=f"{props.customer}", auth_type="PLAIN_TEXT", cluster_name=f"{props.customer}-mongodb-cluster", shard_capacity=2, shard_count=4, admin_user_password=cluster_secret_manager.secret_value_from_json("db_pw").unsafe_unwrap(), subnet_ids=application_subnet, )
这种方式下,SecretString是标准JSON结构,secret_value_from_json可以正确提取出db_pw字段的值。
内容的提问来源于stack exchange,提问作者Jack Rogers
相关产品推荐
相关产品推荐

