CloudFormation
AWS CloudFormation
🎯 Sebab Apa Wujud
CloudFormation wujud sebab buat infra manual (klik console satu-satu) = lambat, tak konsisten antara env (dev/prod), dan susah nak replicate atau rollback. CloudFormation = Infrastructure as Code: tulis template (YAML/JSON) sekali, deploy infra yang sama berulang kali, dan kalau gagal auto-rollback. Buang human error + 'works on dev tapi tak sama kat prod'. Ia FREE — bayar resource je.
Apa Dia
Mengurus dan menyediakan infrastruktur AWS secara automatik menggunakan template (IaC)
Contoh Guna
Deploy EC2 + S3 + RDS sekaligus dari satu template YAML/JSON, replicate environment dev/staging/prod
CloudFormation = manual IKEA untuk infra (analogi)
Macam manual IKEA: template sama → perabot sama setiap kali, takda silap manusia. INGAT exam: preview = Change Set; kesan ubah manual = Drift Detection; deploy multi-account/region = StackSets; kekalkan data masa delete = DeletionPolicy: Retain.
Pilih konsep operasi CFN — decision tree (yang mana aku guna?)
Tiga "protect" yang selalu keliru: Stack Policy = lindung masa UPDATE · DeletionPolicy: Retain = kekalkan resource bila stack DELETE · Termination Protection = halang stack itu sendiri dari delete. INGAT exam: "multiple accounts/regions" → StackSets; "reusable/modular" → Nested Stacks; "preview" → Change Set; "manual change/drift" → Drift Detection.
CloudFormation vs Terraform vs Elastic Beanstalk
| Aspect | CloudFormation | Terraform | Elastic Beanstalk |
|---|---|---|---|
| Jenis | AWS-native IaC | Multi-cloud IaC (HashiCorp) | PaaS — deploy app, infra auto |
| Skop | AWS resources sahaja | AWS + GCP + Azure + dll | App platform (EC2/ASG/ELB auto) |
| Bahasa | YAML / JSON template | HCL | Tak tulis infra — push code je |
| State | Managed by AWS | tfstate file (kau urus sendiri) | Managed by AWS |
| Keyword | "AWS-only IaC, no extra cost" | "multi-cloud / satu tool semua" | "deploy web app cepat, jangan urus infra" |
Ingat: AWS-only IaC + percuma → CloudFormation. Multi-cloud satu tool → Terraform. Deploy app tanpa fikir infra → Elastic Beanstalk (dia sebenarnya guna CloudFormation di bawah hood).
Template SECTIONS — 7 bahagian (apa kau TULIS dalam fail YAML/JSON)
| Section | Apa dia | Wajib? | Exam keyword |
|---|---|---|---|
| Resources | Define resource nak dicipta (EC2/S3/VPC/RDS...) | 🔴 WAJIB — satu-satunya | "the only required section" |
| Parameters | Input DINAMIK masa launch (user pilih env/saiz) | Optional | "user chooses env / instance size" |
| Mappings | Lookup table STATIC (region → AMI ID) | Optional | "region-specific AMI / static lookup" |
| Conditions | Cipta resource bersyarat (if prod → buat X) | Optional | "create only if / conditional logic" |
| Outputs | EXPORT value keluar untuk stack lain import | Optional | "share between stacks → Fn::ImportValue" |
| Metadata | Info tambahan + config untuk cfn-init | Optional | jarang keluar — kenal nama je |
| Transform | Guna SAM (serverless) atau macros | Optional | "serverless + CloudFormation → SAM/Transform" |
Ingat: Resources = SATU-SATUNYA section WAJIB; yang lain optional. Mnemonic 4 exam-favourite: Output keLUAR (kongsi), Parameter masUK (input), Mapping ikut REGION, Condition ikut SYARAT. Transform = SAM (serverless app). INGAT exam: "only required section" → Resources; "region-specific AMI" → Mappings; "share between stacks" → Outputs.
Operasi STACK — konsep CARA CloudFormation urus (bukan section template)
| Konsep | Apa dia | Exam keyword |
|---|---|---|
| Stack | Kumpulan resource dari 1 template, urus sekali. Delete stack = semua resource padam (kemas) | "group of resources / manage together" |
| StackSets | Deploy 1 template ke BANYAK account + region sekali gus (guna Organizations) | "across multiple accounts/regions" |
| Nested Stacks | Stack dalam stack — pecah jadi modul reusable (VPC/security layer) | "reusable / modular templates" |
| Change Set | PREVIEW perubahan SEBELUM apply pada stack | "preview changes before applying" |
| Drift Detection | Kesan resource diubah MANUAL di luar CFN (console) | "detect manual / console changes, config drift" |
| DeletionPolicy | Apa jadi pada resource bila stack delete. Retain = resource KEKAL | "preserve data when stack deleted → Retain" |
| Stack Policy | Lindungi resource penting dari terubah/terpadam masa UPDATE | "protect resource during stack update" |
Ingat: Section = apa kau TULIS dalam template; Operasi = macam mana CFN URUS stack. INGAT exam: multi-account/region → StackSets; modular/reusable → Nested Stacks; preview → Change Set; manual change → Drift Detection; keep data on delete → DeletionPolicy: Retain; protect during update → Stack Policy.
Helper scripts — 4 keping (topik SEMPADAN: kenal cfn-init je dah cukup)
| Script | Kerja | Exam keyword |
|---|---|---|
| cfn-init | Baca metadata + INSTALL packages/files/services masa EC2 launch | "read metadata + install software on launch" (paling kerap) |
| cfn-signal | Hantar isyarat SUCCESS/FAIL balik ke CFN | "signal stack when setup complete" (pair CreationPolicy/WaitCondition) |
| cfn-hup | Daemon pantau perubahan metadata → re-run cfn-init bila stack update | "re-run on metadata change" |
| cfn-get-metadata | Ambil metadata SAHAJA — tak install apa-apa | "just fetch metadata" |
Ingat: init = mula/SETUP (install) · signal = bagi tahu SIAP · hup = PANTAU perubahan · get-metadata = AMBIL info je. INGAT exam: "read metadata and install packages when instance launches" → cfn-init. Ni topik sempadan SAA-C03 (jarang keluar) — cukup hafal cfn-init = install/setup + cfn-signal = bagi tahu siap, tak payah stress 4-4.
⚡ Quick Sifir — hafal ni
- ▪CloudFormation FREE — bayar hanya resource yang dibuat (EC2/RDS/S3), stacks & StackSets percuma
- ▪INGAT 4 komponen: Output keLUAR (kongsi antara stack), Parameter masUK (input launch), Mapping ikut REGION (lookup static), Condition ikut SYARAT (if/else)
- ▪Cross-stack: Stack A guna Outputs + Export → Stack B guna Fn::ImportValue untuk import. Exported value TAK boleh delete/ubah selagi stack lain masih import dia
- ▪Change Set = PREVIEW perubahan sebelum apply; Drift Detection = detect perubahan manual luar CFN
- ▪Mappings = static lookup (region→AMI); Outputs+Fn::ImportValue = cross-stack ref; Parameters = user input
- ▪cfn-init = install packages dari metadata; cfn-signal = hantar SUCCESS/FAIL; cfn-hup = re-run bila metadata berubah
- ▪DeletionPolicy: Retain = resource KEKAL walau stack dipadam (untuk RDS/S3)
- ▪Nested Stacks = reusable component (VPC/security layer); StackSets = deploy multi-account/region
- ▪Stack update gagal → auto-ROLLBACK ke state lama (default)
🪤 Perangkap Soalan
Q: Satu CloudFormation template untuk banyak region, auto-pilih AMI ID betul ikut region. Guna apa?
⚠ Umpan: Parameters — sangka user kena input AMI ID setiap region.
✓ Betul: Mappings (static region→AMI lookup) atau Lambda-backed custom resource (dynamic lookup SSM). Bukan Parameters (manual). Keyword: 'region-specific AMI' → Mappings/custom resource.
Q: Nak detect kalau ada orang ubah resource stack secara MANUAL via console. Feature?
⚠ Umpan: Change Set — sangka ia tunjuk perubahan yang dah berlaku.
✓ Betul: Drift Detection. Change Set = preview perubahan SEBELUM apply; Drift = detect perubahan manual yang dah terjadi di luar CFN. Keyword: 'manual console changes' → Drift Detection.
Q: Padam stack tapi nak data RDS/S3 KEKAL (jangan lenyap). Macam mana?
⚠ Umpan: Backup manual dulu sebelum delete stack — leceh + boleh terlupa.
✓ Betul: Set DeletionPolicy: Retain pada resource tu. Stack dipadam, resource kekal. Keyword: 'retain data on stack deletion' → DeletionPolicy: Retain.
Q: Stack urus RDS dengan data production kritikal. Kalau stack TER-delete, nak pastikan database TAK musnah & data kekal. Set apa?
⚠ Umpan: Termination Protection — bunyi macam betul sebab ia 'protect dari delete'. Tapi ia halang STACK dari dipadam langsung; ia TAK kawal nasib resource kalau stack memang jadi dipadam.
✓ Betul: DeletionPolicy: Retain pada RDS resource — kalau stack dipadam, database tetap kekal. Keyword 'if stack deleted, preserve the resource/data' → DeletionPolicy: Retain. (Termination Protection = halang stack delete; DeletionPolicy = nasib resource bila stack memang delete.)
Q: Masa stack UPDATE, nak lindungi database production kritikal daripada terganti/terpadam oleh operasi update tu sendiri. Feature?
⚠ Umpan: DeletionPolicy: Retain — nampak betul sebab 'protect resource'. Tapi DeletionPolicy cuma terpakai bila STACK dipadam, bukan masa update.
✓ Betul: Stack Policy — JSON policy yang lindungi resource tertentu daripada diubah/diganti masa stack UPDATE. Keyword 'protect resource during stack update' → Stack Policy. (Stack Policy = masa UPDATE; DeletionPolicy = masa DELETE.)
Q: EC2 perlu READ METADATA dari CloudFormation template + INSTALL software packages bila instance launch. Helper script mana?
⚠ Umpan: cfn-hup atau cfn-signal — bunyi macam uruskan setup masa launch. SALAH: cfn-hup pantau perubahan metadata (re-run je), cfn-signal cuma bagi tahu CFN dah siap.
✓ Betul: cfn-init — baca AWS::CloudFormation::Init metadata + install packages/files/services masa launch. Logik nama: init = initialize/SETUP. Keyword 'read metadata + install packages on launch' → cfn-init.
🧠 Cara Mudah Ingat
- →Lambda-backed Custom Resources: guna Lambda untuk perform logic masa CloudFormation create/update/delete — contoh: lookup AMI ID dynamically
- →AMI IDs berbeza tiap region + instance type → Lambda custom resource query SSM Parameter Store atau EC2 API untuk get correct AMI ID masa stack creation
- →Tanpa custom resource: kena maintain separate template per region (manual overhead). Dengan custom resource: satu template, Lambda inject AMI ID automatik
- →Custom resource flow: CFN trigger Lambda → Lambda query API → return value → CFN inject ke template
- →Bukan SNS/SQS untuk AMI lookup — SNS = notifications, SQS = queuing, bukan dynamic lookup
- →Exam: "single CloudFormation template for multiple regions, auto-select correct AMI ID" → Lambda-backed custom resource
- →Mappings: static key-value lookup tables dalam template (e.g. region → AMI ID). Tak perlu user input, hardcoded dalam template
- →Outputs: export values dari stack untuk cross-stack reference. Consuming stack guna Fn::ImportValue untuk import
- →Parameters: user input masa stack launch (dynamic). Conditions: conditional resource creation berdasarkan parameter values
- →EXAM KEY: "region-specific AMI selection" → Mappings. "Share values between stacks" → Outputs + ImportValue. "User chooses env" → Parameters
- →cfn-init: reads AWS::CloudFormation::Init metadata + install packages/files/services — PRIMARY bootstrap script
- →cfn-signal: hantar SUCCESS/FAILURE signal ke CloudFormation (untuk WaitCondition/CreationPolicy)
- →cfn-hup: daemon yang detect metadata changes dan re-run cfn-init bila stack update
- →cfn-get-metadata: retrieve metadata SAHAJA — tidak install apa-apa
- →Exam: "read metadata and install packages on EC2 launch" → cfn-init
- →Change set: PREVIEW perubahan (resources akan create/update/delete) SEBELUM execute — tak terus apply. Best practice: always review change set before updating production stack
- →Drift detection: detect bila resource dalam stack diubah MANUALLY (outside CloudFormation, e.g. via console) — stack jadi "DRIFTED" dari template. Tak auto-fix, just detect & report
- →Stack update failure → automatic ROLLBACK ke previous working state (default behaviour)
- →Stack deletion: resources dengan DeletionPolicy: Retain akan KEKAL walaupun stack dipadam — guna untuk data store (RDS, S3) yang tak nak accidentally lenyap
- →Exam: "preview changes before applying" → Change Sets. "Detect manual console changes to stack resources" → Drift Detection
- →Nested Stacks: stack yang dipanggil dari dalam stack lain (parent stack) menggunakan AWS::CloudFormation::Stack resource type. Guna bila template dah terlalu besar atau ada reusable components (e.g. network layer, security layer yang dipakai oleh banyak stacks).
- →Nested Stacks benefit: modularization — separate VPC stack, app stack, DB stack. Parent orchestrate semua. Setiap nested stack diupdate/rolledback independently.
- →Exam: "reuse common infrastructure components (VPC, subnets) across multiple CloudFormation stacks" → Nested Stacks. "Share VPC ID between stacks" → Outputs + ImportValue (cross-stack ref).
- →PRICING: CloudFormation is FREE — kau bayar hanya untuk AWS resources yang ia create (EC2, RDS, S3, dll). Tiada charge untuk stacks, templates, changes, drift detection, StackSets. Designer & change sets juga free.
- →StackSets: deploy ke multiple accounts/regions sekali gus. Perlukan AWS Organizations atau self-managed permissions. Boleh auto-reconcile drift.
- →Exam: "no additional charge for using CloudFormation" → hanya bayar resources yang dibuat. Nested stacks & StackSets percuma.
- →AWS Solutions (e.g. Instance Scheduler on AWS) = pre-built CloudFormation templates — deploy stack, bukan native service. Instance Scheduler auto start/stop EC2+RDS on schedule.
- →Resources = SATU-SATUNYA section yang WAJIB dalam template. Template tanpa Resources tak sah. Exam: "the only required section in a CloudFormation template" → Resources.
- →Transform: section untuk guna SAM (Serverless Application Model — AWS::Serverless-2016-10-31) atau CloudFormation macros. Exam: "simplify serverless (Lambda/API Gateway/DynamoDB) definitions in CloudFormation" → Transform / SAM.
- →Stack Policy: JSON policy yang lindungi resource kritikal (e.g. database) daripada terubah/terpadam masa stack UPDATE — beza dengan DeletionPolicy (yang protect masa stack DELETE). Exam: "prevent accidental updates to specific resources during a stack update" → Stack Policy.
- →Termination Protection: setting di STACK level yang halang stack itu sendiri daripada dipadam (mesti disable dulu sebelum boleh delete). BEZA: Termination Protection = halang stack DELETE; DeletionPolicy: Retain = kalau stack memang dipadam, kekalkan resource tertentu. Exam: "prevent the stack from being deleted" → Termination Protection; "keep the database if the stack is deleted" → DeletionPolicy: Retain.
- →INGAT 3-cara keliru: Termination Protection (halang stack delete) · DeletionPolicy (nasib resource bila stack DELETE) · Stack Policy (lindung resource masa stack UPDATE).
Guna Bila
Automate infrastructure deployment, consistent environment