· 4 years ago · Apr 16, 2021, 10:40 AM
1
2# Use this code snippet in your app.
3# If you need more information about configurations or implementing the sample code, visit the AWS docs:
4# https://aws.amazon.com/developers/getting-started/python/
5
6import boto3
7import base64
8from botocore.exceptions import ClientError
9import json
10
11def get_secret(secret_name):
12
13 region_name = "us-west-2"
14
15 # Create a Secrets Manager client
16 session = boto3.session.Session()
17 client = session.client(
18 service_name='secretsmanager',
19 region_name=region_name
20 )
21
22 # In this sample we only handle the specific exceptions for the 'GetSecretValue' API.
23 # See https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_GetSecretValue.html
24 # We rethrow the exception by default.
25
26 try:
27 get_secret_value_response = client.get_secret_value(
28 SecretId=secret_name
29 )
30 secret_string = get_secret_value_response['SecretString']
31 return json.loads(secret_string)
32 except ClientError as e:
33 if e.response['Error']['Code'] == 'DecryptionFailureException':
34 # Secrets Manager can't decrypt the protected secret text using the provided KMS key.
35 # Deal with the exception here, and/or rethrow at your discretion.
36 raise e
37 elif e.response['Error']['Code'] == 'InternalServiceErrorException':
38 # An error occurred on the server side.
39 # Deal with the exception here, and/or rethrow at your discretion.
40 raise e
41 elif e.response['Error']['Code'] == 'InvalidParameterException':
42 # You provided an invalid value for a parameter.
43 # Deal with the exception here, and/or rethrow at your discretion.
44 raise e
45 elif e.response['Error']['Code'] == 'InvalidRequestException':
46 # You provided a parameter value that is not valid for the current state of the resource.
47 # Deal with the exception here, and/or rethrow at your discretion.
48 raise e
49 elif e.response['Error']['Code'] == 'ResourceNotFoundException':
50 # We can't find the resource that you asked for.
51 # Deal with the exception here, and/or rethrow at your discretion.
52 raise e
53