How to use Boto3 to generate a random password in AWS Secret Manager

AWSBoto3PythonServer Side ProgrammingProgramming

Problem Statement: Use boto3 library in Python to generate a random password in AWS Secret Manager

Approach/Algorithm to solve this problem

  • Step 1: Import boto3 and botocore exceptions to handle exceptions.

  • Step 2: There are no parameters here.

  • 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 get_random_password and pass the parameter as per the desired complexity.

  • Step 6: It returns a random password.

  • Step 7: Handle the generic exception if something went wrong while generating the random password.

Example Code

Use the following code to generate random password −

import boto3
from botocore.exceptions import ClientError

def generate_random_password():
   session = boto3.session.Session()
   s3_client = session.client('secretmanager')
   try:
   response = s3_client.get_random_password(PasswordLength=18,
      ExcludeCharacters="",
       ExcludeNumbers=False,
      ExcludePunctuation=True,
      ExcludeUppercase=False,
      ExcludeLowercase = False,
      IncludeSpace=False,
      RequireEachIncludedType=True
   )
   return response
   except ClientError as e:
      raise Exception("boto3 client error in generate_random_password: " + e.__str__())
   except Exception as e:
      raise Exception("Unexpected error in generate_random_password: " + e.__str__())

a = generate_random_password()
print(a["RandomPassword"])

Output

mcwJ6tLfN0uidY9zcY
raja
Published on 16-Apr-2021 07:50:29
Advertisements