如何使用 Boto3 在 AWS Secrets Manager 中生成隨機密碼
問題陳述: 使用 Python 中的 boto3 庫在 AWS Secrets Manager 中生成隨機密碼
解決此問題的方法/演算法
步驟 1: 匯入 boto3 和 botocore 異常以處理異常。
步驟 2: 此處沒有引數。
步驟 3: 使用 boto3 庫建立 AWS 會話。確保在預設配置檔案中提到了 region_name。如果沒有提及,則在建立會話時顯式傳遞 region_name。
步驟 4: 為 secretmanager 建立 AWS 客戶端。
步驟 5: 呼叫 get_random_password 並根據所需的複雜性傳遞引數。
步驟 6: 它返回一個隨機密碼。
步驟 7: 如果在生成隨機密碼時出現錯誤,請處理通用異常。
示例程式碼
使用以下程式碼生成隨機密碼:
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"])
輸出
mcwJ6tLfN0uidY9zcY
廣告