Đề bài: Sử dụng thư viện boto3 trong Python để tạo mật khẩu ngẫu nhiên (random password) trong AWS Secrets Manager.
Cách tiếp cận / Thuật toán
Bước 1: Import boto3 và botocore.exceptions để xử lý ngoại lệ.
Bước 2: Không có tham số bắt buộc cho hàm này.
Bước 3: Tạo phiên làm việc AWS bằng boto3. Đảm bảo region_name được cấu hình; nếu không, truyền rõ ràng.
Bước 4: Tạo client AWS cho dịch vụ secretsmanager.
Bước 5: Gọi get_random_password và truyền các tham số theo độ phức tạp mong muốn.
Bước 6: Trả về một mật khẩu ngẫu nhiên.
Bước 7: Xử lý ngoại lệ chung nếu có lỗi khi tạo mật khẩu.
Mã ví dụ
Sử dụng mã sau để tạo mật khẩu ngẫu nhiên:
import boto3
from botocore.exceptions import ClientError
def generate_random_password():
session = boto3.session.Session()
s3_client = session.client('secretsmanager')
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("Lỗi client boto3 trong generate_random_password: " + e.__str__())
except Exception as e:
raise Exception("Lỗi không mong muốn trong generate_random_password: " + e.__str__())
a = generate_random_password()
print(a["RandomPassword"])
Kết quả
mcwJ6tLfN0uidY9zcY