Đề bài – Sử dụng thư viện boto3 trong Python để lấy thông tin ghi nhật ký của một bucket S3. Ví dụ: tìm chi tiết logging của Bucket_1 trong S3.
Phương pháp/Thuật toán giải quyết
Bước 1 – Import boto3 và các ngoại lệ từ botocore để xử lý lỗi.
Bước 2 – Sử dụng bucket_name làm tham số cho hàm.
Bước 3 – Tạo phiên AWS (session) bằng thư viện boto3.
Bước 4 – Tạo client AWS cho dịch vụ S3.
Bước 5 – Gọi hàm get_bucket_logging và truyền tên bucket.
Bước 6 – Hàm trả về một dictionary chứa thông tin chi tiết về bucket S3.
Bước 7 – Xử lý ngoại lệ chung nếu có lỗi xảy ra.
Ví dụ
Sử dụng mã sau để lấy chi tiết ghi nhật ký bucket:
import boto3
from botocore.exceptions import ClientError
def get_bucket_logging_of_s3(bucket_name):
session = boto3.session.Session()
s3_client = session.client('s3')
try:
result = s3_client.get_bucket_logging(Bucket=bucket_name)
except ClientError as e:
raise Exception("Lỗi client boto3 trong get_bucket_logging_of_s3: " + e.__str__())
except Exception as e:
raise Exception("Lỗi không mong đợi trong hàm get_bucket_logging_of_s3: " + e.__str__())
return result
print(get_bucket_logging_of_s3("Bucket_1"))
Kết quả
{
'LoggingEnabled': {
'TargetBucket': 'string',
'TargetGrants': [
{
'Grantee': {
'DisplayName': 'string',
'EmailAddress': 'string',
'ID': 'string',
'Type': 'CanonicalUser'|'AmazonCustomerByEmail'|'Group',
'URI': 'string'
},
'Permission': 'FULL_CONTROL'|'READ'|'WRITE'
},
],
'TargetPrefix': 'string'
}
}