从 AWS 秘密管理器中提取数据库详细信息会引发错误 - Python

Extract db details from AWS secret manager throws an error - Python

我正在使用下面的 Python 代码从密码管理器中提取数据库详细信息,但仍然出现相同的错误 'Unable to locate credentials'。我做错了什么?

import boto3  # Required to interact with AWS
import psycopg2
import base64
from botocore.exceptions import ClientError

secret_name = "X"
region_name = "X"

session = boto3.session.Session()

client = session.client(
    service_name='secretsmanager',
    region_name=region_name
)

try:
    get_secret_value_response = client.get_secret_value(
        SecretId=secret_name
    )
except ClientError as e:
    if e.response['Error']['Code'] == 'ResourceNotFoundException':
        print("The requested secret " + secret_name + " was not found")
    elif e.response['Error']['Code'] == 'InvalidRequestException':
        print("The request was invalid due to:", e)
    elif e.response['Error']['Code'] == 'InvalidParameterException':
        print("The request had invalid params:", e)
else:
    # Decrypted secret using the associated KMS CMK
    # Depending on whether the secret was a string or binary, one of these fields will be populated
    if 'SecretString' in get_secret_value_response:
        secret = json.loads(get_secret_value_response['SecretString'])
    else:
        binary_secret_data = get_secret_value_response['SecretBinary']

user = secret['username']
password = secret['password']
db_name = secret['dbname']
host = secret['host']

conn = psycopg2.connect(host='host',port='5432',database=db_name, user=user, password=password)

您需要配置 AWS 凭证以与 AWS API 交互,否则您会收到 Unable to locate credentials 错误。

有多种配置凭据的方法,因此只需检查此 doc 并选择最适合您需要的方法。