Practicing Infrastructure as Code with AWS CloudFormation - Template Design and Stack Management

Define infrastructure with templates and preview impact with change sets before deployment. Detect configuration drift with drift detection and deploy across your entire organization with StackSets.

Overview of CloudFormation

CloudFormation is an IaC service that declaratively defines AWS resources in YAML or JSON templates and provisions them as stacks. Compared to manual resource creation, it can be used for reproducing environments, version control, and automation. Templates can be managed in Git and integrated into code reviews and CI/CD pipelines, applying the same quality control processes used in software development to infrastructure changes. SAM is an extension of CloudFormation that simplifies the definition of serverless applications. Through the CloudFormation Registry, you can manage third-party and custom resource types in addition to AWS-native types.

Template Design and Stack Management

Templates define Parameters (up to 200) for deployment-time input values, Mappings for environment-specific settings, and Conditions for conditional logic. A single stack can manage up to 500 resources, and the template body size limit is 1 MB when uploaded via S3. When this limit is exceeded, nested stacks are used for partitioning, referencing child template URLs via AWS::CloudFormation::Stack resources. Change sets are created before stack updates to preview which resources will be added, modified, or deleted. Resources that trigger replacement cause temporary service interruption, so you review change sets in advance. The Outputs section combined with Export/ImportValue enables sharing resource ARNs and IDs across stacks, and one configuration option is to split stacks so that teams share the work. The DeletionPolicy attribute lets you specify Delete (default), Retain (preserve resource after stack deletion), or Snapshot (take a snapshot before deletion), systematically protecting critical data.

Drift Detection and StackSets

Drift detection identifies whether stack resources have deviated from their template definitions. Manual console operations or script-based changes are detected as drift, and you can review the differences from the template. Automate periodic drift detection with EventBridge schedules to catch configuration deviations early. Drift detection does not support all resource types, so you can check the supported resources list in the documentation. StackSets deploy the same template across multiple accounts and regions in a single operation. With Organizations integration, deployments are automated at the OU level. When a new account is added to an OU, the StackSet is automatically deployed. MaxConcurrentCount and FailureToleranceCount limit concurrency and tolerated failures in large-scale rollouts.

Design Best Practices and Pitfalls

In template design, be cautious about changing logical names (LogicalId). Changing a LogicalId triggers resource replacement, which can lead to data loss for stateful resources such as RDS instances or EBS volumes. Stack policies can block updates or deletions of important resources, and you can also set UpdateReplacePolicy: Retain on critical resources. Circular dependencies are a common error that causes template deployment failures, often occurring in mutual security group references; resolve them by using separate AWS::EC2::SecurityGroupIngress/Egress resources. When a rollback failure (UPDATE_ROLLBACK_FAILED) occurs, use the ContinueUpdateRollback API to specify resources to skip and recover the stack. For large templates, you can combine cfn-lint with TaskCat for multi-region simultaneous testing and cfn-guard for automated policy compliance validation.

Choosing Between Terraform and CDK

In AWS-only environments that don't require multi-cloud support, CloudFormation lets you use native features like StackSets and Organizations integration. State is automatically managed by AWS, eliminating the need to provision S3 buckets or lock tables. Terraform supports multi-cloud and can manage non-AWS resources in the same workflow, though users manage the state file (S3 + DynamoDB locking) themselves. CDK defines infrastructure in general-purpose programming languages like TypeScript or Python, leveraging language features such as loops, conditionals, and abstraction classes to express complex infrastructure concisely. Since CDK ultimately generates CloudFormation templates, you retain access to CloudFormation features like limits and drift detection. As a selection guide: StackSets for organizational guardrail deployment, CDK for programmable abstractions, and Terraform for multi-cloud scenarios.

Pricing and Limit Considerations

CloudFormation itself incurs no additional charges. Costs are limited to the usage fees of the provisioned AWS resources. Third-party resources (extension types via CloudFormation Registry) incur per-handler-operation charges (CREATE/UPDATE/DELETE/READ/LIST operations). Key limits include a default of 2,000 stacks per account (can be raised), 200 Outputs per template, and 200 Mappings per template. To improve template development efficiency, use cfn-lint to catch syntax errors early, and review change sets to confirm impact before deployment. Reuse common resources (VPCs, security groups) with nested stacks to eliminate template duplication. The Rain CLI can streamline template formatting and deployment.

Summary

CloudFormation is a template-based IaC service for creating the same infrastructure repeatedly. Change sets let you preview impact before deployment, and drift detection catches configuration deviations. StackSets deploy templates across your entire organization, automating multi-account, multi-region infrastructure management. You can protect stateful resources with DeletionPolicy and stack policies, and combine with CDK or Terraform for an IaC setup that fits your project.

References (Official AWS Resources)

The primary sources for this page are the official AWS website and documentation. Check the official pages below for the latest specifications and pricing.

If this page and the official documentation disagree, treat the official documentation as authoritative.

Share