</>Học Dev
Bài học

Tuần 1 - Ngày 5: AWS CLI và SDK

Tuần 1 – Ngày 5

Tuần 1 - Ngày 5: AWS CLI và SDK

Mục tiêu học tập

  • Cài đặt và cấu hình AWS CLI v2
  • Hiểu Credentials Provider Chain
  • Biết dùng Named Profiles, MFA với CLI
  • Phân biệt CLI, SDK, CloudShell, CDK

1. AWS CLI (Command Line Interface)

Định nghĩa

AWS CLI là tool dòng lệnh để tương tác với AWS services qua API.

Phiên bản

  • AWS CLI v2 (recommended) — bundled Python, faster, better UX
  • AWS CLI v1 — legacy, đã sắp deprecated

Cài đặt

# macOS
brew install awscli
# Or:
curl "https://awscli.amazonaws.com/AWSCLIV2.pkg" -o "AWSCLIV2.pkg"
sudo installer -pkg AWSCLIV2.pkg -target /

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

# Windows: tải MSI installer từ https://aws.amazon.com/cli/

# Verify
aws --version
# Output: aws-cli/2.x.x Python/3.x.x ...

2. Configure CLI

Cách 1: aws configure (đơn giản nhất)

$ aws configure
AWS Access Key ID [None]: AKIAxxxxxxxxxxxx
AWS Secret Access Key [None]: xxxxxxxxxxxxxxxxxxxx
Default region name [None]: us-east-1
Default output format [None]: json

→ Tạo 2 files:

  • ~/.aws/credentials (chứa keys)
  • ~/.aws/config (chứa region, output format)

Cấu trúc files

# ~/.aws/credentials
[default]
aws_access_key_id = AKIAxxxxxxxxxxxx
aws_secret_access_key = xxxxxxxxxxxxxxxxxxxx

[dev]
aws_access_key_id = AKIAyyyyyyyyyyyy
aws_secret_access_key = yyyyyyyyyyyyyyyyyyyy

# ~/.aws/config
[default]
region = us-east-1
output = json

[profile dev]
region = ap-southeast-1
output = table

Dùng Named Profile

# Default profile
aws s3 ls

# Specific profile
aws s3 ls --profile dev

# Or via env var
export AWS_PROFILE=dev
aws s3 ls

3. Credentials Provider Chain

AWS CLI/SDK tìm credentials theo thứ tự ưu tiên sau (dừng ở cái đầu tiên tìm thấy):

1.Command-lineoptions--access-key,--secret-key,--session-token2.EnvironmentVariablesAWS_ACCESS_KEY_IDAWS_SECRET_ACCESS_KEYAWS_SESSION_TOKEN3.AWSSSO(singlesign-on)awsconfiguresso4.WebIdentityToken(Cognito,OIDC)5.Sharedcredentialsfile~/.aws/credentials(profilemcđnhhocAWS_PROFILE)6.Sharedconfigfile~/.aws/config7.Containercredentials(ECS/Fargate)AWS_CONTAINER_CREDENTIALS_RELATIVE_URI8.EC2InstanceProfile(IMDSv2)http://169.254.169.254/latest/meta-data/iam/security-credentials/<role>

Best practice

  • Local dev: AWS SSO hoặc named profile
  • EC2: IAM Role attach vào instance (không hard-code key)
  • ECS/Fargate: Task Role
  • Lambda: Execution Role
  • CI/CD: OIDC federation (GitHub Actions, GitLab) thay vì long-lived keys

4. CLI Output Formats

# JSON (default)
aws ec2 describe-instances

# Table (human-readable)
aws ec2 describe-instances --output table

# Text (tab-separated)
aws ec2 describe-instances --output text

# YAML
aws ec2 describe-instances --output yaml

Filter và Query

# --filters: server-side filter (tiết kiệm bandwidth)
aws ec2 describe-instances \
  --filters "Name=instance-state-name,Values=running"

# --query: client-side JMESPath (filter sau khi nhận response)
aws ec2 describe-instances \
  --query 'Reservations[*].Instances[*].[InstanceId,InstanceType,State.Name]'

# Kết hợp
aws ec2 describe-instances \
  --filters "Name=tag:Environment,Values=production" \
  --query 'Reservations[*].Instances[*].InstanceId' \
  --output text

5. MFA với CLI

Khi IAM user yêu cầu MFA, CLI cần token tạm thời:

# Lấy temporary credentials với MFA
aws sts get-session-token \
  --serial-number arn:aws:iam::111111111111:mfa/alice \
  --token-code 123456 \
  --duration-seconds 3600

# Response:
# {
#   "Credentials": {
#     "AccessKeyId": "ASIA...",
#     "SecretAccessKey": "...",
#     "SessionToken": "...",
#     "Expiration": "..."
#   }
# }

Hoặc cấu hình profile auto-prompt MFA:

# ~/.aws/config
[profile dev-mfa]
mfa_serial = arn:aws:iam::111111111111:mfa/alice
role_arn = arn:aws:iam::222222222222:role/CrossAccountRole
source_profile = default
aws s3 ls --profile dev-mfa
# CLI sẽ prompt: Enter MFA code:

6. AWS CloudShell

Định nghĩa

CloudShell là browser-based shell trong AWS Console, đã preinstall AWS CLI, Python, Node.js, Git.

Đặc điểm

  • Miễn phí (không tốn EC2)
  • 1 GB persistent storage mỗi Region (lưu home directory)
  • Authenticated tự động bằng identity console hiện tại
  • Available ở 1 số Region (us-east-1, eu-west-1, ap-southeast-1...)
  • Idle timeout: 20-30 phút

Use case

  • Run AWS CLI command nhanh mà không cần setup local
  • Học AWS CLI trong môi trường an toàn
  • Quick scripts mà không cần local environment

7. AWS SDK

Định nghĩa

SDK (Software Development Kit) là thư viện cho phép app gọi AWS APIs từ code.

Các SDK chính

Ngôn ngữPackage
Pythonboto3
JavaScript/Node.js@aws-sdk/client-* (v3 modular)
Javaaws-sdk-java-v2
.NETAWSSDK.* (NuGet)
Gogithub.com/aws/aws-sdk-go-v2
PHP, Ruby, C++, Rust...

Ví dụ Python boto3

import boto3

# Tạo S3 client (auto picks credentials từ provider chain)
s3 = boto3.client('s3', region_name='us-east-1')

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

# Upload file
s3.upload_file('local.txt', 'my-bucket', 'remote.txt')

# Resource API (higher-level)
s3_res = boto3.resource('s3')
bucket = s3_res.Bucket('my-bucket')
for obj in bucket.objects.all():
    print(obj.key)

8. AWS CDK (Cloud Development Kit) — Khái niệm

Định nghĩa

CDK cho phép define infrastructure bằng code (TypeScript, Python, Java, C#, Go) thay vì YAML/JSON CloudFormation.

Workflow

CDK code (TypeScript)
       │
       ▼
   cdk synth  →  CloudFormation template (JSON/YAML)
       │
       ▼
   cdk deploy →  AWS CloudFormation creates resources

Ưu điểm so với CloudFormation thuần

  • Type safety, autocomplete
  • Reusable constructs (L1/L2/L3)
  • Loops, conditionals (logic của ngôn ngữ chính)
  • Test với unit test framework

9. So sánh các tools

ToolKhi nào dùng
AWS ConsoleExplore service, click nhanh
AWS CLIScript, automation, CI/CD
AWS SDKBuild application
AWS CloudShellCLI without local setup
CloudFormationIaC declarative (JSON/YAML)
AWS CDKIaC programmatic (code)
TerraformMulti-cloud IaC (3rd party)

10. Common CLI Commands cheatsheet

# S3
aws s3 ls
aws s3 cp file.txt s3://my-bucket/
aws s3 sync ./local s3://my-bucket/path/

# EC2
aws ec2 describe-instances
aws ec2 start-instances --instance-ids i-xxxx
aws ec2 stop-instances --instance-ids i-xxxx
aws ec2 run-instances --image-id ami-xxx --instance-type t3.micro

# IAM
aws iam list-users
aws iam list-roles
aws iam get-user

# STS (Security Token Service)
aws sts get-caller-identity   # "Whoami" cho AWS

# CloudFormation
aws cloudformation deploy --template-file stack.yaml --stack-name my-stack

# Help
aws help                    # Top-level help
aws s3 help                 # Service help
aws s3 cp help              # Command help

Câu hỏi ôn tập

  1. EC2 instance cần access S3 — nên cấu hình credentials theo cách nào?

    Xem đáp án

    Attach IAM Role (Instance Profile) vào EC2 instance. SDK/CLI trên instance sẽ tự động lấy temporary credentials từ Instance Metadata Service (IMDSv2) tại http://169.254.169.254. Không cần cấu hình gì thêm trong code — credentials được rotate tự động mỗi giờ. Tuyệt đối không hard-code Access Key ID/Secret trong code, config file, hay environment variable trên server.

  2. Liệt kê thứ tự ưu tiên trong Credentials Provider Chain (top 3)?

    Xem đáp án

    (1) Command-line options (--access-key, --secret-key) — cao nhất. (2) Environment variables (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN). (3) AWS SSO session (aws configure sso). Tiếp theo: Web Identity Token, shared credentials file (~/.aws/credentials), config file, container credentials, EC2 Instance Profile. Chain dừng tại entry đầu tiên tìm thấy.

  3. AWS CloudShell có tính phí không?

    Xem đáp án

    Miễn phí. CloudShell không tính phí compute riêng. Bạn được 1 GB persistent storage miễn phí mỗi Region (home directory). Chỉ tính phí nếu CloudShell thực hiện AWS API calls tạo resources (ví dụ launch EC2) — nhưng bản thân shell không có phí. Tự động authenticated bằng identity đang đăng nhập Console.

  4. Khác biệt giữa --filters--query trong AWS CLI?

    Xem đáp án

    --filtersserver-side filtering — AWS xử lý filter trước khi trả response, tiết kiệm bandwidth và thời gian với dataset lớn. --queryclient-side filtering (JMESPath) — AWS trả toàn bộ response, CLI filter local. Kết hợp cả hai: --filters giảm data từ server, --query extract fields cần thiết từ response. --filters chỉ hoạt động với các fields AWS hỗ trợ filter; --query linh hoạt hơn với bất kỳ field nào trong JSON.

  5. CDK khác CloudFormation ở điểm gì?

    Xem đáp án

    CDK cho phép define infrastructure bằng ngôn ngữ lập trình (TypeScript, Python, Java, Go...) với type safety, autocomplete, loops, conditionals, và unit tests. CDK compile ra CloudFormation template (cdk synth) rồi deploy qua CloudFormation. CloudFormation thuần dùng YAML/JSON declarative — verbose hơn và không có logic programming. CDK có L2/L3 constructs (high-level abstractions) giúp viết ít code hơn cho patterns phổ biến.

Bài tập thực hành

  • Cài AWS CLI v2 và chạy aws configure
  • Tạo 2 profiles (default, dev) và chuyển đổi giữa chúng
  • Chạy aws sts get-caller-identity xem account đang dùng
  • List tất cả EC2 instances trong tất cả Region (describe-regions + loop)
  • Setup AWS SSO với aws configure sso
  • Thử CloudShell trong AWS Console

Tài liệu tham khảo chính thức


Tiếp theo: Quiz Tuần 1