Get a Secrets Manager secret value using the Python Amazon SDK - Amazon Secrets Manager
Services or capabilities described in Amazon Web Services documentation might vary by Region. To see the differences applicable to the China Regions, see Getting Started with Amazon Web Services in China (PDF).

Get a Secrets Manager secret value using the Python Amazon SDK

In applications, you can retrieve your secrets by calling GetSecretValue or BatchGetSecretValuein any of the Amazon SDKs. However, we recommend that you cache your secret values by using client-side caching. Caching secrets improves speed and reduces your costs.

For Python applications, use the Secrets Manager Python-based caching component or call the SDK directly with get_secret_value or batch_get_secret_value.

The following code examples show how to use GetSecretValue.

Required permissions: secretsmanager:GetSecretValue

class GetSecretWrapper: def __init__(self, secretsmanager_client): self.client = secretsmanager_client def get_secret(self, secret_name): """ Retrieve individual secrets from AWS Secrets Manager using the get_secret_value API. This function assumes the stack mentioned in the source code README has been successfully deployed. This stack includes 7 secrets, all of which have names beginning with "mySecret". :param secret_name: The name of the secret fetched. :type secret_name: str """ try: get_secret_value_response = self.client.get_secret_value( SecretId=secret_name ) logging.info("Secret retrieved successfully.") return get_secret_value_response["SecretString"] except self.client.exceptions.ResourceNotFoundException: msg = f"The requested secret {secret_name} was not found." logger.info(msg) return msg except Exception as e: logger.error(f"An unknown error occurred: {str(e)}.") raise