AWS Learning
Monitoring & Management

AWS Systems Manager State Manager

Associations, Desired State, Targeting, Scheduling, Automation Runbooks, Configuration Drift

Tổng quan

State Manager là tool trong AWS Systems Manager giúp tự động duy trì trạng thái mong muốn (desired state) trên managed nodes và các AWS resources khác.

┌─────────────────────────────────────────────────────────────────────────────┐
│                        State Manager                                        │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│   VẤN ĐỀ: Configuration Drift                                               │
│   ─────────────────────────────                                             │
│   • Server A cài antivirus, Server B quên                                   │
│   • Dev tắt firewall rule rồi quên bật lại                                  │
│   • Instance mới launch thiếu software cần thiết                            │
│   • SSH config bị thay đổi thủ công                                         │
│                                                                             │
│   GIẢI PHÁP: State Manager Associations                                     │
│   ──────────────────────────────────────                                    │
│   • Định nghĩa trạng thái mong muốn (desired state)                         │
│   • Tự động apply lên tất cả target nodes                                   │
│   • Lên lịch chạy định kỳ → phát hiện & fix drift                           │
│   • Nodes mới tự động nhận cấu hình khi match target                        │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘

[!IMPORTANT] State Manager MIỄN PHÍ hoàn toàn. Không tính phí cho associations hay executions.


Khái niệm cốt lõi — Association

Association là đơn vị cấu hình chính của State Manager — nó định nghĩa:

Thành phầnVai tròVí dụ
SSM DocumentHành động cần thực hiệnAWS-RunShellScript, AWS-ConfigureAWSPackage
ParametersTham số cho documentTên package, commands cần chạy
TargetsNodes/resources áp dụngTag Environment=Production, tất cả nodes
ScheduleKhi nào chạyrate(1 day), cron(0 2 ? * SUN *)
Rate ControlsKiểm soát tốc độ deployConcurrency: 10, Error Threshold: 5%
┌─────────────────────────────────────────────────────────────────────────────┐
│                          Association                                        │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│   ┌──────────────┐    ┌──────────────┐    ┌──────────────┐                  │
│   │ SSM Document │    │   Targets    │    │   Schedule   │                  │
│   │              │    │              │    │              │                  │
│   │ "CÀI CÁI GÌ" │    │ "CÀI Ở ĐÂU"  │    │ "CÀI KHI NÀO"│                  │
│   └──────┬───────┘    └──────┬───────┘    └──────┬───────┘                  │
│          │                   │                   │                          │
│          └───────────────────┼───────────────────┘                          │
│                              │                                              │
│                              ▼                                              │
│                    ┌──────────────────┐                                     │
│                    │  State Manager   │                                     │
│                    │  thực thi trên   │                                     │
│                    │  managed nodes   │                                     │
│                    └──────────────────┘                                     │
│                                                                             │
│   Giới hạn: Mỗi managed node tối đa 20 associations                         │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘

Cách State Manager hoạt động

┌─────────────────────────────────────────────────────────────────────────────┐
│                    Workflow — 4 bước                                        │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│  BƯỚC 1: Xác định Desired State                                             │
│  ────────────────────────────────                                           │
│  "Tôi muốn tất cả EC2 phải cài CloudWatch Agent"                            │
│                                                                             │
│                    ▼                                                        │
│                                                                             │
│  BƯỚC 2: Chọn SSM Document                                                  │
│  ────────────────────────────                                               │
│  → Dùng document có sẵn: AWS-ConfigureAWSPackage                            │
│  → Hoặc tạo custom document                                                 │
│                                                                             │
│                    ▼                                                        │
│                                                                             │
│  BƯỚC 3: Tạo Association                                                    │
│  ──────────────────────────                                                 │
│  → Chọn targets (tags, instance IDs, resource groups, all)                  │
│  → Đặt schedule: rate(1 day)                                                │
│  → Cấu hình parameters                                                      │
│                                                                             │
│                    ▼                                                        │
│                                                                             │
│  BƯỚC 4: State Manager tự động enforce                                      │
│  ──────────────────────────────────────                                     │
│  → Chạy ngay khi tạo association (mặc định)                                 │
│  → Chạy lại theo schedule                                                   │
│  → Chạy khi có thay đổi (config, target, document)                          │
│  → Nodes mới match target → tự động apply                                   │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘

Khi nào Association tự động chạy lại?

TriggerMô tả
Tạo mớiChạy ngay lập tức (mặc định)
Theo scheduleTheo cron/rate đã định
Edit associationKhi thay đổi document version, parameters, schedule, output location
Edit documentKhi document $DEFAULT/$LATEST version thay đổi
Node online lần đầuNode mới match target → apply ngay
Node reconnectNode offline rồi online lại (miss scheduled run)
Node trở lại sau 30+ ngàyNode stopped > 30 ngày rồi start lại
ManualUser chạy thủ công từ console/CLI

[!NOTE] Có thể tắt auto-run khi target thay đổi bằng option Apply association only at the next specified Cron interval (ApplyOnlyAtCronInterval=true). Hữu ích khi dùng Automation runbooks để tránh phát sinh chi phí khi launch nhiều instances.


SSM Documents dùng với State Manager

State Manager hỗ trợ 3 loại documents:

Document TypeMô tảVí dụ
CommandChạy commands trên nodesAWS-RunShellScript, AWS-RunPowerShellScript
PolicyApply cấu hình liên tụcAWS-GatherSoftwareInventory
AutomationChạy runbooks phức tạpAWS-RestartEC2Instance, AWS-CreateSnapshot

Documents phổ biến cho State Manager

DocumentMục đích
AWS-ConfigureAWSPackageCài/gỡ/update AWS packages (CloudWatch Agent, v.v.)
AWS-RunShellScriptChạy shell script trên Linux
AWS-RunPowerShellScriptChạy PowerShell trên Windows
AWS-UpdateSSMAgentTự động update SSM Agent
AWS-ApplyDSCMofsApply PowerShell DSC configurations
AWS-JoinDirectoryServiceDomainJoin Windows vào Active Directory domain
AWS-GatherSoftwareInventoryThu thập inventory data
AWS-ApplyAnsiblePlaybooksChạy Ansible playbooks
AWS-ApplyChefRecipesChạy Chef recipes

Targeting — Chọn nodes mục tiêu

┌─────────────────────────────────────────────────────────────────────────────┐
│                       4 cách Target                                         │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│  1. SPECIFY TAGS (Recommended ⭐)                                           │
│  ──────────────────────────────────                                         │
│  --targets Key=tag:Environment,Values=Production                            │
│                                                                             │
│  ✅ Nodes mới có tag match → tự động nhận association                       │
│  ✅ Xóa tag → ngừng chạy association                                        │
│  ✅ Best practice cho Auto Scaling Groups                                   │
│                                                                             │
│  2. CHOOSE INSTANCES MANUALLY                                               │
│  ──────────────────────────────                                             │
│  --targets Key=InstanceIds,Values=i-0123abc,i-0456def                       │
│                                                                             │
│  3. RESOURCE GROUPS                                                         │
│  ────────────────────                                                       │
│  --targets Key=resource-groups:Name,Values=MyWebServers                     │
│                                                                             │
│  ⚠️ Resource group tối đa 5 tag keys                                        │
│                                                                             │
│  4. ALL MANAGED NODES                                                       │
│  ──────────────────────                                                     │
│  Target tất cả nodes trong account + region hiện tại                        │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘

[!TIP] Luôn ưu tiên dùng Tags để target, đặc biệt khi dùng Command/Policy documents và Auto Scaling Groups. Nodes mới launch với đúng tags sẽ tự động nhận association.


Scheduling — Lên lịch chạy

Cron và Rate Expressions

LoạiVí dụÝ nghĩa
Raterate(1 day)Mỗi ngày 1 lần
Raterate(12 hours)Mỗi 12 giờ
Croncron(0 2 ? * SUN *)Chủ nhật lúc 2AM UTC
Croncron(30 23 ? * TUE#3 *)Thứ 3 tuần thứ 3 mỗi tháng, 23:30 UTC
Croncron(0 0 ? * 3L *)Thứ 3 cuối cùng mỗi tháng, 0:00 UTC

Schedule Offset

Cho phép delay thêm N ngày sau ngày scheduled. Ví dụ:

Schedule: cron(0 0 ? * THU#2 *)     → Thứ 5 tuần thứ 2
Offset:   3                          → + 3 ngày
Kết quả:  Chạy vào Chủ nhật sau Thứ 5 tuần thứ 2

→ Hữu ích khi muốn chạy sau Patch Tuesday

[!NOTE] State Manager không hỗ trợ chỉ định months trong cron expressions cho associations.


Rate Controls — Kiểm soát tốc độ

┌─────────────────────────────────────────────────────────────────────────────┐
│                        Rate Controls                                        │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│  CONCURRENCY — Bao nhiêu nodes chạy đồng thời?                              │
│  ──────────────────────────────────────────────                             │
│  • Absolute: "Tối đa 20 nodes cùng lúc"                                     │
│  • Percentage: "Tối đa 10% fleet cùng lúc"                                  │
│  • Mặc định (nếu không set): 50 nodes                                       │
│                                                                             │
│  ⚠️ Nodes mới match target khi đang chạy:                                   │
│     → Nếu chưa vượt concurrency → chạy luôn                                 │
│     → Nếu đã vượt → chờ interval tiếp theo                                  │
│                                                                             │
│  ERROR THRESHOLD — Bao nhiêu lỗi thì dừng?                                  │
│  ────────────────────────────────────────────                               │
│  • Absolute: "Dừng sau 10 lỗi"                                              │
│  • Percentage: "Dừng sau 10% nodes lỗi"                                     │
│  • Mặc định (nếu không set): 100% (không giới hạn)                          │
│                                                                             │
│  💡 Muốn đảm bảo không vượt error threshold:                                │
│     → Set Concurrency = 1 (chạy từng node một)                              │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘

State Manager + Automation Runbooks

State Manager không chỉ chạy commands trên nodes, mà còn schedule Automation runbooks để quản lý AWS resources rộng hơn:

Hành độngVí dụ Runbook
Attach IAM role cho EC2Custom runbook
Enforce Security Group rulesCustom runbook
Tạo/xóa DynamoDB backupsAWS-CreateDynamoDBBackup
Tạo/xóa EBS snapshotsAWS-CreateSnapshot
Tắt S3 public accessCustom runbook
Start/Stop EC2 theo giờAWS-StartEC2Instance, AWS-StopEC2Instance
Patch AMIsAWS-UpdateLinuxAmi
┌─────────────────────────────────────────────────────────────────────────────┐
│          State Manager + Automation = Quản lý resources rộng                │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│  Command/Policy Documents          Automation Runbooks                      │
│  ────────────────────────          ─────────────────────                    │
│  Target: Managed Nodes             Target: ANY AWS Resources                │
│  Scope: Chạy scripts/configs       Scope: Multi-step workflows              │
│                                                                             │
│  Ví dụ:                            Ví dụ:                                   │
│  • Cài software                    • Enforce SG rules                       │
│  • Update agent                    • Tạo EBS snapshot                       │
│  • Join AD domain                  • Stop EC2 ngoài giờ                     │
│  • Chạy shell script               • Tạo DynamoDB backup                    │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘

[!WARNING] Khi dùng Automation runbooks target "all instances" và launch nhiều instances thường xuyên, runbook sẽ chạy trên mỗi instance mới → có thể phát sinh chi phí Automation cao. Dùng ApplyOnlyAtCronInterval=true để tránh.

Giới hạn: Tối đa 100 concurrent automations running trong 1 AWS account.


Compliance Reporting

State Manager tích hợp với SSM Compliance để báo cáo trạng thái tuân thủ:

StatusÝ nghĩa
CompliantAssociation chạy thành công, node ở desired state
Non-CompliantAssociation fail hoặc node không ở desired state
  • Có thể gán Compliance Severity (Critical, High, Medium, Low, Unspecified)
  • Kết hợp với Change Calendar để kiểm soát khi nào association được phép chạy
  • Output có thể lưu vào S3 bucket để audit

Use Cases phổ biến

1. Bootstrap instances khi launch

Association: Cài CloudWatch Agent cho mọi EC2 mới
─────────────────────────────────────────────────
Document:    AWS-ConfigureAWSPackage
Parameters:  action=Install, name=AmazonCloudWatchAgent
Targets:     Tag: Role=WebServer
Schedule:    rate(1 day)

→ Instance mới launch với tag Role=WebServer
→ State Manager tự động cài CloudWatch Agent
→ Mỗi ngày kiểm tra lại → cài lại nếu bị gỡ

2. Tự động update SSM Agent

Association: Giữ SSM Agent luôn mới nhất
──────────────────────────────────────
Document:    AWS-UpdateSSMAgent
Targets:     All managed instances
Schedule:    rate(14 days)

3. Join Windows vào Active Directory

Association: Tự động join AD domain
────────────────────────────────
Document:    AWS-JoinDirectoryServiceDomain
Parameters:  directoryId, directoryName, dnsIpAddresses
Targets:     Tag: OS=Windows, JoinAD=true
Schedule:    rate(1 day)

4. Enforce security configs

Association: Đảm bảo SSH config đúng chuẩn
────────────────────────────────────────
Document:    AWS-RunShellScript (custom)
Commands:    
  - Disable root login
  - Set SSH timeout
  - Restrict key-based auth only
Targets:     Tag: Compliance=PCI
Schedule:    rate(6 hours)

5. Stop/Start EC2 ngoài giờ (tiết kiệm chi phí)

Association 1: Stop instances lúc 8PM
──────────────────────────────────────
Document:    AWS-StopEC2Instance (Automation)
Targets:     Tag: AutoStop=true
Schedule:    cron(0 20 ? * MON-FRI *)

Association 2: Start instances lúc 7AM
──────────────────────────────────────
Document:    AWS-StartEC2Instance (Automation)
Targets:     Tag: AutoStop=true  
Schedule:    cron(0 7 ? * MON-FRI *)

→ Tiết kiệm ~60% chi phí EC2 cho dev/test environments

So sánh State Manager vs các công cụ khác

State Manager vs Maintenance Windows

Tiêu chíState ManagerMaintenance Windows
Mục đíchDuy trì desired state liên tụcChạy tasks trong khung giờ cho phép
FocusCompliance & configurationTime-sensitive operations
SchedulingCron/rate, chạy khi target thay đổiChỉ trong maintenance window
Auto-apply cho nodes mới✅ Có❌ Không
Use case"EC2 phải luôn cài antivirus""Patch OS vào Chủ nhật 2AM"

State Manager vs các công cụ ngoài AWS

Tiêu chíState ManagerAnsiblePuppet/Chef
Chi phíFREEFree (community) / PaidPaid
AgentSSM Agent (có sẵn)Agentless (SSH)Agent required
SetupMinimalCần setupCần master server
AWS integrationNativeQua modulesQua modules
ScopeAWS resourcesAny serverAny server
Learning curveThấpTrung bìnhCao

State Manager vs AWS Config

Tiêu chíState ManagerAWS Config
Vai tròEnforce desired stateDetect configuration changes
Hành độngApply configs, fix driftRecord & evaluate compliance
RemediationTrực tiếp qua associationsGián tiếp qua SSM Automation

[!TIP] Kết hợp cả hai: AWS Config phát hiện drift → trigger SSM Automation → State Manager enforce lại desired state.


Pricing

ComponentChi phí
State ManagerFREE
AssociationsFREE
Association executionsFREE
SSM AgentFREE

[!NOTE] State Manager hoàn toàn miễn phí. Tuy nhiên, nếu dùng Automation runbooks qua State Manager, phí Automation vẫn áp dụng (free 100,000 steps/tháng, sau đó tính phí).


Best Practices

  1. Dùng Tags để target — Tự động apply cho nodes mới, dễ quản lý
  2. Set Rate Controls — Tránh impact toàn bộ fleet cùng lúc
  3. Dùng ApplyOnlyAtCronInterval cho Automation runbooks — Tránh chi phí bất ngờ
  4. Kết hợp Change Calendar — Ngăn association chạy trong freeze periods
  5. Lưu output vào S3 — Giữ audit trail cho compliance
  6. Tách associations theo environment — Dev/Staging/Prod dùng tags khác nhau
  7. Monitor Compliance dashboard — Phát hiện non-compliant nodes sớm
  8. Custom IAM role cho AssociationDispatchAssumeRole — Kiểm soát permissions chặt chẽ

Tóm tắt

┌─────────────────────────────────────────────────────────────────────────────┐
│                   State Manager — Key Takeaways                             │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│  🎯 WHAT:   Tool trong SSM để duy trì desired state trên nodes/resources    │
│  💰 COST:   FREE (Automation steps có thể tính phí riêng)                   │
│  🔑 CORE:   Association = Document + Targets + Schedule + Rate Controls     │
│                                                                             │
│  ┌─────────────────────────────────────────────────────────────────────┐    │
│  │                  Khi nào dùng State Manager?                        │    │
│  │                                                                     │    │
│  │  ✅ Bootstrap instances khi launch (cài software, join domain)      │    │
│  │  ✅ Enforce security configs liên tục (SSH, firewall, antivirus)    │    │
│  │  ✅ Tự động update agents (SSM Agent, CloudWatch Agent)             │    │
│  │  ✅ Chống configuration drift ở quy mô lớn                          │    │
│  │  ✅ Schedule Automation runbooks (stop/start EC2, snapshots)        │    │
│  └─────────────────────────────────────────────────────────────────────┘    │
│                                                                             │
│  ┌─────────────────────────────────────────────────────────────────────┐    │
│  │                  Nhớ nhanh cho exam                                 │    │
│  │                                                                     │    │
│  │  • "Desired state" / "Configuration drift" → State Manager          │    │
│  │  • "Bootstrap EC2 at launch" → State Manager + Tags                 │    │
│  │  • "Ensure software always installed" → State Manager               │    │
│  │  • "Schedule automation" → State Manager + Automation Runbook       │    │
│  │  • "FREE configuration management" → State Manager                  │    │
│  └─────────────────────────────────────────────────────────────────────┘    │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘

Tài liệu tham khảo