- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to use Boto3 to update the secret keys from a specific location in AWS Secret Manager
Problem Statement: Use boto3 library in Python to update secret keys from specific location in AWS Secret Manager.
Approach/Algorithm to solve this problem
Step 1: Import boto3 and botocore exceptions to handle exceptions.
Step 2: secret_stored_location and secret_key_pair are the required parameters. Make sure secret_key_pair is written as string, not as dict.
Step 3: Create an AWS session using boto3 lib. Make sure region_name is mentioned in the default profile. If it is not mentioned, then explicitly pass the region_name, while creating the session.
Step 4: Create an AWS client for secretmanager.
Step 5: Call update_secret and pass the secret_stored_location as SecretId and secret_key_pair as SecretString.
Step 6: It returns the metadata of updated secret.
Step 7: Handle the generic exception if something went wrong while updating secret.
Example Code
Use the following code to update secrets in AWS secret Manager −
import boto3 from botocore.exceptions import ClientError def update_secret_details(secret_stored_location, secret_key_pair): session = boto3.session.Session() s3_client = session.client('secretmanager') try: response = s3_client.update_secret(SecretId=secret_stored_location,SecretString = secret_key_pair) return response except ClientError as e: raise Exception("boto3 client error in update_secret_details: " + e.__str__()) except Exception as e: raise Exception("Unexpected error in update_secret_details: " + e.__str__()) a = update_secret_details('/secrets/aws', '{"user_test1":"test"}') print(a)
Output
{'ARN': 'arn:aws:secretsmanager:us-east-1:***************:secret:/secrets/aws-wr1Aj6', 'Name': '/secrets/aws', 'VersionId': 'f5308bed-7c23-4d47-a32b-8f2a5f044e53', 'ResponseMetadata': {'RequestId': 'b32fe48d**************ab', 'HTTPStatusCode': 200, 'HTTPHeaders': {'date': 'Sat, 03 Apr 2021 09:40:48 GMT', 'content-type': 'application/x-amz-json-1.1', 'content-length': '197', 'connection': 'keep-alive', 'x-amzn-requestid': *********************************}, 'RetryAttempts': 0}}