USA Independence Day Offers Are Live | Flat 20% OFF | Code: PROUD
Global Tech Council
aws7 min read

AWS CloudFormation Guide: Infrastructure as Code Templates, Stacks, and Best Practices

Suyash RaizadaSuyash Raizada

AWS CloudFormation skills matter because CloudFormation is still the native deployment engine behind much of AWS infrastructure as code. You write templates, deploy stacks, review change sets, enforce policy with Hooks, and scale the same pattern across accounts with StackSets. Work on AWS long enough and you will either write CloudFormation directly or use a tool such as AWS CDK that synthesizes to it.

Here is the practical view. CloudFormation is not the flashiest IaC tool, but it is the AWS control plane most teams cannot ignore. AWS documentation, re:Invent engineering sessions, and recent product announcements all point the same way. CloudFormation keeps gaining faster deployment modes, broader registry support, managed policy checks, visual design tools, and migration paths from manually created infrastructure.

Certified Agentic AI Expert Strip

What AWS CloudFormation Does

CloudFormation lets you define AWS resources in a JSON or YAML template, then create them as a managed unit called a stack. A template might describe an Amazon VPC, subnets, security groups, an Application Load Balancer, Auto Scaling, Amazon RDS, IAM roles, Amazon SNS topics, and outputs that other systems consume.

The important word is managed. Once a stack exists, CloudFormation tracks its resources, dependencies, updates, deletion behavior, and drift. AWS guidance is blunt on this point: do not change stack resources by hand in the console unless you are ready to reconcile drift afterward.

Templates

A CloudFormation template is usually written in YAML, though JSON is fully supported. YAML reads better in code reviews. JSON is stricter and sometimes preferred by tooling. Pick one for a team and stay consistent.

Common template sections include:

  • Parameters: user-supplied values, such as environment name or VPC CIDR.
  • Mappings: static lookup tables, often used for region-specific values.
  • Conditions: logic for optional resources.
  • Resources: the required section where AWS resources are declared.
  • Outputs: values exported for humans, automation, or cross-stack references.
  • Metadata: extra information used by tools or CloudFormation interfaces.

A tiny but real example:

Resources:
LogBucket:
Type: AWS::S3::Bucket
DeletionPolicy: Retain
Properties:
BucketEncryption:
ServerSideEncryptionConfiguration:
- ServerSideEncryptionByDefault:
SSEAlgorithm: AES256

That DeletionPolicy: Retain line is not decorative. The default behavior is delete. I have watched junior engineers remove a bucket resource from a template during a cleanup and only then learn that CloudFormation treats removal as a delete operation. For production data stores, logs, and buckets, decide the deletion policy before the first deployment.

Stacks

A stack is a deployed instance of a template. You create, update, delete, and inspect it through the CloudFormation console, CLI, SDK, or pipeline.

When updates are risky, use change sets. A change set shows what CloudFormation plans to add, modify, replace, or delete before you execute the update. Replacement is the word that should make you pause. For some resources, a small-looking property change forces CloudFormation to replace the resource, which can mean downtime or data migration work.

A common field error looks like this: Template format error: Unresolved resource dependencies [SubnetA] in the Resources block of the template. It usually means a Ref or DependsOn points to a logical ID that does not exist, often after a refactor. Logical IDs are not labels. Treat them like API names.

StackSets, Registry, Modules, and Hooks

StackSets for Multi-Account AWS

StackSets extend stacks across multiple AWS accounts and regions from a central administrator account. They fit enterprise baselines well: CloudTrail configuration, IAM guardrails, security tooling, networking defaults, and regional logging setup.

AWS has improved StackSet operations so non-conflicting operations can run concurrently while conflicting ones are queued. For large AWS Organizations environments, that cuts waiting time during fleet-wide changes.

CloudFormation Registry and Modules

The CloudFormation Registry holds AWS resource types, third-party resource types, and modules. Coverage has kept expanding through the registry model, and you can browse the resource types available in your region directly in the console or with the CLI.

Modules are reusable template building blocks. Instead of copying a 200-line secure S3 bucket pattern into ten repositories, a platform team can publish a module and let application teams consume it like a resource type. Use modules for patterns you want to standardize: VPCs, encrypted buckets, baseline IAM roles, and logging resources.

Hooks and CloudFormation Guard

CloudFormation Hooks run checks before stack, change set, or Cloud Control API operations change infrastructure. AWS managed Hooks for Lambda and CloudFormation Guard let teams enforce policy-as-code without wiring every integration from scratch.

Guard rules stored in Amazon S3 can reject a stack update if an S3 bucket lacks encryption or required tags. That beats finding the violation during an audit. Fail before production.

Newer CloudFormation Capabilities You Should Know

Express Mode

AWS introduced CloudFormation Express mode to cut deployment time by completing when resource configuration is applied rather than waiting for longer stabilization checks. AWS states that Express mode can reduce deployment time by up to 4x for suitable workflows, at no additional cost in supported commercial regions.

You enable it in stack deployment options or through the AWS CLI. Use it for fast iteration. Be more careful with stateful production systems where stabilization signals still matter to your release process.

Deployment Timeline View

The deployment timeline view gives a clearer picture of stack progress and resource dependencies. Sounds minor until you troubleshoot a stack with 80 resources and a slow RDS instance blocks everything behind it. Visibility saves time.

IaC Generator, CDK Migrate, and Console-to-Code

AWS now offers more bridges from manual infrastructure to code:

  • IaC Generator creates CloudFormation templates from existing AWS resources and their relationships.
  • CDK Migrate moves CloudFormation templates, deployed stacks, or manually created resources into an AWS CDK application.
  • Console-to-Code converts console actions into reusable CDK or CloudFormation code.
  • AWS Infrastructure Composer supports visual design and template generation for teams that prefer to start from an architecture diagram.

My take: use IaC Generator to document what already exists, not as a final clean template. Generated templates usually need naming cleanup, parameterization, tagging, and a security review before they belong in a repository.

CloudFormation Best Practices for Production

Keep Stacks Small Enough to Understand

Do not put the whole company in one stack. Split by lifecycle and ownership. Networking, shared observability, data stores, and application services often deserve separate stacks. Smaller stacks reduce blast radius and make change sets readable.

Use Parameters Carefully

Use AWS-specific parameter types such as AWS::EC2::KeyPair::KeyName where possible. Add allowed values, patterns, and descriptions. Use pseudo parameters such as AWS::Region and AWS::AccountId to keep templates portable.

Never hardcode secrets. Use AWS Secrets Manager, SSM Parameter Store, dynamic references, or secure CI/CD variables. Plaintext passwords in templates have a long half-life in Git history.

Validate Before Deploying

At minimum, run aws cloudformation validate-template. In real teams, add cfn-lint, CloudFormation Guard, and pipeline checks. A typo such as BucketEncrypton instead of BucketEncryption should fail in CI, not during a Friday deployment.

Review Change Sets

Make change sets part of the release habit. Look for Replacement: True, deleted resources, IAM changes, and updates to stateful services. Pair change sets with stack policies to protect critical databases or production networking resources.

Detect Drift

Drift detection compares live resources against the stack template. It is not magic, and it does not support every property for every resource, but it catches many manual changes. Schedule it for important stacks, especially shared infrastructure.

Tag Everything

Use a consistent tagging strategy. Tag for owner, environment, cost center, application, data classification, and lifecycle. Good tags make cost reports, incident response, and cleanup far less painful.

Use CloudTrail and Least Privilege

CloudTrail records CloudFormation API calls, which gives you an audit trail for infrastructure changes. Pair that with IAM least privilege. The CloudFormation execution role should hold only the permissions the stack needs, not blanket administrator access by default.

CloudFormation vs AWS CDK: Which Should You Use?

Use raw CloudFormation when you want transparent templates, strict review, simple stacks, or close alignment with AWS documentation. Use AWS CDK when your infrastructure has repeated patterns, conditional logic, multiple environments, or developer-heavy workflows.

CDK does not replace CloudFormation knowledge. It synthesizes to CloudFormation, and failed deployments still fail in CloudFormation terms. If you cannot read the generated template or interpret stack events, CDK will hide the problem until it hurts.

Learning Path for AWS Professionals

If you are building a cloud engineering skill plan, connect this guide to related Global Tech Council learning on AWS, DevOps, cybersecurity, data science infrastructure, and cloud automation. CloudFormation also pairs well with study in AWS CDK, CI/CD pipelines, IAM, network design, and policy-as-code.

For hands-on practice, build this sequence:

  1. Create a VPC and subnet stack with outputs.
  2. Create an application stack that imports those outputs.
  3. Add a change set review step in CI.
  4. Add Guard rules for encryption and tags.
  5. Deploy the same baseline with StackSets to a second account or region.
  6. Run drift detection after one controlled manual change, then fix it through code.

Start with one small production-like template this week. Add validation, change sets, tags, and a deletion policy. Then move to modules, Hooks, StackSets, and CDK once the basics feel boring. That is the right order.

Related Articles

View All

Trending Articles

View All