
Cargando...
Define, deploy, and manage your entire AWS infrastructure through versioned, repeatable, auditable code templates
AWS CloudFormation is a fully managed Infrastructure as Code (IaC) service that lets you model, provision, and manage AWS and third-party resources using declarative JSON or YAML templates. It treats infrastructure as a single logical unit called a Stack, enabling repeatable deployments across environments and regions. CloudFormation handles dependency ordering, rollback on failure, and drift detection — making it the backbone of automated, governed, and auditable AWS infrastructure delivery.
Automate the provisioning and management of AWS infrastructure at scale using version-controlled, declarative templates that eliminate manual configuration drift and enable consistent multi-environment deployments.
Use When
Avoid When
Declarative JSON/YAML Templates
YAML is preferred for readability and supports comments; JSON is valid but verbose. Both are fully supported.
Nested Stacks
Use AWS::CloudFormation::Stack resource type to embed child stacks. Enables modular, reusable template components and bypasses the 500-resource and 1MB limits.
Cross-Stack References (Fn::ImportValue)
Export values from one stack's Outputs and import them in another stack using Fn::ImportValue. The exporting stack cannot be deleted while another stack imports its values.
StackSets (Multi-Account/Multi-Region)
Deploy a single template across multiple accounts and regions simultaneously. Supports SELF_MANAGED (manual trust) and SERVICE_MANAGED (AWS Organizations) deployment models.
Change Sets
Preview the impact of template changes before executing them. Shows resources that will be Added, Modified, or Removed. Critical for production change management.
Drift Detection
Detects differences between the expected stack configuration and actual deployed resources. Does NOT automatically remediate drift — you must take manual action or use Config Rules + SSM Automation.
Stack Policies
JSON policy documents that define which update actions are allowed on specific resources. Prevents accidental replacement or deletion of stateful resources like RDS.
Rollback Triggers (CloudWatch Alarms)
Monitor CloudWatch Alarms during stack operations. If an alarm fires within the monitoring window, CloudFormation rolls back the update.
Custom Resources (Lambda/SNS backed)
Extend CloudFormation to manage any resource — AWS or non-AWS — by invoking a Lambda function or SNS topic during stack Create/Update/Delete operations.
CloudFormation Registry (Resource Types)
Register and use private or public third-party resource types (e.g., MongoDB::Atlas::Cluster). Public extensions are available in the CloudFormation Public Registry.
CloudFormation Guard (cfn-guard)
Open-source policy-as-code tool that validates CloudFormation templates against compliance rules BEFORE deployment. Integrates with CI/CD pipelines.
CloudFormation Hooks
Invoke Lambda functions or Guard rules before or after resource provisioning operations. Enables proactive compliance validation.
SSM Parameter Store Integration in Templates
Reference SSM Parameter Store values directly in template Parameters using type AWS::SSM::Parameter::Value<String>. Values are resolved at deploy time.
Secrets Manager Integration
Use dynamic references ({{resolve:secretsmanager:...}}) to inject secret values at deploy time without hardcoding credentials in templates.
Dynamic References
Syntax: {{resolve:service-name:reference-key}}. Supported for SSM Parameter Store (plain text and SecureString) and Secrets Manager. Values are resolved at resource creation/update time.
Deletion Policies
DeletionPolicy attribute options: Delete (default), Retain, Snapshot (for supported resources like RDS, EBS, ElastiCache). Retain is critical for stateful resources.
Update Replace Policy
UpdateReplacePolicy controls what happens to the old resource when CloudFormation must replace it during an update. Options: Delete, Retain, Snapshot.
CreationPolicy and WaitConditions
CreationPolicy pauses stack completion until EC2 instances or Auto Scaling groups signal success via cfn-signal. WaitCondition is the older mechanism for the same purpose.
cfn-init and cfn-hup
cfn-init reads AWS::CloudFormation::Init metadata to configure EC2 instances. cfn-hup daemon polls for template changes and re-runs cfn-init on updates.
Service Catalog Integration
AWS Service Catalog uses CloudFormation templates as the underlying product definition. Enables self-service provisioning with governance guardrails.
AWS CDK (Cloud Development Kit)
CDK synthesizes CloudFormation templates from code written in TypeScript, Python, Java, C#, Go. CDK is an abstraction layer OVER CloudFormation — it still deploys via CloudFormation stacks.
Automatic Rollback on Failure
By default, CloudFormation rolls back all changes if any resource fails. Can be disabled with --disable-rollback flag for debugging. DO NOT disable in production.
Stack Notifications (SNS)
Configure an SNS topic on a stack to receive notifications for all stack events (CREATE_COMPLETE, ROLLBACK_IN_PROGRESS, etc.).
CloudTrail Integration
All CloudFormation API calls are logged in CloudTrail. Enables audit trails for who deployed what and when.
Resource Import
Import existing AWS resources into CloudFormation management without recreating them. The resource must support import (not all resource types do).
Retain on Stack Deletion (DeletionPolicy: Retain)
Resources with DeletionPolicy: Retain are kept after stack deletion. They become unmanaged — CloudFormation no longer tracks them.
CI/CD Infrastructure Pipeline
high freqCodePipeline orchestrates CloudFormation deployments: Source (CodeCommit/GitHub) → Build (CodeBuild validates/lints template) → Deploy (CloudFormation CreateChangeSet action) → Approve (manual gate) → Execute (CloudFormation ExecuteChangeSet action). This is the canonical AWS IaC CI/CD pattern. Change sets provide the human review gate before production changes.
Custom Resources for Extended Functionality
high freqWhen CloudFormation doesn't natively support a resource or action, a Lambda-backed Custom Resource fills the gap. Lambda receives a CloudFormation event (Create/Update/Delete), performs the action (e.g., seed a DynamoDB table, register an SSL cert, call a third-party API), and signals success/failure back to CloudFormation via a pre-signed S3 URL. Critical: Lambda MUST respond to the pre-signed URL or the stack will hang for up to 1 hour before timing out.
Self-Service Governed Provisioning
high freqService Catalog wraps CloudFormation templates as 'Products' organized in 'Portfolios'. End users (developers, data scientists) can self-provision approved architectures without needing CloudFormation permissions directly. IAM permissions are granted to the Service Catalog launch role, not the end user. This pattern enforces governance while enabling developer autonomy — a key exam scenario distinguishing Service Catalog governance from raw CloudFormation access.
StackSets with SERVICE_MANAGED Deployment
high freqCloudFormation StackSets in SERVICE_MANAGED mode integrates with AWS Organizations to automatically deploy stacks to all accounts in an OU (Organizational Unit). New accounts joining the OU automatically receive the stack. This eliminates manual trust relationship setup and is the prescribed pattern for enterprise-scale, multi-account baseline deployments (e.g., VPC, CloudTrail, Config rules across all accounts).
Drift Detection and Compliance Remediation
high freqAWS Config continuously monitors resource configurations and can detect when resources deviate from their CloudFormation-defined state (drift). Config Rules can trigger SSM Automation documents to remediate drift automatically. CloudFormation Hooks can also invoke Config proactive evaluations before resources are provisioned. Together, they form a detect-and-remediate compliance loop.
Dynamic Parameter Resolution
high freqCloudFormation templates reference SSM Parameter Store values using the AWS::SSM::Parameter::Value<Type> parameter type or {{resolve:ssm:parameter-name}} dynamic references. This decouples environment-specific values (AMI IDs, VPC IDs, endpoint URLs) from the template itself. SSM Parameter Store becomes the single source of truth for environment configuration, enabling the same template to deploy correctly across dev/staging/prod by pointing to different parameter paths.
Higher-Level IaC Abstraction
high freqAWS CDK (Cloud Development Kit) allows developers to define infrastructure in familiar programming languages (TypeScript, Python, Java, C#, Go). CDK synthesizes (cdk synth) CloudFormation templates and deploys them (cdk deploy) via CloudFormation stacks. CDK constructs provide opinionated, pre-configured patterns (L2/L3 constructs). The output is always a CloudFormation template — CDK is an abstraction layer, not a replacement.
Secure Credential Injection
high freqUse dynamic references {{resolve:secretsmanager:MySecret:SecretString:password}} in CloudFormation templates to inject secrets at resource creation time without storing credentials in the template or parameter values. The secret value is never exposed in CloudFormation events or the console. Critical for RDS master passwords, API keys, and other credentials passed to resource properties.
The 500-resource limit per stack is the most tested CloudFormation limit. The solution is ALWAYS nested stacks (AWS::CloudFormation::Stack) or splitting into separate stacks with cross-stack references. Nested stacks are preferred when resources are tightly coupled; separate stacks with Fn::ImportValue are preferred when teams own different layers independently.
DeletionPolicy: Retain vs. DeletionPolicy: Snapshot — Retain keeps the resource as-is with no data export; Snapshot creates a final snapshot before deletion (supported by RDS, ElastiCache, Redshift, EBS volumes). For stateful databases on exam questions about preventing data loss during stack deletion, Snapshot is the safer answer. Retain is correct when you need the live resource to persist.
Change Sets are the correct answer for 'how to safely preview infrastructure changes before applying them in production.' They show which resources will be Added, Modified (with replacement vs. no-replacement distinction), or Removed. CRITICAL: Creating a change set does NOT execute it — you must explicitly execute it. This two-phase approach is the exam-preferred pattern for production deployments.
StackSets SERVICE_MANAGED mode (with AWS Organizations) automatically deploys to new accounts joining an OU and requires NO manual trust relationship setup. SELF_MANAGED mode requires you to manually create IAM roles (AWSCloudFormationStackSetAdministrationRole and AWSCloudFormationStackSetExecutionRole) in both admin and target accounts. Exam questions about 'automatically deploying to new accounts' always point to SERVICE_MANAGED + Organizations.
CloudFormation Custom Resources backed by Lambda MUST send a response to the pre-signed S3 URL provided in the event. If the Lambda function fails silently (exception not caught, timeout, no response sent), CloudFormation will wait the full timeout period (up to 1 hour for Create/Update, 1 hour for Delete) before marking the stack as FAILED. Always wrap Lambda custom resource handlers in try/catch and always call cfnresponse.send() in both success and failure paths.
500 resources per stack limit → use Nested Stacks (AWS::CloudFormation::Stack). Template > 51,200 bytes → store in S3. Template > 1 MB → decompose into nested stacks. These three limits and their solutions appear on every certification exam.
Change Sets = preview before you apply. DeletionPolicy: Snapshot = safe database deletion. StackSets + Organizations SERVICE_MANAGED = auto-deploy to new accounts. These three patterns are the most frequently tested CloudFormation scenarios across all six certifications.
Service Catalog is NOT a replacement for CloudFormation — it is a governance layer ON TOP of CloudFormation. When users need self-service provisioning WITHOUT direct CloudFormation IAM permissions, the answer is Service Catalog with a launch role. When the question is about drift, compliance, or unauthorized changes, the answer is CloudFormation Drift Detection + AWS Config + SSM Automation.
Fn::ImportValue (cross-stack references) creates a hard dependency between stacks. You CANNOT delete or update the exporting stack's output while another stack is importing it. This is a common operational trap in exam scenarios about stack lifecycle management. To break the dependency, you must first update or delete the importing stack.
Stack Policies prevent accidental updates to critical resources. Once applied, a stack policy CANNOT be deleted — only updated. The default stack policy (when none is set) allows all updates. A common pattern: set a stack policy that denies Replace and Delete on RDS instances, then temporarily override it with an explicit Allow when a planned replacement is needed.
CloudFormation Drift Detection identifies resources that have been manually changed outside of CloudFormation (e.g., someone manually modified a security group). Drift detection does NOT automatically remediate — it only reports the drift status (DRIFTED, IN_SYNC, NOT_CHECKED). Remediation requires re-deploying the stack or using AWS Config + SSM Automation. Exam questions about 'detecting unauthorized changes' point to drift detection.
AWS CDK synthesizes CloudFormation templates. CDK is NOT a separate deployment mechanism — it uses CloudFormation under the hood. CDK apps create CloudFormation stacks. All CloudFormation limits (500 resources, 200 parameters, etc.) still apply to CDK-generated stacks. CDK bootstrap (cdk bootstrap) creates a CloudFormation stack called CDKToolkit that provisions an S3 bucket and ECR repository for assets.
Dynamic references syntax matters: SSM Parameter Store plain text: {{resolve:ssm:parameter-name:version}}, SSM SecureString: {{resolve:ssm-secure:parameter-name:version}}, Secrets Manager: {{resolve:secretsmanager:secret-id:SecretString:json-key:version-stage:version-id}}. SecureString values are NOT shown in CloudFormation console events — they are masked. This is a security feature, not a bug.
Service Catalog vs. CloudFormation direct access: Service Catalog is the answer when the question mentions 'self-service provisioning with governance,' 'end users who should not have direct CloudFormation permissions,' or 'approved catalog of infrastructure products.' The key distinction: Service Catalog uses a launch role with elevated permissions, so end users can provision resources they couldn't create directly.
CreationPolicy with cfn-signal is the correct pattern for waiting until EC2 instances finish bootstrapping (UserData scripts, software installation) before CloudFormation marks the stack as CREATE_COMPLETE. Without CreationPolicy, CloudFormation marks EC2 as complete as soon as the API call succeeds — even if UserData is still running. WaitCondition is the older equivalent for non-EC2 resources.
cfn-init reads the AWS::CloudFormation::Init metadata block to install packages, create files, and start services on EC2 instances in a structured way. It is idempotent and more reliable than raw UserData scripts. cfn-hup daemon monitors for metadata changes and re-runs cfn-init when the stack is updated — enabling configuration updates without replacing instances.
Common Mistake
Manual deployment through the AWS Console gives better control and visibility than CloudFormation automation, and is more reliable for complex architectures.
Correct
Manual deployments create configuration drift, are not repeatable, cannot be version-controlled, and have no automatic rollback. CloudFormation provides superior control through change sets (preview before apply), rollback triggers (CloudWatch Alarm integration), drift detection, and a complete audit trail via CloudTrail. 'Control' in AWS architecture means predictability and auditability — both of which favor IaC over manual processes.
This is the #1 misconception tested in DOP-C02 and SAP-C02. Exam scenarios describe a team that manually configures production and asks for improvements — the answer is always CloudFormation (or CDK/Terraform), not 'better documentation of manual steps.' Manual processes are an anti-pattern in the Well-Architected Framework's Operational Excellence pillar.
Common Mistake
CloudFormation and AWS Service Catalog are interchangeable tools — if you have CloudFormation templates, you don't need Service Catalog.
Correct
Service Catalog solves a governance and access control problem that raw CloudFormation cannot address alone. Service Catalog allows end users to self-provision approved infrastructure WITHOUT having IAM permissions to use CloudFormation directly. The Service Catalog launch role acts on behalf of the user with elevated permissions. Service Catalog also enforces approved template versions, tagging policies, and budget constraints — governance features absent from standalone CloudFormation.
Exam questions about 'developers provisioning infrastructure without CloudFormation access' or 'enforcing approved architecture patterns across teams' always resolve to Service Catalog backed by CloudFormation, not direct CloudFormation access. The key differentiator is the separation of governance (admin defines products) from consumption (users deploy products).
Common Mistake
CloudFormation Drift Detection automatically fixes configuration drift when it detects resources that have been manually modified.
Correct
Drift Detection is DETECTION ONLY — it identifies and reports which resources have drifted from their CloudFormation-defined state, but takes NO automatic remediation action. To fix drift, you must either: (1) re-deploy the CloudFormation stack to overwrite the manual changes, (2) update the template to match the manual changes and re-deploy, or (3) use AWS Config Rules with SSM Automation remediation actions for automated correction.
Exam questions about 'automatically remediating unauthorized changes' require Config + SSM Automation, not CloudFormation drift detection alone. Drift detection answers the question 'what changed?' — remediation answers 'how do I fix it?' These are separate concerns requiring separate tools.
Common Mistake
When a CloudFormation stack update fails, you need to manually clean up partially created resources before retrying.
Correct
CloudFormation automatically rolls back to the last known good state when a stack update fails (ROLLBACK_IN_PROGRESS → UPDATE_ROLLBACK_COMPLETE). Resources that were successfully created during the failed update are automatically deleted or reverted. You do NOT need to manually clean up. The only exception is if rollback itself fails (UPDATE_ROLLBACK_FAILED state), which requires manual intervention using the ContinueUpdateRollback API with resource skipping.
The automatic rollback behavior is a core CloudFormation safety feature. Exam questions about 'what happens when a CloudFormation update fails' should answer 'automatic rollback.' The ROLLBACK_FAILED edge case (where you must use ContinueUpdateRollback) is a separate scenario tested in advanced exams.
Common Mistake
Nested stacks and cross-stack references (Fn::ImportValue) are the same pattern and solve the same problems.
Correct
These are distinct patterns for different use cases. Nested stacks (AWS::CloudFormation::Stack) embed child stacks within a parent — they are deployed and managed together as a unit. Cross-stack references use Outputs + Fn::ImportValue to share values between INDEPENDENT stacks that have separate lifecycles. Use nested stacks when resources are tightly coupled and deployed together. Use cross-stack references when teams own separate stacks independently (e.g., networking team owns VPC stack, application team imports VPC ID).
Exam scenarios describe organizational ownership patterns to guide the answer. 'Separate teams manage different layers' → cross-stack references. 'Modularize a large template into reusable components deployed together' → nested stacks. Confusing these leads to wrong answers on architecture design questions.
Common Mistake
Pre-provisioning maximum expected capacity in CloudFormation templates ensures operational excellence by eliminating scale-up delays.
Correct
Pre-provisioning maximum capacity is a cost anti-pattern, not an operational excellence pattern. The AWS Well-Architected Framework recommends right-sizing with Auto Scaling, on-demand provisioning, and CloudFormation templates that define scaling policies rather than fixed maximum capacity. CloudFormation templates should define Auto Scaling Groups with appropriate min/max/desired values, not statically provision peak capacity.
This misconception appears in SAP-C02 and SAA-C03 cost optimization questions. The correct answer always involves dynamic scaling (Auto Scaling Groups, Aurora Serverless, Lambda) rather than static over-provisioning. CloudFormation enables this by templating scaling policies, not by hardcoding resource counts.
Common Mistake
CloudFormation is free, so there is no cost impact from creating many stacks or running frequent deployments.
Correct
CloudFormation the service is free, but every resource it creates incurs standard AWS pricing. Additionally, frequent stack deployments can cause resource replacement (e.g., if a property change requires resource replacement, the old resource runs until the new one is ready, temporarily doubling cost). Change sets help preview replacement behavior before incurring costs. StackSets deploying to many accounts create resources in each account, multiplying costs.
The 'CloudFormation is free' statement is technically true but misleading. Exam questions about cost optimization with CloudFormation focus on the resources created, not the service itself. Understanding which template changes trigger resource replacement (vs. in-place update) is critical for cost-aware IaC design.
CDRM for CloudFormation Template Sections: Conditions, Descriptions, Resources (only mandatory section!), Mappings — plus Parameters, Outputs, Metadata, Transform. Remember: 'Resources' is the ONLY required section.
DRS for DeletionPolicy options: Delete (default, gone forever), Retain (keep it alive), Snapshot (save a backup first). For databases: always use Snapshot or Retain — never let Delete be the default.
CRUD for Change Set states: CREATE_PENDING → CREATE_IN_PROGRESS → CREATE_COMPLETE → then you EXECUTE it. Creating ≠ Executing — two separate API calls, two separate decisions.
The '500 Rule': 500 resources max per stack → solution is Nested Stacks. 1MB template max → solution is S3 storage. 51,200 bytes direct upload limit → solution is S3 URL. When you hit a limit, the answer is always 'go bigger' via nesting or S3.
For StackSets remember 'SASO': Self-managed = manual role Setup, Organizations-managed = Automatic account enrollment. The 'O' in SASO = Organizations = automatic.
CertAI Tutor · SAP-C02, DVA-C02, SAA-C03, DEA-C01, DOP-C02, CLF-C02 · 2026-02-21
In the Same Category
Comparisons
Guides & Patterns