Thiết lập phân quyền truy cập (IAM) cho toàn bộ dịch vụ AWS trong pipeline và bật CloudTrail để giám sát, ghi lại mọi hoạt động trên tài khoản AWS.
→ Đảm bảo bảo mật, kiểm soát truy cập, và minh chứng hoạt động nhóm.
📥 Input
AWS Account với quyền admin
Convention đặt tên dự án: mlops-retail-prediction-dev
Vùng mục tiêu: ap-southeast-1
CloudTrail đa vùng được bật
Input từ Task 1: Task 1 (Introduction) — project conventions, naming, and high-level objectives
✅ Output
💰 Chi phí ước tính ≈ 0.05 USD/tháng (CloudTrail + lưu trữ S3 cho logs)
📌 Các bước chính
✅ Deliverables
📊 Acceptance Criteria
Đi tới S3 Console: AWS Console → S3 → “Create bucket”
Cấu hình Bucket:
Bucket name: mlops-cloudtrail-logs-us-east-1-842676018087
Region: us-east-1 (phải cùng region với CloudTrail trail)
Block all public access: ✅ Enabled
Versioning: ✅ Enabled
Default encryption: ✅ AWS KMS
KMS key: alias/mlops-retail-prediction-dev-cloudtrail-key
Cấu hình Lifecycle Policy:
Bước 1. S3 Console → chọn bucket mlops-cloudtrail-logs-ap-southeast-1 → Management → Create lifecycle rule.

Bước 2. Đặt tên (ví dụ CloudTrailLogLifecycle), Apply to all objects hoặc dùng Prefix mlops-logs/.
Chi tiết các trường cấu hình:
Object tags:
Object size:
Lifecycle rule actions:

Bước 3. Chọn actions (Current versions):

Bước 4. Kiểm tra rule đã Active trong tab Management.

⚠️ Lưu ý về Region:
us-east-1Ngắn gọn: Nếu dữ liệu chính của pipeline (prefix gold/ và artifacts/) nằm trong us-east-1, hãy tạo SageMaker Domain / Project ở us-east-1 để tránh lỗi cross-region (S3 301), phức tạp với KMS keys, và các endpoint khác.
Nếu tổ chức yêu cầu SageMaker phải ở ap-southeast-1, bạn cần sao chép hoặc replicate dữ liệu sang bucket ở ap-southeast-1 trước khi tạo Project. Ví dụ lệnh sync (PowerShell / CloudShell):
aws s3 mb s3://mlops-retail-prediction-dev-842676018087-apse1 --region ap-southeast-1
aws s3 sync s3://mlops-retail-prediction-dev-842676018087/gold/ s3://mlops-retail-prediction-dev-842676018087-apse1/gold/ --acl bucket-owner-full-control
aws s3 sync s3://mlops-retail-prediction-dev-842676018087/artifacts/ s3://mlops-retail-prediction-dev-842676018087-apse1/artifacts/ --acl bucket-owner-full-control
Kèm theo:
Gợi ý: Cho lab và debug nhanh, phương án ít rủi ro là tạo Project/Domain ở nơi bucket hiện có (ở lab này là us-east-1).
us-east-1):Cấu hình Key:
Key type: ✅ Symmetric (mã hóa và giải mã dữ liệu)
Key usage: ✅ Encrypt and decrypt
Thêm labels:
Alias: alias/mlops-retail-prediction-dev-cloudtrail-key
Description (optional): KMS key for CloudTrail logs encryption
Tags (optional):
- Key: Project
- Value: MLOps-Retail-Prediction
Cấu hình quyền quản trị:
Key administrators: Chọn IAM users/roles được phép quản lý key
Key deletion: Có cho phép xóa key hay không
Cấu hình quyền sử dụng:
Key users:
- Thêm service principal: cloudtrail.amazonaws.com
Chỉnh sửa key policy:
{
"Version": "2012-10-17",
"Id": "Key policy created by CloudTrail",
"Statement": [
{
"Sid": "Enable IAM User Permissions",
"Effect": "Allow",
"Principal": {
"AWS": [
"arn:aws:iam::842676018087:root"
]
},
"Action": "kms:*",
"Resource": "*"
},
{
"Sid": "Allow CloudTrail to encrypt logs",
"Effect": "Allow",
"Principal": {
"Service": "cloudtrail.amazonaws.com"
},
"Action": "kms:GenerateDataKey*",
"Resource": "*",
"Condition": {
"StringLike": {
"kms:EncryptionContext:aws:cloudtrail:arn": [
"arn:aws:cloudtrail:*:842676018087:trail/*"
]
},
"StringEquals": {
"aws:SourceArn": "arn:aws:cloudtrail:us-east-1:842676018087:trail/mlops-retail-prediction-audit-trail"
}
}
},
{
"Sid": "Allow CloudTrail to describe key",
"Effect": "Allow",
"Principal": {
"Service": "cloudtrail.amazonaws.com"
},
"Action": "kms:DescribeKey",
"Resource": "*"
}
]
}
Các điểm quan trọng trong KMS policy: Enable IAM User Permissions: Cho phép root account quản lý key Allow CloudTrail to encrypt logs:
{
"Version": "2012-10-17",
"Id": "Key policy created by CloudTrail",
"Statement": [
{
"Sid": "Enable IAM User Permissions",
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::842676018087:root"
},
"Action": "kms:*",
"Resource": "*"
},
{
"Sid": "Allow CloudTrail to encrypt logs",
"Effect": "Allow",
"Principal": {
"Service": "cloudtrail.amazonaws.com"
},
"Action": "kms:GenerateDataKey*",
"Resource": "*",
"Condition": {
"StringEquals": {
"aws:SourceArn": "arn:aws:cloudtrail:us-east-1:842676018087:trail/mlops-retail-prediction-audit-trail"
},
"StringLike": {
"kms:EncryptionContext:aws:cloudtrail:arn": "arn:aws:cloudtrail:*:842676018087:trail/*"
}
}
},
{
"Sid": "Allow CloudTrail to describe key",
"Effect": "Allow",
"Principal": {
"Service": "cloudtrail.amazonaws.com"
},
"Action": "kms:DescribeKey",
"Resource": "*"
},
{
"Sid": "Allow principals in the account to decrypt log files",
"Effect": "Allow",
"Principal": {
"AWS": "*"
},
"Action": [
"kms:Decrypt",
"kms:ReEncryptFrom"
],
"Resource": "*",
"Condition": {
"StringEquals": {
"kms:CallerAccount": "842676018087"
},
"StringLike": {
"kms:EncryptionContext:aws:cloudtrail:arn": "arn:aws:cloudtrail:*:842676018087:trail/*"
}
}
},
{
"Sid": "Enable cross account log decryption",
"Effect": "Allow",
"Principal": {
"AWS": "*"
},
"Action": [
"kms:Decrypt",
"kms:ReEncryptFrom"
],
"Resource": "*",
"Condition": {
"StringEquals": {
"kms:CallerAccount": "842676018087"
},
"StringLike": {
"kms:EncryptionContext:aws:cloudtrail:arn": "arn:aws:cloudtrail:*:842676018087:trail/*"
}
}
}
]
}
Key Policy bao gồm:
KMS key phải được tạo ở cùng Region với S3 bucket và có đúng policy cho phép CloudTrail sử dụng.
Vào S3 bucket permissions:
S3 Console → mlops-cloudtrail-logs-ap-southeast-1 → Permissions → Bucket policy
Policy mặc định cho S3 bucket:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AWSCloudTrailAclCheck",
"Effect": "Allow",
"Principal": {
"Service": "cloudtrail.amazonaws.com"
},
"Action": "s3:GetBucketAcl",
"Resource": "arn:aws:s3:::mlops-cloudtrail-logs-ap-southeast-1-842676018087",
"Condition": {
"StringEquals": {
"aws:SourceArn": "arn:aws:cloudtrail:us-east-1:842676018087:trail/mlops-retail-prediction-audit-trail"
}
}
},
{
"Sid": "AWSCloudTrailWrite",
"Effect": "Allow",
"Principal": {
"Service": "cloudtrail.amazonaws.com"
},
"Action": "s3:PutObject",
"Resource": "arn:aws:s3:::mlops-cloudtrail-logs-ap-southeast-1-842676018087/mlops-logs/AWSLogs/842676018087/*",
"Condition": {
"StringEquals": {
"aws:SourceArn": "arn:aws:cloudtrail:us-east-1:842676018087:trail/mlops-retail-prediction-audit-trail",
"s3:x-amz-acl": "bucket-owner-full-control"
}
}
}
]
}
S3 Bucket Policy bao gồm:
Policy này cho phép CloudTrail kiểm tra ACL của bucket và ghi logs vào bucket.
Bước 1: Tạo Trail mới
AWS Console → us-east-1 → CloudTrail → Create trail
Bước 2: Cấu hình Trail cơ bản (ở region us-east-1)
| Mục | Giá trị |
|---|---|
| Trail name | mlops-retail-prediction-audit-trail |
| Apply trail to all regions | ✅ Yes |
| Management events | ✅ Read/Write |
| Data events | ✅ S3 bucket data events |
| Insights events | ✅ Enabled (phát hiện hành vi bất thường) |
Bước 3: Cấu hình Storage
| Mục | Giá trị |
|---|---|
| S3 bucket | mlops-cloudtrail-logs-ap-southeast-1 |
| Log file prefix | mlops-logs/ |
| Log file SSE-KMS encryption | ✅ Enabled |
| AWS KMS alias | alias/mlops-retail-prediction-dev-cloudtrail-key (chọn key đã tạo) |
Bước 4: Tích hợp CloudWatch Logs (tùy chọn)
| Mục | Giá trị |
|---|---|
| CloudWatch Logs | ✅ Enabled |
| Log group | mlops-cloudtrail-log-group |
| IAM Role | CloudTrail_CloudWatchLogs_Role (auto-created) |
Role CloudTrail_CloudWatchLogs sẽ được tự động tạo với các quyền cần thiết: logs:PutLogEvents, logs:CreateLogStream, logs:DescribeLogStreams
Bước 5: Review và Create trail
Thứ tự quan trọng để tránh lỗi:
AWS service
Service: EKS - Cluster
Policy: AmazonEKSClusterPolicy
Role name: mlops-retail-prediction-dev-eks-cluster-role
Description: EKS cluster service role for retail prediction MLOps platform
AWS service
Service: EC2
✅ AmazonEKSWorkerNodePolicy
✅ AmazonEKS_CNI_Policy
✅ AmazonEC2ContainerRegistryReadOnly
✅ CloudWatchAgentServerPolicy
Role name: mlops-retail-prediction-dev-eks-nodegroup-role
Description: EKS node group role with ECR, S3, and CloudWatch access for retail prediction

Trusted Entity Type:
AWS service
Service: SageMaker
Gán Policies:
✅ AmazonSageMakerFullAccess
✅ AmazonS3FullAccess (cho lưu trữ dữ liệu và model)
✅ CloudWatchLogsFullAccess (cho training job logs)
Thêm Inline Policy cho EC2 (BẮT BUỘC cho Projects):
Policy Name: SageMakerEC2Access
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"ec2:DescribeVpcs",
"ec2:DescribeSubnets",
"ec2:DescribeSecurityGroups",
"ec2:DescribeNetworkInterfaces",
"ec2:DescribeAvailabilityZones",
"ec2:DescribeRouteTables"
],
"Resource": "*"
}
]
}
Cách thêm:
mlops-retail-prediction-dev-sagemaker-executionSageMakerEC2AccessChi tiết Role:
Role name: mlops-retail-prediction-dev-sagemaker-execution
Description: SageMaker execution role for retail prediction training jobs and model deployment
Vì SageMaker Projects là bắt buộc, cần thêm EC2 permissions ngay:
mlops-retail-prediction-dev-sagemaker-execution{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"ec2:DescribeVpcs",
"ec2:DescribeSubnets",
"ec2:DescribeSecurityGroups",
"ec2:DescribeNetworkInterfaces",
"ec2:DescribeAvailabilityZones",
"ec2:DescribeRouteTables"
],
"Resource": "*"
}
]
}
SageMakerEC2Access✅ Xác minh: Role phải có 4 policies:
AmazonSageMakerFullAccess (AWS managed)AmazonS3FullAccess (AWS managed)CloudWatchLogsFullAccess (AWS managed)SageMakerEC2Access (inline policy vừa tạo)SageMaker Unified Studio (2024+) yêu cầu:
Nếu thiếu EC2 permissions:
✅ GIẢI PHÁP:
Kiểm tra trạng thái CloudTrail: AWS Console → CloudTrail → Trails
✅ mlops-retail-prediction-audit-trail: Active
✅ Multi-region trail: Enabled
✅ Management events: Read/Write
✅ Data events: S3 configured
✅ CloudWatch Logs: Integrated
Xác minh S3 Logging: AWS Console → S3 → mlops-cloudtrail-logs-ap-southeast-1
✅ Log files được tạo: /mlops-logs/AWSLogs/[account-id]/CloudTrail/
✅ Encryption: SSE-S3 enabled
✅ Lifecycle policy: Applied
✅ Access logging: Configured
Đi tới IAM → Roles và kiểm tra:
✅ mlops-retail-prediction-dev-eks-cluster-role
✅ mlops-retail-prediction-dev-eks-nodegroup-role
✅ mlops-retail-prediction-dev-sagemaker-execution
✅ CloudTrail_CloudWatchLogs_Role (auto-created)
Kiểm tra Trust Relationships:
eks.amazonaws.com (EKS cluster role)ec2.amazonaws.com (EKS node group role)sagemaker.amazonaws.com (SageMaker execution role)cloudtrail.amazonaws.com (CloudTrail logging role)Kiểm tra CloudTrail Logging:
Kiểm tra quyền IAM:
# Test SageMaker role có thể assume và truy cập S3
aws sts assume-role --role-arn arn:aws:iam::ACCOUNT:role/mlops-retail-prediction-dev-sagemaker-execution --role-session-name test
Kiểm tra SageMaker role đầy đủ:
# Test S3 access
aws s3 ls s3://mlops-retail-prediction-dev-ACCOUNT/ --profile sagemaker-test
# Test SageMaker training job permissions
aws sagemaker list-training-jobs --region us-east-1 --profile sagemaker-test
# Test EC2 permissions (nếu đã thêm)
aws ec2 describe-vpcs --region us-east-1 --profile sagemaker-test
# Test EKS roles sẵn sàng cho việc tạo cluster
aws eks describe-cluster --name test-cluster --region ap-southeast-1
| Hạng mục | Đơn giá | Ghi chú / Assumptions | Ví dụ ước tính |
|---|---|---|---|
| S3 — Standard | $0.023 / GB‑month | Hot logs (ngày 0–30) | 1 GB → $0.023 |
| S3 — Standard‑IA | $0.0125 / GB‑month | Sau 30 ngày (truy cập ít) | 1 GB → $0.0125 |
| S3 — Glacier | $0.004 / GB‑month | Lưu trữ dài hạn (90–365 ngày) | 1 GB → $0.004 |
| S3 — Deep Archive | $0.00099 / GB‑month | Retention >365 ngày | 1 GB → $0.00099 |
| CloudTrail — Management events | Miễn phí (bản sao đầu tiên) | Management API calls | — |
| CloudTrail — Data events | $0.10 / 100,000 events | S3 object-level, Lambda, v.v. | 100k events → $0.10 |
| CloudTrail — Insights | $0.35 / 100,000 events | Tùy chọn phát hiện bất thường | 100k events → $0.35 |
Tình huống mẫu (ước tính hàng tháng)
Ghi chú ngắn:
Cảnh báo: Các lệnh bên dưới sẽ xóa tài nguyên thực tế. Kiểm tra tên tài nguyên (bucket, role, trail, key) trước khi chạy.
PowerShell (AWS CLI):
# Xóa trail (nếu tên chính xác)
aws cloudtrail delete-trail --name mlops-retail-prediction-audit-trail
# Nếu muốn tắt ghi sang CloudWatch Logs trước
aws cloudtrail update-trail --name mlops-retail-prediction-audit-trail --cloud-watch-logs-log-group-arn "" --cloud-watch-logs-role-arn ""
Lưu ý: Bucket có thể nằm ở us-east-1 theo cấu hình trên. Kiểm tra aws s3 ls/console trước khi xóa.
# Xóa tất cả objects (recursive)
aws s3 rm s3://mlops-cloudtrail-logs-ap-southeast-1 --recursive
# Xóa bucket
aws s3api delete-bucket --bucket mlops-cloudtrail-logs-ap-southeast-1 --region us-east-1
KMS keys không thể bị xóa ngay lập tức nếu đang được sử dụng. Ta nên lên lịch xóa an toàn (ví dụ 7 ngày):
# Tìm KeyId từ alias
$keyId = aws kms list-aliases --query "Aliases[?AliasName=='alias/mlops-retail-prediction-dev-cloudtrail-key'].TargetKeyId" --output text
# Lên lịch xóa key (pending days: 7 - 30)
aws kms schedule-key-deletion --key-id $keyId --pending-window-in-days 7
Quy trình an toàn: 1) Detach managed policies 2) Xóa inline policies 3) Xóa role.
# Ví dụ: xóa SageMaker execution role
$roleName = 'mlops-retail-prediction-dev-sagemaker-execution'
# 1) Liệt kê và detach managed policies
aws iam list-attached-role-policies --role-name $roleName --query 'AttachedPolicies[].PolicyArn' --output text | ForEach-Object { aws iam detach-role-policy --role-name $roleName --policy-arn $_ }
# 2) Xóa inline policies
aws iam list-role-policies --role-name $roleName --query 'PolicyNames' --output text | ForEach-Object { aws iam delete-role-policy --role-name $roleName --policy-name $_ }
# 3) Xóa role
aws iam delete-role --role-name $roleName
# Lặp lại cho các role khác (EKS cluster/nodegroup, CloudTrail_CloudWatchLogs_Role, GitHub/CI roles, v.v.)
# Xóa CloudWatch log group (nếu có)
aws logs delete-log-group --log-group-name "/aws/containerinsights/mlops-retail-cluster/application" || Write-Host 'Log group not found'
# Xóa CloudWatch log group cho CloudTrail integration
aws logs delete-log-group --log-group-name "mlops-cloudtrail-log-group" || Write-Host 'Log group not found'
# Disable Container Insights addon from EKS (nếu áp dụng)
aws eks delete-addon --cluster-name mlops-retail-cluster --addon-name amazon-cloudwatch-observability
# Xóa images theo tag
aws ecr batch-delete-image --repository-name mlops/retail-api --image-ids imageTag=dev,imageTag=staging || Write-Host 'No matching images or already deleted'
# Xóa untagged images (thận trọng)
aws ecr describe-images --repository-name mlops/retail-api --filter tagStatus=UNTAGGED --query 'imageDetails[].imageDigest' --output text | ForEach-Object { aws ecr batch-delete-image --repository-name mlops/retail-api --image-ids imageDigest=$_ }
# Stop in-progress training jobs with name pattern
aws sagemaker list-training-jobs --name-contains "retail-" --status-equals InProgress --query 'TrainingJobSummaries[].TrainingJobName' --output text | ForEach-Object { aws sagemaker stop-training-job --training-job-name $_ }
# Delete failed endpoints
aws sagemaker list-endpoints --name-contains "retail-" --query 'Endpoints[?EndpointStatus==`Failed`].EndpointName' --output text | ForEach-Object { aws sagemaker delete-endpoint --endpoint-name $_ }
# Delete pending model packages in model group (thận trọng: giữ các approved)
aws sagemaker list-model-packages --model-package-group-name "retail-forecast-models" --model-approval-status PendingManualApproval --query 'ModelPackageSummaryList[].ModelPackageArn' --output text | ForEach-Object { aws sagemaker delete-model-package --model-package-name $_ }
# Kiểm tra trail đã bị xóa
aws cloudtrail describe-trails --query 'trailList[?Name==`mlops-retail-prediction-audit-trail`]' || Write-Host 'Trail removed or not found'
# Kiểm tra bucket
aws s3 ls s3://mlops-cloudtrail-logs-ap-southeast-1 2>$null || Write-Host 'Bucket removed or empty'
# Kiểm tra IAM role
aws iam get-role --role-name mlops-retail-prediction-dev-sagemaker-execution 2>$null || Write-Host 'Role removed'
# Kiểm tra KMS key scheduled deletion
aws kms list-keys --query 'Keys[?KeyId==`'$keyId'`]' || Write-Host 'Check key deletion schedule manually in KMS console'
Nếu bạn muốn, tôi có thể:
ForEach-Object bằng các script an toàn hơn để preview danh sách tài nguyên trước khi xóa.✅ CloudTrail Multi-Region - Bản ghi kiểm toán toàn diện cho tất cả hoạt động AWS
✅ Lưu trữ Audit S3 - Lưu giữ log tối ưu chi phí với lifecycle policies
✅ Role Bảo mật EKS - Quyền cho cluster và node group đã sẵn sàng
✅ Role Thực thi SageMaker - Training jobs + Projects ready (EC2 permissions BẮT BUỘC)
✅ Nền tảng Bảo mật - Kiến trúc least-privilege chuẩn doanh nghiệp
✅ Sẵn sàng Tuân thủ - Audit trail phù hợp với yêu cầu pháp lý
💰 Chi phí hàng tháng: ~0.05 USD (CloudTrail + lưu trữ S3)
🔍 Phủ sóng kiểm toán: 100% các API call và hoạt động người dùng
🛡️ Tư thế bảo mật: Quyền truy cập theo nguyên tắc least-privilege, sẵn sàng cho production
🚀 Bước tiếp theo:
🔐 Lưu ý bảo mật: