
September 09, 2026
12 min read
By Kokil Thapa | Last reviewed: September 2026
AWS CloudFormation fundamentals matter the moment your stack grows beyond a single EC2 instance and an RDS database. You need repeatable infrastructure that survives staff turnover, survives a bad Friday deploy, and matches what is actually running in the account. CloudFormation is AWS's native Infrastructure as Code (IaC) service: you describe resources in a YAML or JSON template, upload it, and AWS creates or updates a named stack. For teams shipping Laravel on AWS EC2 with RDS, or any production PHP workload, that model beats clicking through the console every time.
What is AWS CloudFormation and how does it work?
CloudFormation is AWS's declarative IaC engine. You write a template file listing the resources you want—a VPC, subnets, security groups, an EC2 instance, an RDS cluster—and CloudFormation translates that into API calls. The result is a stack: a logical container for every resource the template created.
That differs from imperative scripts that run aws ec2 run-instances one command at a time. With CloudFormation, you declare the desired end state. AWS figures out the order of operations, handles dependencies between resources, and rolls back if something fails mid-create.
In practice, this is the AWS-native counterpart to tools like Terraform. If your entire footprint lives on AWS and you want tight integration with IAM, StackSets, and service-specific resource types, CloudFormation is the default choice. For broader multi-cloud work, see our Terraform guide for AWS and Azure.
Every resource in a stack carries a logical ID you define in the template, such as WebServer or AppDatabase. CloudFormation maps that to a physical resource ID—the actual EC2 instance ID or RDS endpoint. You reference logical IDs inside the template using intrinsic functions like Ref and Fn::GetAtt.
Stack events appear in the CloudFormation console and via the CLI. When a create or update fails, CloudFormation rolls back to the last stable state by default. That safety net alone saves hours on production incidents.
Core concepts at a glance
- Template — the declarative document describing resources and their properties.
- Stack — a deployed instance of a template in a specific AWS Region and account.
- StackSet — deploy the same template across multiple accounts or Regions from one operation.
- Change set — a preview of what an update will add, modify, or delete before you commit.
- Drift — when someone changed a resource manually and it no longer matches the template.
For deeper IaC patterns on AWS, read our companion post on CloudFormation infrastructure as code.
How do you write a CloudFormation template?
A CloudFormation template has up to nine top-level sections. Only the Resources section is required. Everything else is optional but useful in real projects.
Minimal working template
Start with a small S3 bucket template. Store it in Git alongside your application code. Validate syntax with the JSON formatter if you write JSON, or use YAML for readability.
AWSTemplateFormatVersion: '2010-09-09'
Description: Minimal S3 bucket for Laravel file storage
Parameters:
EnvironmentName:
Type: String
Default: staging
AllowedValues: [staging, production]
Resources:
AppStorageBucket:
Type: AWS::S3::Bucket
Properties:
BucketName: !Sub 'myapp-${EnvironmentName}-uploads'
PublicAccessBlockConfiguration:
BlockPublicAcls: true
BlockPublicPolicy: true
IgnorePublicAcls: true
RestrictPublicBuckets: true
VersioningConfiguration:
Status: Enabled
Outputs:
BucketName:
Description: S3 bucket for application uploads
Value: !Ref AppStorageBucket
Export:
Name: !Sub '${AWS::StackName}-BucketName'
The short-form intrinsic functions (!Ref, !Sub) are YAML-only sugar. JSON templates use the long form: {"Ref": "AppStorageBucket"}. Official syntax lives in the AWS CloudFormation template anatomy guide.
Parameters and conditions
Parameters make one template work across environments. Pass EnvironmentName=production at deploy time instead of maintaining two nearly identical files. Use AllowedValues, MinLength, and AllowedPattern to catch bad input before AWS creates anything.
Conditions let you include or skip resources based on parameter values. A common pattern: create a Multi-AZ RDS instance only when EnvironmentName equals production. That keeps staging costs low while production stays resilient.
Cross-stack references
Large architectures split into nested stacks or separate stacks linked by exports. Stack A exports a VPC ID; Stack B imports it with Fn::ImportValue. This mirrors how you'd structure a VPC on AWS separately from application tiers.
Never rename or delete an export that another stack imports. CloudFormation blocks the operation until dependents release the import.
How do you deploy and update a CloudFormation stack?
Deployment starts with template validation, then stack creation. Use the AWS CLI, console, or CI/CD pipeline. I prefer CLI plus GitLab CI—the same pattern I use with Deployer on EC2, but for infrastructure instead of PHP code.
Deploy a new stack
- Validate the template locally with
cfn-lint template.yaml. - Upload the template to S3 if it exceeds 51,200 bytes or you want version history.
- Run
aws cloudformation create-stackwith parameters and capabilities. - Watch events until stack status reaches
CREATE_COMPLETE.
aws cloudformation validate-template \
--template-body file://template.yaml
aws cloudformation create-stack \
--stack-name myapp-staging-storage \
--template-body file://template.yaml \
--parameters ParameterKey=EnvironmentName,ParameterValue=staging \
--capabilities CAPABILITY_NAMED_IAM \
--tags Key=Project,Value=myapp Key=Environment,Value=staging
aws cloudformation wait stack-create-complete \
--stack-name myapp-staging-storage
The --capabilities CAPABILITY_NAMED_IAM flag is required when your template creates named IAM roles or policies. Without it, the stack fails immediately. Follow IAM least-privilege practices inside every role you define.
Update with change sets
Never run blind updates on production stacks. Create a change set first. It shows exactly which resources will be replaced—a destructive operation for stateful resources like RDS.
aws cloudformation create-change-set \
--stack-name myapp-staging-storage \
--change-set-name add-lifecycle-policy \
--template-body file://template-v2.yaml \
--parameters ParameterKey=EnvironmentName,ParameterValue=staging
aws cloudformation describe-change-set \
--stack-name myapp-staging-storage \
--change-set-name add-lifecycle-policy
aws cloudformation execute-change-set \
--stack-name myapp-staging-storage \
--change-set-name add-lifecycle-policy
Drift detection and stack policies
Drift detection compares live resources against the template. Run it after any incident where someone touched the console. If security group rules drift, your next template update may overwrite their hotfix—or fail unexpectedly.
aws cloudformation detect-stack-drift \
--stack-name myapp-staging-storage
aws cloudformation describe-stack-resource-drifts \
--stack-name myapp-staging-storage
Stack policies protect critical resources during updates. Attach a JSON policy that denies updates to production RDS instances unless a specific IAM principal initiates the change. Details are in the AWS stack policy documentation.
Wire CloudFormation into CI/CD on AWS with CodePipeline so infrastructure changes pass the same review gate as application code. Store templates in Git. Tag every stack with project, environment, and owner.
What is the difference between CloudFormation, Terraform, and AWS CDK?
All three solve IaC. The trade-offs are language, ecosystem, and operational model. Pick based on team skills and cloud scope—not hype.
| Criteria | AWS CloudFormation | Terraform (OpenTofu) | AWS CDK |
|---|---|---|---|
| Language | YAML / JSON templates | HCL | TypeScript, Python, Java, C# |
| Cloud scope | AWS only | Multi-cloud + many providers | AWS primary; limited other targets |
| State management | AWS-managed (the stack) | Remote state file (S3, etc.) | Synthesizes to CloudFormation |
| Day-one speed | Moderate; verbose YAML | Fast with modules | Fast for developers who code |
| Rollback | Built-in automatic rollback | Manual recovery planning | Inherits CloudFormation rollback |
| Best fit | AWS-only teams, compliance, native integrations | Multi-cloud, mixed providers | Developer teams wanting real code |
AWS CDK is not a replacement for CloudFormation—it compiles down to it. If you prefer TypeScript over YAML, read our AWS CDK infrastructure guide. CDK still produces CloudFormation stacks under the hood.
Terraform excels when you manage AWS plus Cloudflare DNS plus a Hetzner backup server in one repo. CloudFormation excels when you want AWS-native features like StackSets, drift detection, and service-specific resource types on day one.
What are CloudFormation best practices for production workloads?
Templates that work in a sandbox break in production when naming, secrets, and deletion policies are ignored. These practices come from running real PHP and Laravel workloads on AWS—not from certification cram guides.
Structure templates for reuse
Split monolithic templates into layers: network stack, data stack, application stack. Each layer exports values the next layer imports. On a booking platform like Adventure Third Pole Trek, the app stack can redeploy without touching the VPC.
Use nested stacks for repeated patterns. A nested stack for a standard web tier (ALB + ASG + security groups) keeps the root template readable. Update the nested template once; every parent stack picks it up on the next deploy.
Handle secrets correctly
Never put database passwords or API keys in plain text inside a template. Use dynamic references to AWS Secrets Manager or SSM Parameter Store.
Resources:
AppDatabase:
Type: AWS::RDS::DBInstance
Properties:
Engine: mysql
MasterUsername: admin
MasterUserPassword: !Sub '{{resolve:secretsmanager:myapp/db/credentials:SecretString:password}}'
DBInstanceClass: db.t4g.micro
AllocatedStorage: 20
VPCSecurityGroups:
- !Ref DatabaseSecurityGroup
The {{resolve:secretsmanager:...}} syntax tells CloudFormation to fetch the value at deploy time. The secret never appears in the template body or stack events.
Protect stateful resources
Set DeletionPolicy: Retain on RDS instances, S3 buckets with production data, and DynamoDB tables. Without it, deleting the stack destroys the data. That is the most expensive mistake in IaC.
Enable termination protection on production stacks. It blocks accidental delete-stack calls. Combine with stack policies for defense in depth.
Cost and operations for Nepal teams
Small teams in Nepal often run staging and production in one account with separate stacks. Parameterise instance sizes so staging uses t4g.micro while production uses t4g.small or larger. Budget alerts matter—see our guide on budgeting AWS in NPR for startups.
Compare hosting economics before committing. A Laravel hosting comparison across AWS, DigitalOcean, and Hetzner helps founders choose the right starting point. CloudFormation still adds value even on a single EC2 stack because it documents exactly what was provisioned.
For file storage patterns, pair your stack with the S3 setup guide for Laravel. For managed operations, Linux system administration services cover the server layer CloudFormation does not.
Testing and linting
- Run
cfn-linton every commit; it catches invalid properties before deploy. - Use
taskcator similar tools to test templates across Regions automatically. - Deploy to a sandbox account first; never experiment on production stacks.
- Tag all resources with
Environment,Project, andOwnerfor cost allocation. - Document every parameter in the template Description field—your future self will thank you.
The AWS CLI CloudFormation reference covers every command you'll use daily. Keep it bookmarked.
Key Takeaways
- AWS CloudFormation fundamentals boil down to templates, stacks, parameters, outputs, and change sets—master those five before advanced patterns.
- Always preview updates with change sets; replacements on RDS or EC2 cause downtime if you miss them.
- Split large architectures into layered stacks with exports/imports instead of one 2,000-line template.
- Use Secrets Manager dynamic references and
DeletionPolicy: Retainon every stateful resource. - Run drift detection after any manual console change to keep the template trustworthy.
- Choose CloudFormation for AWS-native IaC; reach for Terraform or CDK when multi-cloud or developer ergonomics demand it.
People Also Ask
Is CloudFormation free to use?
CloudFormation itself has no charge. You pay only for the AWS resources the stack creates—EC2, RDS, S3, and so on. Stack operations like create, update, and delete are free. This makes CloudFormation cost-effective even for small teams prototyping infrastructure.
Can CloudFormation manage existing resources?
Yes, through resource import. You define the resource in a template, then run an import operation to bring an existing S3 bucket or VPC under stack management. Not every resource type supports import, so check the documentation before planning a migration from manual provisioning.
What happens if a CloudFormation update fails?
By default, CloudFormation rolls back to the previous stable state automatically. Resources that were partially created get deleted. Resources that were being updated revert. You can disable rollback to debug failures, but that leaves the stack in an unstable state—use it only in non-production environments.
CloudFormation vs manually using the AWS console?
The console is fine for learning and one-off experiments. Production infrastructure should live in version-controlled templates. Manual changes cause drift, cannot be peer-reviewed, and disappear when the engineer who clicked the buttons leaves the team. CloudFormation gives you repeatability, audit trails, and rollback.
Build repeatable AWS infrastructure with confidence
AWS CloudFormation fundamentals give you a native, rollback-safe way to define infrastructure that matches your application lifecycle. Start with a small template—an S3 bucket, a security group, one EC2 instance. Add parameters, outputs, and change sets as the stack grows. Pair it with proper IAM, secrets management, and CI/CD, and you have a foundation that scales from a Kathmandu startup to a global SaaS.
If you want help designing CloudFormation stacks for a Laravel app, a legal-tech portal, or an eCommerce platform, enterprise application development and hosting setup services cover the full path from template to production. Review shipped work in the portfolio, or contact us to discuss your AWS architecture.
Frequently Asked Questions
0 Comments
Leave a comment
Your email is not published. Comments appear once they have been read. Sign in to have your details filled in.

