AWS CloudFormation

Infrastructure as code for AWS: declare the resources in a template, CloudFormation makes reality match — and unmakes it on delete. Stacks are portable across accounts and regions, and it's the backbone of Beanstalk, SAM and Service Catalog.

Infrastructure as code cho AWS: khai báo tài nguyên trong template, CloudFormation làm thực tế khớp theo — và tháo ra khi delete. Stack portable across account & region, và là xương sống của Beanstalk, SAM, Service Catalog.

Reach for it / not the right toolKhi nào dùng / khi nào không

Reach for CloudFormationChọn CloudFormation

  • Provision a whole stack repeatably and tear it down cleanly — dev/test environments on demand.Provision cả stack có thể lặp lại và tháo sạch — env dev/test theo yêu cầu.
  • Same stack across multiple accounts & regions → StackSets.Cùng stack across nhiều account & region → StackSets.
  • Detect whether someone changed infra by hand → Drift detection.Phát hiện ai đó sửa hạ tầng bằng tay → Drift detection.

Not the right toolKhông phải chỗ dùng

  • Just deploying app code to running compute → CodeDeploy; a managed web env → Beanstalk.Chỉ deploy code app lên compute đang chạy → CodeDeploy; env web managed → Beanstalk.
  • A curated self-service catalog for non-experts → Service Catalog (itself built on CFN).Một self-service catalog có tuyển chọn cho người không chuyên → Service Catalog (bản thân nó dựng trên CFN).
  • Protecting against manual changes automatically — CFN detects drift but doesn't prevent it.Ngăn thay đổi thủ công tự động — CFN phát hiện drift nhưng không chặn.

If you think in Terraform — a Rosetta tableNếu bạn quen Terraform — bảng đối chiếu

Same job — declare desired state, let the tool reconcile — different words. The big split: CloudFormation keeps state server-side for you; Terraform keeps an explicit state file (remote backend or HCP Terraform). Cùng một việc — khai báo trạng thái mong muốn, để tool reconcile — khác từ ngữ. Khác biệt lớn: CloudFormation giữ state phía server giúp bạn; Terraform giữ file state tường minh (remote backend hoặc HCP Terraform).

CloudFormation Terraform / HCP
Template (YAML / JSON)Template (YAML / JSON) Configuration in HCL (.tf)
Stack Root module + a state file · a workspace in HCP TerraformRoot module + state file · một workspace trong HCP Terraform
Change Set (preview)Change Set (xem trước) terraform plan
Create / update stack · delete stackTạo / update stack · xoá stack terraform apply · terraform destroy
Nested stacks Modules
Parameters · Outputs variable · output
!Ref · !GetAtt Resource references / attribute interpolationTham chiếu resource / nội suy attribute
Mappings · Conditions locals · count / for_each
DeletionPolicy: RetainDeletionPolicy: Retain lifecycle { prevent_destroy = true } · removed block
DeletionPolicy: SnapshotDeletionPolicy: Snapshot skip_final_snapshot = false + final_snapshot_identifier
Custom Resource (Lambda)Custom Resource (Lambda) null_resource + provisioner · external data source · a real providernull_resource + provisioner · data source external · provider riêng
StackSets Many workspaces + aliased providers · VCS-driven runs in HCP TerraformNhiều workspace + provider alias · run theo VCS trong HCP Terraform
Drift detectionDrift detection terraform plan (refresh) shows drift · HCP drift detectionterraform plan (refresh) hiện drift · HCP drift detection
Resource importResource import terraform import · import { } block
Dynamic ref {{resolve:secretsmanager}}Dynamic ref {{resolve:secretsmanager}} data "aws_secretsmanager_secret_version"
Service Catalog HCP Terraform no-code modules + private registry · Sentinel policiesHCP Terraform no-code module + private registry · policy Sentinel
The one that bitesCái dễ dính State ownership. CFN's state lives in the service — delete the stack and it knows what to remove. Terraform's truth is the state file; lose or corrupt it and Terraform no longer knows what it owns. That's why remote state (S3 + lock) or HCP Terraform matters, and why terraform import / state rm have no direct CFN equivalent. Sở hữu state. State của CFN nằm trong service — xoá stack là nó biết gỡ gì. Sự thật của Terraform là state file; mất hoặc hỏng nó thì Terraform không còn biết mình quản gì. Vì vậy remote state (S3 + lock) hoặc HCP Terraform mới quan trọng, và vì sao terraform import / state rm không có bản CFN tương đương trực tiếp.

Retaining data on delete — DeletionPolicyGiữ data khi delete — DeletionPolicy

Put a DeletionPolicy on a resource to control what happens when the stack (or that resource) is deleted. This is the classic "we deleted the stack and lost the database" exam trap. Gắn DeletionPolicy lên resource để kiểm soát điều gì xảy ra khi stack (hoặc resource đó) bị xoá. Đây là bẫy kinh điển "xoá stack là mất luôn database".

Delete (default) resource is removed · S3 bucket must be emptied firstresource bị xoá · S3 bucket phải rỗng trước
Retain keep / preserve the resource · works for any resource or nested stackgiữ lại resource · dùng được cho mọi resource hoặc nested stack
Snapshot take a final snapshot, then delete · only snapshottable resourceschụp snapshot cuối rồi xoá · chỉ resource hỗ trợ snapshot
What Snapshot supportsSnapshot áp dụng cho EBS Volume · ElastiCache Cluster & ReplicationGroup · RDS DBInstance & DBCluster · Redshift Cluster. Gotcha: for AWS::RDS::DBCluster the default policy is already Snapshot (not Delete). And you can't delete an S3 bucket until it's empty. EBS Volume · ElastiCache Cluster & ReplicationGroup · RDS DBInstance & DBCluster · Redshift Cluster. Lưu ý: với AWS::RDS::DBCluster mặc định đã là Snapshot (không phải Delete). Và không xoá được S3 bucket khi chưa rỗng.

Custom Resources (Lambda)Custom Resource (Lambda)

The escape hatch: when CFN can't do something natively, a Custom Resource calls a Lambda on create/update/delete — and the Lambda does whatever you want via API calls. Cửa thoát: khi CFN không làm được sẵn, Custom Resource gọi Lambda lúc create/update/delete — và Lambda làm gì tuỳ bạn qua API call.

A CloudFormation Custom Resource invokes a Lambda function on create, update and delete; the Lambda in turn makes API calls to whatever you want CloudFormation Custom Resource AWS Lambda Function Whatever you want create, update, delete API calls

Use cases: a resource CFN doesn't support yet (new service), an on-premises resource, emptying an S3 bucket before it's deleted, fetching an AMI id — anything you want.

Use case: resource CFN chưa hỗ trợ (service mới), resource on-prem, dọn S3 bucket trước khi xoá, lấy AMI id — bất cứ gì bạn muốn.

StackSetsStackSets

Create / update / delete stacks across multiple accounts and regions in a single operation. Update the StackSet and all associated stack instances update everywhere. Tạo / update / delete stack across nhiều account & region trong một thao tác. Update StackSet thì tất cả stack instance liên quan update ở mọi nơi.

A CloudFormation StackSet in an administrator account fans a stack out to three targets — Account A us-east-1, Account A ap-south-1, and Account B eu-west-2 StackSet Admin Account Account A us-east-1 Account A ap-south-1 Account B eu-west-2

An admin account owns the StackSet; trusted accounts create/update/delete stack instances from it. Turn on Automatic Deployment to roll out to accounts joining an AWS Organization or specific OUs.

Admin account sở hữu StackSet; trusted account tạo/update/delete stack instance từ đó. Bật Automatic Deployment để tự triển khai tới account gia nhập AWS Organization hoặc OU cụ thể.

Drift detectionDrift detection

CFN creates infra but doesn't protect against manual changes. Drift detection compares the live resource to the template and flags what someone changed by hand — on the whole stack or individual resources. CFN tạo hạ tầng nhưng không chống thay đổi thủ công. Drift detection so tài nguyên thực tế với template và báo cái ai đó sửa tay — trên cả stack hoặc từng resource.

Drift detection compares a security group rule in the template (SSH from 10.0.0.115/32) against the live resource that someone changed via the console to 0.0.0.0/0, and reports the stack as drifted Template · SSHSecurityGroup SSH · TCP/22 10.0.0.115/32 Live · changed via console SSH · TCP/22 0.0.0.0/0 CloudFormation Drift ⚠ Drifted! compare

Someone widened an SSH rule from a single IP to 0.0.0.0/0 in the console. Drift detection compares live vs template and reports the resource — and stack — as drifted.

Ai đó nới rule SSH từ một IP thành 0.0.0.0/0 trong console. Drift detection so thực tế với template và báo resource — và stack — đã drift.

Integration with Secrets ManagerTích hợp Secrets Manager

Generate a secret in the template, reference it in the RDS instance with a dynamic reference, and link the two so rotation targets the right DB — no password ever written in plaintext. Tạo secret trong template, tham chiếu nó trong RDS instance bằng dynamic reference, và link hai bên để rotation trỏ đúng DB — không bao giờ ghi password dạng plaintext.

Resources:
  # secret is generated
  MyRDSInstanceRotationSecret:
    Type: AWS::SecretsManager::Secret
    Properties:
      GenerateSecretString:
        SecretStringTemplate: '{"username": "admin"}'
        GenerateStringKey: password
        PasswordLength: 16

  # reference the secret inside the RDS DB instance
  MyRDSDBInstance:
    Type: AWS::RDS::DBInstance
    Properties:
      Engine: mysql
      MasterUsername:     !Sub "{{resolve:secretsmanager:${MyRDSInstanceRotationSecret}::username}}"
      MasterUserPassword: !Sub "{{resolve:secretsmanager:${MyRDSInstanceRotationSecret}::password}}"

  # link the secret to the RDS DB instance (for rotation)
  SecretRDSAttachment:
    Type: AWS::SecretsManager::SecretTargetAttachment
    Properties:
      TargetType: AWS::RDS::DBInstance
      SecretId: !Ref MyRDSInstanceRotationSecret
      TargetId: !Ref MyRDSDBInstance
The three piecesBa mảnh ghép Secret auto-generates the password · the RDS instance pulls user/pass via {{resolve:secretsmanager:…}} dynamic references · SecretTargetAttachment links them so rotation knows which DB to update. Secret tự sinh password · RDS instance lấy user/pass qua dynamic reference {{resolve:secretsmanager:…}} · SecretTargetAttachment link chúng để rotation biết update DB nào.

Resource importResource import

  • Bring existing resources into an existing/new stack — no delete-and-recreate needed. Đưa resource có sẵn vào stack mới/hiện có — không cần delete rồi tạo lại.
  • You need a template describing the entire stack (existing + target resources) and a unique identifier per target (e.g. BucketName for S3). Cần template mô tả toàn bộ stack (resource cũ + target) và một identifier duy nhất cho mỗi target (vd BucketName cho S3).
  • Each imported resource must carry a DeletionPolicy attribute (any value) + an identifier. Mỗi resource import phải có thuộc tính DeletionPolicy (giá trị nào cũng được) + identifier.
  • Can't import the same resource into multiple stacks. Không import cùng một resource vào nhiều stack.

Built on CFN — Service CatalogDựng trên CFN — Service Catalog

Self-service portal for non-expertsPortal self-service cho người không chuyên Users new to AWS have too many options and may create non-compliant stacks. Service Catalog gives them a self-service portal to launch only admin-authorized products (VMs, databases, storage) — each product is a CloudFormation template curated by admins. Also backs Elastic Beanstalk and the SAM framework. Người mới với AWS có quá nhiều lựa chọn và có thể tạo stack không tuân thủ. Service Catalog cho họ một portal self-service chỉ để launch sản phẩm admin đã duyệt (VM, database, storage) — mỗi product là một template CloudFormation do admin tuyển chọn. CFN cũng là nền của Elastic Beanstalk và framework SAM.