Kokil Thapa - Professional Web Developer in Nepal
Freelancer Web Developer in Nepal with 15+ Years of Experience

Kokil Thapa is an experienced full-stack web developer focused on building fast, secure, and scalable web applications. He helps businesses and individuals create SEO-friendly, user-focused digital platforms designed for long-term growth.

AWS CloudFormation Fundamentals

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.

AWS CloudFormation Stack WorkflowTemplateYAML or JSONValidatecfn-lint / CLIDeployCreateStack APIStackLIVE resourcesStack-Managed AWS ResourcesVPCEC2RDSS3 BucketSecurity Groups
AWS CloudFormation fundamentals: a validated template deploys a stack that owns every linked resource

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.

CloudFormation Template SectionsAWSTemplateFormatVersion + DescriptionParametersEnv, instance type, CIDRMappingsRegion-specific AMIsResources (required)EC2, RDS, S3, IAM roles, Lambda, VPCOutputsExport URLs, ARNsConditionsCreate only in prod
Template anatomy for AWS CloudFormation fundamentals: Parameters feed Resources; Outputs expose values to other stacks

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

  1. Validate the template locally with cfn-lint template.yaml.
  2. Upload the template to S3 if it exceeds 51,200 bytes or you want version history.
  3. Run aws cloudformation create-stack with parameters and capabilities.
  4. 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
Stack Lifecycle StatesCREATECOMPLETEUPDATECOMPLETEROLLBACKDELETEDrift DetectionManual vs templateFailed creates/updates auto-rollback unless you disable it
Stack lifecycle in AWS CloudFormation: failed operations roll back; drift detection catches manual console edits

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.

CriteriaAWS CloudFormationTerraform (OpenTofu)AWS CDK
LanguageYAML / JSON templatesHCLTypeScript, Python, Java, C#
Cloud scopeAWS onlyMulti-cloud + many providersAWS primary; limited other targets
State managementAWS-managed (the stack)Remote state file (S3, etc.)Synthesizes to CloudFormation
Day-one speedModerate; verbose YAMLFast with modulesFast for developers who code
RollbackBuilt-in automatic rollbackManual recovery planningInherits CloudFormation rollback
Best fitAWS-only teams, compliance, native integrationsMulti-cloud, mixed providersDeveloper 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.

IaC Tool Decision GuideAWS only or multi-cloud?AWS onlyMulti-cloudCloudFormationNative AWS IaCTerraformProvider ecosystemPrefer coding over YAML?Stick with YAML + macrosUse AWS CDK
Choosing between CloudFormation, Terraform, and CDK when learning AWS CloudFormation fundamentals

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-lint on every commit; it catches invalid properties before deploy.
  • Use taskcat or 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, and Owner for 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: Retain on 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

AWS CloudFormation is AWS’s native Infrastructure as Code service. You describe resources in a YAML or JSON template, deploy it as a named stack, and AWS creates or updates those resources through API calls. It is declarative: you define the desired end state, not a sequence of CLI commands.

CloudFormation itself has no charge. You pay only for the AWS resources the stack creates, such as EC2, RDS, and S3. Stack create, update, and delete operations are free.

The five essentials are templates, stacks, parameters, outputs, and change sets. A template is the declarative document. A stack is a deployed instance of that template in a Region and account. Parameters let one template serve staging and production. Outputs expose values, often exported for other stacks. Change sets preview updates before you commit them.

You write a template listing resources such as a VPC, subnets, security groups, EC2, and RDS. CloudFormation maps each logical ID you define to a physical resource ID, resolves dependencies, and runs create or update operations in order. Stack events appear in the console and CLI. If an operation fails mid-create, CloudFormation rolls back to the last stable state by default.

A template has up to nine top-level sections, but only Resources is required. Parameters feed values into Resources at deploy time. Outputs expose values such as bucket names or endpoints. Conditions let you include or skip resources based on parameter values. Optional sections like Description and Metadata help document and organise real projects stored in Git alongside application code.

Validate syntax first with cfn-lint, then run aws cloudformation validate-template. Create the stack with aws cloudformation create-stack, passing parameters and tags. Add --capabilities CAPABILITY_NAMED_IAM when the template creates named IAM roles or policies, or the stack fails immediately. Watch progress with aws cloudformation wait stack-create-complete until status reaches CREATE_COMPLETE. Upload the template to S3 if it exceeds 51,200 bytes or you want version history.

A change set is a preview of what a stack update will add, modify, or delete before you commit. On production stacks, never run blind updates. Some changes replace resources entirely, which is destructive for stateful items like RDS and causes downtime. Create the change set with aws cloudformation create-change-set, review it with describe-change-set, then execute only after you accept the impact.

Both solve Infrastructure as Code, but the trade-offs differ. CloudFormation uses YAML or JSON, is AWS-only, and keeps state AWS-managed inside the stack with built-in automatic rollback. Terraform uses HCL, supports multi-cloud and mixed providers, and stores state in a remote file such as S3. CloudFormation fits AWS-only teams wanting native StackSets, drift detection, and service-specific resource types. Terraform fits when you manage AWS plus other providers in one repo.

AWS CDK is not a replacement for CloudFormation. You write infrastructure in TypeScript, Python, Java, or C#, and CDK synthesises a CloudFormation template under the hood. Deployment still produces CloudFormation stacks with the same rollback behaviour. CDK suits developer teams who prefer real code over verbose YAML. CloudFormation suits teams comfortable with templates or compliance workflows that require plain declarative documents.

Never put database passwords or API keys in plain text inside a template. Use dynamic references to AWS Secrets Manager or SSM Parameter Store. The resolve syntax fetches the value at deploy time, so the secret never appears in the template body or stack events. On production Laravel workloads with RDS, this is the minimum bar before any stack touches a database resource.

Drift occurs when someone changes a resource manually in the console and it no longer matches the template. Run aws cloudformation detect-stack-drift, then describe-stack-resource-drifts to see what diverged. If security group rules drift after an incident hotfix, your next template update may overwrite that fix or fail unexpectedly. Run drift detection after any manual console change to keep the template trustworthy.

By default, CloudFormation rolls back to the previous stable state automatically. Resources that were partially created during the failed update get deleted. Resources that were partially modified revert where possible. That safety net alone saves hours on production incidents compared with imperative scripts where you must manually untangle half-finished changes.

Yes, through resource import. You define the resource in a template, then run an import operation to bring an existing S3 bucket, VPC, or other supported resource under stack management. Not every resource type supports import, so check AWS documentation before planning a migration from manual provisioning or console-clicked infrastructure.

DeletionPolicy Retain tells CloudFormation to keep a resource when the stack is deleted instead of destroying it. Set it on RDS instances, S3 buckets holding production data, and DynamoDB tables. Without Retain, deleting the stack destroys the data, which is one of the most expensive mistakes in Infrastructure as Code. Combine with termination protection on production stacks to block accidental delete-stack calls.

Split monolithic templates into layered stacks: network, data, and application, linked by exports and imports. Use nested stacks for repeated patterns like ALB plus Auto Scaling Group. Parameterise instance sizes so staging stays on smaller classes while production scales up. Run cfn-lint on every commit, deploy to a sandbox account first, tag stacks with Environment, Project, and Owner, and wire changes through CI/CD such as GitLab CI or CodePipeline so infrastructure passes the same review gate as application code.

Share this article

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.

Quick Contact Options
Choose how you want to connect me: