paint-brush
Cách tôi tự động sao lưu AWS WorkMail cho nhiều người dùngby@th3n00bc0d3r
233

Cách tôi tự động sao lưu AWS WorkMail cho nhiều người dùng

Muhammad Bilal15m2024/05/27
Read on Terminal Reader

AWS WorkMail là dịch vụ lịch và email mạnh mẽ kết hợp tính bảo mật, độ tin cậy và tính dễ sử dụng. Bằng cách tận dụng AWS WorkMail, các tổ chức có thể tập trung vào các hoạt động cốt lõi của mình mà không phải lo lắng về sự phức tạp trong việc quản lý cơ sở hạ tầng email. Trong hướng dẫn này, tôi sẽ hướng dẫn bạn quy trình tự động hóa sao lưu Amazon WorkMail cho nhiều người dùng, xử lý tối đa 10 tác vụ xuất hộp thư đồng thời.
featured image - Cách tôi tự động sao lưu AWS WorkMail cho nhiều người dùng
Muhammad Bilal HackerNoon profile picture
0-item

AWS WorkMail là dịch vụ lịch và email mạnh mẽ kết hợp tính bảo mật, độ tin cậy và tính dễ sử dụng. Sự tích hợp của nó với các dịch vụ AWS và khả năng tương thích với các ứng dụng email hiện tại khiến nó trở thành một lựa chọn hấp dẫn cho các doanh nghiệp muốn hợp lý hóa việc quản lý email và lịch của họ trong khi vẫn đảm bảo tính bảo mật và tuân thủ. Bằng cách tận dụng AWS WorkMail, các tổ chức có thể tập trung vào các hoạt động cốt lõi của mình mà không phải lo lắng về sự phức tạp trong việc quản lý cơ sở hạ tầng email. Việc thiết lập hệ thống sao lưu đáng tin cậy cho AWS WorkMail là rất quan trọng để đảm bảo rằng email của bạn được an toàn và có thể phục hồi dễ dàng. Trong hướng dẫn này, tôi sẽ hướng dẫn bạn quy trình tự động hóa sao lưu AWS WorkMail cho nhiều người dùng, xử lý tối đa 10 tác vụ xuất hộp thư đồng thời. Chúng tôi sẽ sử dụng các dịch vụ AWS và Python để tạo ra giải pháp sao lưu mạnh mẽ.


Ah! Tôi nhớ có lần tôi đang sử dụng máy chủ thư CPANEL và sau đó can thiệp vào máy chủ thư của chính mình. Những máy chủ thư đơn phiên bản có quyền truy cập hạn chế vào địa chỉ IP vào đầu những năm 2010 hoạt động trơn tru, nhưng khi ngày càng có nhiều người trên toàn thế giới bắt đầu khai thác những máy chủ này, Comon, chúng tôi vẫn nhận được rất nhiều thư rác và nội dung tiếp thị. Mọi việc thật khó khăn để đảm bảo email của bạn không rơi vào hộp thư rác.


Việc lựa chọn giữa AWS WorkMail, máy chủ thư tự lưu trữ và máy chủ thư cPanel phụ thuộc vào một số yếu tố, bao gồm ngân sách, chuyên môn kỹ thuật, nhu cầu về khả năng mở rộng và yêu cầu bảo mật.


  • AWS WorkMail lý tưởng cho các doanh nghiệp đang tìm kiếm giải pháp email có thể mở rộng, bảo mật và được quản lý với chi phí bảo trì tối thiểu.
  • Máy chủ Thư Tự Lưu trữ phù hợp với các tổ chức có chuyên môn kỹ thuật nội bộ và có nhu cầu tùy chỉnh cụ thể nhưng đòi hỏi chi phí và nỗ lực bảo trì cao hơn.
  • cPanel Mail Server cung cấp một cách tiếp cận cân bằng cho các doanh nghiệp vừa và nhỏ cần giao diện thân thiện với người dùng và thoải mái với một số mức độ bảo trì, được hưởng lợi từ các dịch vụ lưu trữ đi kèm.


Mối quan tâm chính của tôi luôn là như sau;

Bảo vệ

  • AWS WorkMail : Cung cấp các tính năng bảo mật tích hợp, bao gồm mã hóa khi truyền và khi lưu trữ, tích hợp với Dịch vụ quản lý khóa AWS (KMS) và tuân thủ các tiêu chuẩn quy định khác nhau.
  • Máy chủ thư tự lưu trữ : Bảo mật phụ thuộc hoàn toàn vào chuyên môn của quản trị viên. Yêu cầu cấu hình để mã hóa, lọc thư rác và cập nhật bảo mật thường xuyên để bảo vệ khỏi các mối đe dọa.
  • cPanel Mail Server : Cung cấp các tính năng bảo mật nhưng trách nhiệm thực hiện và duy trì các biện pháp bảo mật thuộc về người dùng. cPanel cung cấp các công cụ để cấu hình SSL/TLS, lọc thư rác và chống vi-rút, nhưng việc thiết lập phù hợp và cập nhật thường xuyên là điều cần thiết.


Sau đó, AWS đã ra tay giải cứu và kể từ khi sử dụng AWS từ năm 2015, mọi việc trở nên dễ dàng, ngoại trừ trường hợp xảy ra trường hợp tôi phải sao lưu Tài khoản AWS của mình để chuyển sang tài khoản mới. Chà, tôi đã tìm kiếm trên internet để tìm một giải pháp đáng tin cậy vì cho đến thời điểm hiện tại, AWS WorkMail không cung cấp cách đơn giản để sao lưu email của bạn vào máy tính cục bộ hoặc S3, và đó là có thể hiểu được dựa trên việc tuân thủ bảo mật, tuy nhiên, tôi vẫn mong rằng AWS sẽ cung cấp một số GUI hoặc công cụ cho việc đó. Trong khi duyệt, tôi đã tìm thấy các công cụ chắc chắn TRẢ TIỀN, vì vậy tôi quyết định đi theo con đường phát triển công cụ đó của riêng mình. Sau khi kiểm tra nghiêm ngặt, dựa trên kinh nghiệm của tôi với AWS, sự cố 9/10 luôn xảy ra khi một dịch vụ không thể giao tiếp với dịch vụ kia do vấn đề về chính sách hoặc vai trò IAM.


Đây là đóng góp của tôi cho tất cả những người đang gặp khó khăn trong việc sao lưu Tài khoản thư công việc AWS.


Sao lưu hoạt động như thế nào?


Chúng tôi đã tạo Vai trò IAM trong tài khoản của bạn, cấp cho vai trò quyền truy cập để xuất từ AWS WorkMail, sau đó chúng tôi đính kèm chính sách với vai trò tương tự để cho phép vai trò đó truy cập S3. Sau đó, chúng tôi tạo Khóa KMS để cấp quyền truy cập vào Vai trò IAM. Nhóm S3 cũng cần quyền truy cập vào vai trò IAM để hoạt động bình thường.

Bước 1: Định cấu hình AWS CLI

Trước tiên, hãy đảm bảo rằng AWS CLI được cài đặt và định cấu hình bằng thông tin xác thực phù hợp. Mở terminal của bạn và chạy:

 aws configure

Làm theo lời nhắc để đặt ID khóa truy cập AWS, Khóa truy cập bí mật, vùng mặc định và định dạng đầu ra.

Bước 2: Thiết lập tài nguyên AWS cần thiết

Chúng ta cần tạo vai trò IAM, chính sách, nhóm S3 và khóa KMS. Lưu tập lệnh bash sau dưới dạng setup_workmail_export.sh .

 #!/bin/bash # Configuration ROLE_NAME="WorkMailExportRole" POLICY_NAME="workmail-export" S3_BUCKET_NAME="s3.bucket.name" AWS_REGION="your-region" ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text) # Create Trust Policy cat <<EOF > trust-policy.json { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": "export.workmail.amazonaws.com" }, "Action": "sts:AssumeRole", "Condition": { "StringEquals": { "sts:ExternalId": "$ACCOUNT_ID" } } } ] } EOF # Create IAM Role aws iam create-role --role-name $ROLE_NAME --assume-role-policy-document file://trust-policy.json # Create IAM Policy cat <<EOF > role-policy.json { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "s3:*", "Resource": [ "arn:aws:s3:::$S3_BUCKET_NAME", "arn:aws:s3:::$S3_BUCKET_NAME/*" ] }, { "Effect": "Allow", "Action": [ "kms:Decrypt", "kms:GenerateDataKey" ], "Resource": "*" } ] } EOF # Attach the Policy to the Role aws iam put-role-policy --role-name $ROLE_NAME --policy-name $POLICY_NAME --policy-document file://role-policy.json # Create S3 Bucket aws s3api create-bucket --bucket $S3_BUCKET_NAME --region $AWS_REGION --create-bucket-configuration LocationConstraint=$AWS_REGION # Create Key Policy cat <<EOF > key-policy.json { "Version": "2012-10-17", "Id": "workmail-export-key", "Statement": [ { "Sid": "Enable IAM User Permissions", "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::$ACCOUNT_ID:root" }, "Action": "kms:*", "Resource": "*" }, { "Sid": "Allow administration of the key", "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::$ACCOUNT_ID:role/$ROLE_NAME" }, "Action": [ "kms:Create*", "kms:Describe*", "kms:Enable*", "kms:List*", "kms:Put*", "kms:Update*", "kms:Revoke*", "kms:Disable*", "kms:Get*", "kms:Delete*", "kms:ScheduleKeyDeletion", "kms:CancelKeyDeletion" ], "Resource": "*" } ] } EOF # Create the KMS Key and get the Key ID and ARN using Python for JSON parsing KEY_METADATA=$(aws kms create-key --policy file://key-policy.json) KEY_ID=$(python3 -c "import sys, json; print(json.load(sys.stdin)['KeyMetadata']['KeyId'])" <<< "$KEY_METADATA") KEY_ARN=$(python3 -c "import sys, json; print(json.load(sys.stdin)['KeyMetadata']['Arn'])" <<< "$KEY_METADATA") # Update S3 Bucket Policy cat <<EOF > s3_bucket_policy.json { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::$ACCOUNT_ID:role/$ROLE_NAME" }, "Action": "s3:*" "Resource": [ "arn:aws:s3:::$S3_BUCKET_NAME", "arn:aws:s3:::$S3_BUCKET_NAME/*" ] } ] } EOF # Apply the Bucket Policy aws s3api put-bucket-policy --bucket $S3_BUCKET_NAME --policy file://s3_bucket_policy.json # Clean up temporary files rm trust-policy.json role-policy.json key-policy.json s3_bucket_policy.json # Display the variables required for the backup script cat <<EOF Setup complete. Here are the variables required for the backup script: # Print out the Variables organization_id = 'your-organization-id' user_id = 'your-user-id' s3_bucket_name = '$S3_BUCKET_NAME' s3_prefix = 'workmail-backup/' region = '$AWS_REGION' kms_key_arn = '$KEY_ARN' role_name = '$ROLE_NAME' account_id = '$ACCOUNT_ID' EOF

Làm cho tập lệnh có thể thực thi được và chạy nó:

 chmod +x setup_workmail_export.sh ./setup_workmail_export.sh

Bước 3: Viết tập lệnh sao lưu

Bây giờ, hãy viết tập lệnh Python để xuất hộp thư theo lô 10. Lưu tập lệnh sau dưới dạng workmail_export.py .

 import boto3 import json import time from datetime import datetime # Configuration organization_id = 'your-organization-id' user_emails = { 'user-id-1': '[email protected]', 'user-id-2': '[email protected]', 'user-id-3': '[email protected]', 'user-id-4': '[email protected]', 'user-id-5': '[email protected]', 'user-id-6': '[email protected]', 'user-id-7': '[email protected]', 'user-id-8': '[email protected]', 'user-id-9': '[email protected]', 'user-id-10': '[email protected]', 'user-id-11': '[email protected]', 'user-id-12': '[email protected]' # Add more user ID to email mappings as needed } s3_bucket_name = 's3.bucket.name' region = 'your-region' kms_key_arn = 'arn:aws:kms:your-region:your-account-id:key/your-key-id' role_name = 'WorkMailExportRole' account_id = 'your-account-id' # Get the current date current_date = datetime.now().strftime('%Y-%m-%d') # Set the S3 prefix with the date included s3_prefix_base = f'workmail-backup/{current_date}/' # Initialize AWS clients workmail = boto3.client('workmail', region_name=region) sts = boto3.client('sts', region_name=region) def start_export_job(entity_id, user_email): client_token = str(time.time()) # Unique client token role_arn = f"arn:aws:iam::{account_id}:role/{role_name}" s3_prefix = f"{s3_prefix_base}{user_email}/" try: response = workmail.start_mailbox_export_job( ClientToken=client_token, OrganizationId=organization_id, EntityId=entity_id, Description='Backup job', RoleArn=role_arn, KmsKeyArn=kms_key_arn, S3BucketName=s3_bucket_name, S3Prefix=s3_prefix ) return response['JobId'] except Exception as e: print(f"Failed to start export job for {entity_id}: {e}") return None def check_job_status(job_id): while True: try: response = workmail.describe_mailbox_export_job( OrganizationId=organization_id, JobId=job_id ) print(f"Full Response: {response}") # Log full response for debugging state = response.get('State', 'UNKNOWN') print(f"Job State: {state}") if state in ['COMPLETED', 'FAILED']: break except Exception as e : print(f"Error checking job status for {job_id}: {e}") time.sleep(30) # Wait for 30 seconds before checking again return state def export_mailboxes_in_batches(user_emails, batch_size=10): user_ids = list(user_emails.keys()) for i in range(0, len(user_ids), batch_size): batch = user_ids[i:i+batch_size] job_ids = [] for user_id in batch: user_email = user_emails[user_id] job_id = start_export_job(user_id, user_email) if job_id: print(f"Started export job for {user_email} with Job ID: {job_id}") job_ids.append((user_email, job_id)) for user_email, job_id in job_ids: state = check_job_status(job_id) if state == 'COMPLETED': print(f"Export job for {user_email} completed successfully") else: print(f"Export job for {user_email} failed with state: {state}") def main(): export_mailboxes_in_batches(user_emails) if __name__ == "__main__": main()

Thay thế phần giữ chỗ bằng ID tổ chức AWS WorkMail thực tế, ID người dùng tới ánh xạ email, tên bộ chứa S3, vùng, ARN khóa KMS, tên vai trò và ID tài khoản AWS.


Bước 4: Chạy tập lệnh sao lưu

Đảm bảo bạn đã cài đặt Boto3:

 pip install boto3

Sau đó, thực thi tập lệnh Python:

 python workmail_export.py 


Nhập hộp thư

 import boto3 import json import time # Configuration organization_id = 'your-organization-id' user_import_data = { 'user-id-1': '[email protected]', 'user-id-2': '[email protected]', 'user-id-3': '[email protected]', 'user-id-4': '[email protected]', 'user-id-5': '[email protected]', 'user-id-6': '[email protected]', 'user-id-7': '[email protected]', 'user-id-8': '[email protected]', 'user-id-9': '[email protected]', 'user-id-10': '[email protected]', 'user-id-11': '[email protected]', 'user-id-12': '[email protected]' # Add more user ID to email mappings as needed } s3_bucket_name = 's3.bucket.name' s3_object_prefix = 'workmail-backup/' # Prefix for S3 objects (folders) region = 'your-region' role_name = 'WorkMailImportRole' account_id = 'your-account-id' # Initialize AWS clients workmail = boto3.client('workmail', region_name=region) sts = boto3.client('sts', region_name=region) def start_import_job(entity_id, user_email): client_token = str(time.time()) # Unique client token role_arn = f"arn:aws:iam::{account_id}:role/{role_name}" s3_object_key = f"{s3_object_prefix}{user_email}/export.zip" try: response = workmail.start_mailbox_import_job( ClientToken=client_token, OrganizationId=organization_id, EntityId=entity_id, Description='Import job', RoleArn=role_arn, S3BucketName=s3_bucket_name, S3ObjectKey=s3_object_key ) return response['JobId'] except Exception as e: print(f"Failed to start import job for {entity_id}: {e}") return None def check_job_status(job_id): while True: try: response = workmail.describe_mailbox_import_job( OrganizationId=organization_id, JobId=job_id ) state = response.get('State', 'UNKNOWN') print(f"Job State: {state}") if state in ['COMPLETED', 'FAILED']: break except Exception as e: print(f"Error checking job status for {job_id}: {e}") time.sleep(30) # Wait for 30 seconds before checking again return state def import_mailboxes_in_batches(user_import_data, batch_size=10): user_ids = list(user_import_data.keys()) for i in range(0, len(user_ids), batch_size): batch = user_ids[i:i+batch_size] job_ids = [] for user_id in batch: user_email = user_import_data[user_id] job_id = start_import_job(user_id, user_email) if job_id: print(f"Started import job for {user_email} with Job ID: {job_id}") job_ids.append((user_email, job_id)) for user_email, job_id in job_ids: state = check_job_status(job_id) if state == 'COMPLETED': print(f"Import job for {user_email} completed successfully") else: print(f"Import job for {user_email} failed with state: {state}") def main(): import_mailboxes_in_batches(user_import_data) if __name__ == "__main__": main()


Bằng cách làm theo các bước này, bạn đã thiết lập một hệ thống tự động để sao lưu hộp thư AWS WorkMail của mình, xử lý tối đa 10 tác vụ xuất đồng thời. Giải pháp này đảm bảo rằng email của bạn được lưu trữ an toàn trong bộ chứa S3, được sắp xếp theo email và ngày của người dùng, đồng thời được mã hóa bằng khóa KMS. Thiết lập này cung cấp chiến lược sao lưu mạnh mẽ và có thể mở rộng cho dữ liệu email của tổ chức bạn.


Kho lưu trữ Github: https://github.com/th3n00bc0d3r/AWS-WorkMail-Backup


Vui lòng liên hệ trên LinkedIn của tôi, Ngoài ra, bạn luôn có thể mua cho tôi một ly cà phê