メインコンテンツまでスキップ

AWS Console, CLI & SDK

Có ba cách chính để tương tác với AWS: Management Console (giao diện web), AWS CLI (command line) và AWS SDK (lập trình). Mỗi công cụ phù hợp với những tình huống khác nhau — hiểu rõ khi nào dùng gì sẽ giúp bạn làm việc hiệu quả hơn đáng kể.


1. Tổng quan

Ba cách tương tác với AWS

Công cụMô tảPhù hợp nhất
Management ConsoleGiao diện web đồ họa tại console.aws.amazon.comKhám phá dịch vụ mới, debug thủ công, quản lý billing
AWS CLICông cụ dòng lệnh, có thể scripting và automationCI/CD pipeline, cron job, deploy script, bulk operations
AWS SDKThư viện lập trình (Python, JS, Go, Java...)Application backend, event-driven workload, Infrastructure as Code tùy chỉnh

Khi nào dùng gì?

Console   → Tìm hiểu tính năng mới, xem log CloudWatch, tạo resource lần đầu
CLI → Lặp lại thao tác nhiều lần, deploy trong pipeline, script tự động hóa
SDK → Tích hợp AWS vào code ứng dụng, gọi API có điều kiện phức tạp
Rule of thumb

Nếu bạn làm thao tác đó hơn 2 lần — hãy chuyển sang CLI. Nếu logic phức tạp hơn một vài lệnh — dùng SDK.


2. AWS CLI v2

AWS CLI v2 là gì?

AWS CLI v2 là phiên bản hiện tại của công cụ dòng lệnh chính thức do AWS phát triển. Nó cho phép bạn kiểm soát hầu hết các dịch vụ AWS từ terminal.

So sánh CLI v1 vs v2

Tính năngCLI v1CLI v2
Cài đặtpip install awscliBinary độc lập, không cần Python
SSOKhông hỗ trợ nativeHỗ trợ AWS SSO (aws sso login)
Auto-promptKhông có--cli-auto-prompt gợi ý tham số
OutputJSON, text, tableThêm YAML; --output yaml-stream
PagerKhông cóTự động dùng less
Credential ManagementFile-basedTích hợp keychain/Secret Service
Khuyến nghị

Luôn dùng CLI v2. CLI v1 vẫn hoạt động nhưng không còn được phát triển tính năng mới.

Cài đặt

Linux (x86_64)

curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
unzip awscliv2.zip
sudo ./aws/install

Linux (ARM / Graviton)

curl "https://awscli.amazonaws.com/awscli-exe-linux-aarch64.zip" -o "awscliv2.zip"
unzip awscliv2.zip
sudo ./aws/install

macOS

# Dùng pkg installer (khuyến nghị)
curl "https://awscli.amazonaws.com/AWSCLIV2.pkg" -o "AWSCLIV2.pkg"
sudo installer -pkg AWSCLIV2.pkg -target /

# Hoặc dùng Homebrew
brew install awscli

Windows

Tải file .msi từ: https://awscli.amazonaws.com/AWSCLIV2.msi và chạy installer.

Hoặc dùng PowerShell:

msiexec.exe /i https://awscli.amazonaws.com/AWSCLIV2.msi

Kiểm tra sau khi cài

aws --version
# aws-cli/2.x.x Python/3.x.x Linux/... botocore/2.x.x

Các lệnh cơ bản

# Xem help tổng quát
aws help

# Xem help cho một service
aws s3 help
aws ec2 describe-instances help

# Cấu hình credentials (interactive)
aws configure

# Liệt kê S3 buckets
aws s3 ls

# Liệt kê nội dung một bucket
aws s3 ls s3://my-bucket/

# Xem thông tin caller identity
aws sts get-caller-identity

3. Xác thực & Credentials

Các loại credentials

LoạiMô tảDùng khi
Access Key IDĐịnh danh (bắt đầu bằng AKIA...)Xác định "ai" đang gọi
Secret Access KeyMật khẩu của Access KeyKý request (không bao giờ chia sẻ)
Session TokenToken tạm thời kèm expiryKhi dùng IAM Role, SSO, AssumeRole
Không bao giờ commit credentials

Secret Access Key lộ ra GitHub là tình huống khẩn cấp. AWS scanner tự động phát hiện và gửi cảnh báo — nhưng kẻ tấn công có thể đã dùng trước đó rồi.

Cấu hình bằng aws configure

aws configure
# AWS Access Key ID [None]: ...
# AWS Secret Access Key [None]: ...
# Default region name [None]: ap-northeast-1
# Default output format [None]: json

Lệnh này tạo ra hai file:

~/.aws/credentials

[default]
aws_access_key_id = AKIA...
aws_secret_access_key = ...

~/.aws/config

[default]
region = ap-northeast-1
output = json

Named Profiles — làm việc với nhiều AWS account

Khi bạn cần làm việc với nhiều account (dev, staging, production) hoặc nhiều IAM user, sử dụng named profiles.

Tạo profile thủ công trong ~/.aws/credentials:

[default]
aws_access_key_id = AKIA...
aws_secret_access_key = ...

[<project-name>-dev]
aws_access_key_id = AKIA...DEV
aws_secret_access_key = ...

[<project-name>-prd]
aws_access_key_id = AKIA...PROD
aws_secret_access_key = ...

~/.aws/config tương ứng:

[default]
region = ap-northeast-1
output = json

[profile <project-name>-dev]
region = ap-northeast-1
output = json

[profile <project-name>-prd]
region = us-east-1
output = json

Sử dụng profile:

# Dùng flag --profile
aws s3 ls --profile <project-name>-dev
aws ec2 describe-instances --profile <project-name>-prd

# Dùng biến môi trường (ưu tiên cao hơn flag)
export AWS_PROFILE=<project-name>-dev
aws s3 ls

# Đặt lại về default
unset AWS_PROFILE

AWS SSO Profile

AWS IAM Identity Center (SSO) cho phép đăng nhập bằng tài khoản công ty (Google Workspace, Okta, Active Directory...) thay vì quản lý Access Key thủ công — đây là cách được khuyến nghị trong môi trường doanh nghiệp.

Cấu hình ~/.aws/config:

[profile my-dev]
sso_start_url = https://my-company.awsapps.com/start
; sso_session = my-sso-session
sso_region = ap-northeast-1
sso_account_id = 123456789012
sso_role_name = DeveloperAccess
region = ap-northeast-1
output = json

[profile my-staging]
sso_start_url = https://my-company.awsapps.com/start
sso_region = ap-northeast-1
sso_account_id = 222222222222
sso_role_name = DeployRole
region = ap-northeast-1
output = json

Đăng nhập qua SSO:

aws sso login --profile my-dev

CLI sẽ in ra một URL và mở trình duyệt tự động (hoặc bạn copy URL vào browser):

Attempting to automatically open the SSO authorization page in your default browser.
If the browser does not open or you wish to use a different device to authorize this request, open the following URL:

https://device.sso.ap-northeast-1.amazonaws.com/?user_code=ABCD-EFGH

Then enter the code: ABCD-EFGH

Truy cập link, chọn Allow để cấp quyền. Sau khi allow xong, terminal sẽ thông báo:

Successfully logged into Start URL: https://my-company.awsapps.com/start

Sử dụng sau khi đăng nhập:

# Dùng bình thường với --profile
aws s3 ls --profile my-dev
aws ec2 describe-instances --profile my-staging

# Hoặc set AWS_PROFILE
export AWS_PROFILE=my-dev
aws sts get-caller-identity
Session hết hạn

SSO session thường hết hạn sau 8–12 giờ (tùy cấu hình của admin). Khi nhận lỗi Token has expired, chỉ cần chạy lại aws sso login --profile <tên-profile>.


4. Credential Provider Chain

AWS CLI và SDK không chỉ đọc từ ~/.aws/credentials. Chúng tìm credentials theo một thứ tự ưu tiên cố định — gọi là Credential Provider Chain.

Thứ tự ưu tiên

1. Environment Variables
AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN

2. AWS Profile (--profile flag hoặc AWS_PROFILE env var)

3. ~/.aws/credentials file (profile [default])

4. ~/.aws/config file (profile [default])

5. Container credentials (ECS Task Role)
http://169.254.170.2/v2/credentials/{id}

6. Instance Metadata Service (EC2 IAM Role)
http://169.254.169.254/latest/meta-data/iam/security-credentials/

Ví dụ thực tế

# Trong CI/CD pipeline — dùng environment variables
export AWS_ACCESS_KEY_ID="AKIA..."
export AWS_SECRET_ACCESS_KEY="..."
export AWS_DEFAULT_REGION="ap-northeast-1"
aws s3 sync ./dist s3://my-bucket/

# Trên EC2 có IAM Role — không cần set gì cả, SDK tự lấy
aws s3 ls # Hoạt động nhờ Instance Profile gắn vào EC2
EC2 & ECS

Nếu chạy trên EC2 hoặc ECS có IAM Role gắn vào, bạn không cần cấu hình credentials thủ công. AWS SDK tự động lấy temporary credentials từ metadata service và tự renew khi hết hạn.


5. AssumeRole — Làm việc với nhiều AWS Account

aws sts assume-role là lệnh quan trọng nhất khi bạn cần:

  • Truy cập tài nguyên ở account khác (cross-account)
  • Chạy với quyền cao hơn tạm thời
  • Automation trong CI/CD cần switch giữa nhiều account

Cấu trúc AssumeRole

Ví dụ: Assume role vào account production

# Bước 1: Lấy temporary credentials
aws sts assume-role \
--role-arn "arn:aws:iam::123456789012:role/DeployRole" \
--role-session-name "deploy-session-$(date +%s)" \
--duration-seconds 3600 \
--output json

# Output trả về:
# {
# "Credentials": {
# "AccessKeyId": "ASIA...",
# "SecretAccessKey": "...",
# "SessionToken": "...",
# "Expiration": "2026-04-15T10:00:00Z"
# }
# }

Script assume-role tái sử dụng

#!/bin/bash
assume_role() {
local role_arn="$1"
local session_name="${2:-session-$(date +%s)}"

local access_key_id secret_access_key session_token
read -r access_key_id secret_access_key session_token <<< "$(aws sts assume-role \
--role-arn "$role_arn" \
--role-session-name "$session_name" \
--query 'Credentials.[AccessKeyId,SecretAccessKey,SessionToken]' \
--output text)"

export AWS_ACCESS_KEY_ID="$access_key_id"
export AWS_SECRET_ACCESS_KEY="$secret_access_key"
export AWS_SESSION_TOKEN="$session_token"

echo "Assumed role: $role_arn"
aws sts get-caller-identity
}

# Dùng:
assume_role "arn:aws:iam::123456789012:role/DeployRole" "ci-deploy"

Named profile với AssumeRole (khuyến nghị)

Cách tốt hơn là cấu hình trong ~/.aws/config để CLI tự động assume role:

~/.aws/credentials (long-lived credentials của base account):

[<project-name>-dev]
aws_access_key_id = AKIA...
aws_secret_access_key = ...

~/.aws/config (AssumeRole profiles):

[profile <project-name>-dev]
region = ap-northeast-1

[profile <project-name>-stg]
role_arn = arn:aws:iam::222222222222:role/StagingDeployRole
source_profile = <project-name>-dev
region = ap-northeast-1

[profile <project-name>-prd]
role_arn = arn:aws:iam::333333333333:role/ProductionReadOnlyRole
source_profile = <project-name>-dev
region = us-east-1
mfa_serial = arn:aws:iam::111111111111:mfa/my-device
# CLI tự động AssumeRole khi dùng profile này
aws s3 ls --profile <project-name>-dev
aws ec2 describe-instances --profile <project-name>-prd # Sẽ hỏi MFA code

6. AWS SDK

Giới thiệu

AWS SDK là thư viện cho phép gọi AWS API trực tiếp từ code ứng dụng. AWS cung cấp SDK cho hầu hết ngôn ngữ phổ biến:

Ngôn ngữSDKInstall
Pythonboto3pip install boto3
JavaScript/Node@aws-sdk/client-* (v3)npm install @aws-sdk/client-s3
Goaws-sdk-go-v2go get github.com/aws/aws-sdk-go-v2
JavaAWS SDK for Java v2Maven/Gradle
Rubyaws-sdk-rubygem install aws-sdk

Ví dụ Python (boto3) — S3

import boto3

# SDK tự động dùng Credential Provider Chain
s3 = boto3.client('s3', region_name='ap-northeast-1')

# List buckets
response = s3.list_buckets()
for bucket in response['Buckets']:
print(bucket['Name'])

# Upload file
s3.upload_file(
Filename='./report.pdf',
Bucket='my-bucket',
Key='reports/2026/report.pdf'
)

# Download file
s3.download_file(
Bucket='my-bucket',
Key='reports/2026/report.pdf',
Filename='/tmp/report.pdf'
)

Ví dụ Python (boto3) — SNS Publish

import boto3
import json

sns = boto3.client('sns', region_name='ap-northeast-1')

# Publish message
response = sns.publish(
TopicArn='arn:aws:sns:ap-northeast-1:{Account ID}:my-topic',
Message=json.dumps({
'event': 'deploy_completed',
'service': 'api',
'environment': 'production',
'version': 'v1.2.3'
}),
Subject='Deploy Notification',
MessageAttributes={
'event_type': {
'DataType': 'String',
'StringValue': 'deploy'
}
}
)

print(f"Message ID: {response['MessageId']}")

Ví dụ Python (boto3) — AssumeRole trong code

import boto3

def get_cross_account_client(service, role_arn, region='ap-northeast-1'):
"""Tạo boto3 client với credentials từ AssumeRole."""
sts = boto3.client('sts')

assumed = sts.assume_role(
RoleArn=role_arn,
RoleSessionName='cross-account-session'
)

creds = assumed['Credentials']

return boto3.client(
service,
region_name=region,
aws_access_key_id=creds['AccessKeyId'],
aws_secret_access_key=creds['SecretAccessKey'],
aws_session_token=creds['SessionToken']
)

# Dùng:
s3 = get_cross_account_client(
's3',
'arn:aws:iam::123456789012:role/ReadOnlyRole'
)
s3.list_buckets()

Khi nào dùng SDK thay CLI?

Tình huốngCông cụ phù hợp
Upload file một lầnCLI
Upload file dựa trên điều kiện trong codeSDK
Gọi API theo event (SQS consumer, Lambda)SDK
Parse và xử lý response phức tạpSDK
Shell script trong CI/CDCLI
App cần retry, pagination tự độngSDK

7. Best Practices

Không hardcode credentials

# ❌ Sai — không bao giờ làm thế này
s3 = boto3.client(
's3',
aws_access_key_id='<access-key-id>',
aws_secret_access_key='<secret-access-key>'
)

# ✅ Đúng — để SDK tự lấy qua Credential Provider Chain
s3 = boto3.client('s3')

# ✅ Hoặc dùng environment variables (cho CI/CD)
# AWS_ACCESS_KEY_ID và AWS_SECRET_ACCESS_KEY được set bên ngoài

Dùng IAM Role thay Access Key khi có thể

EC2 / ECS / Lambda → Gán IAM Role trực tiếp, không cần Access Key
CI/CD (GitHub Actions) → OpenID Connect (OIDC) với IAM Role, không cần long-lived key
Local Dev → Named profile hoặc aws sso login

Principle of Least Privilege

// ❌ Quá rộng
{
"Effect": "Allow",
"Action": "*",
"Resource": "*"
}

// ✅ Chỉ những gì cần thiết
{
"Effect": "Allow",
"Action": [
"s3:GetObject",
"s3:PutObject"
],
"Resource": "arn:aws:s3:::my-bucket/uploads/*"
}

Rotate credentials định kỳ

# Xem danh sách Access Keys của user
aws iam list-access-keys --user-name my-user

# Tạo Access Key mới
aws iam create-access-key --user-name my-user

# Sau khi cập nhật key mới vào mọi nơi, xóa key cũ
aws iam delete-access-key \
--user-name my-user \
--access-key-id AKIAOLDKEYEXAMPLE
Key Rotation

AWS khuyến nghị rotate Access Key mỗi 90 ngày. Dùng IAM Access AnalyzerAWS Config Rule access-keys-rotated để tự động phát hiện key quá hạn.