AWS CloudFormation Best Practices

AWS CloudFormation Best Practices

  • AWS CloudFormation Best Practices are based on real-world experience from current AWS CloudFormation customers
  • AWS CloudFormation Best Practices help provide guidelines on
    • how to plan and organize stacks,
    • create templates that describe resources and the software applications that run on them,
    • and manage stacks and their resources

Required Mainly for Developer, SysOps Associate & DevOps Professional Exam

Planning and Organizing

Shorten the Feedback Loop to Improve Development Velocity

  • Adopt practices and tools that help shorten the feedback loop for infrastructure described with CloudFormation templates.
  • Perform early linting and testing of templates in your workstation to discover potential syntax and configuration issues before submitting to a source code repository.
  • Use CloudFormation Linter (cfn-lint) to validate templates against the CloudFormation Resource Specification, including checking valid values for resource properties and best practices.
  • Use TaskCat to test templates by programmatically creating stacks in the AWS Regions you choose, generating pass/fail reports per Region.
  • Integrate cfn-lint in your source code repository for pre-commit validation of templates.
  • Use the CloudFormation Language Server (launched 2025) in your IDE via AWS Toolkit for context-aware auto-completion, built-in validation, and drift-aware deployment views.

Organize Your Stacks By Lifecycle and Ownership

  • Use the lifecycle and ownership of the AWS resources to help you decide what resources should go in each stack.
  • By grouping resources with common lifecycles and ownership, owners can make changes to their set of resources by using their own process and schedule without affecting other resources.
  • Use two common frameworks for organizing stacks: a multi-layered architecture (horizontal layers with dependencies) or a service-oriented architecture (SOA) (self-contained services wired together).
  • For e.g. Consider an Application using Web and Database instances. Both the Web and Database have a different lifecycle and usually the ownership lies with different teams. Maintaining both in a single stack would need communication and co-ordination between different teams introducing complexity. It would be best to have different stacks owned by the respective teams, so that they can update their resources without impacting each other’s stack.

Use Cross-Stack References to Export Shared Resources

  • With multiple stacks, there is usually a need to refer values and resources across stacks.
  • Use cross-stack references to export resources from a stack so that other stacks can use them.
  • CloudFormation provides two approaches:
    • Fn::ImportValue – Import values that another stack has explicitly exported. Creates a strong reference within the same account and Region. CloudFormation prevents deleting the exporting stack while other stacks depend on its exports.
    • Fn::GetStackOutput – Reference any stack output directly, including outputs from stacks in other AWS accounts or Regions, without requiring explicit exports. Creates a weak reference resolved at create or update time.
  • For e.g. Web stack would always need resources from the Network stack like VPC, Subnets etc.

Use CloudFormation StackSets for Multi-Account and Multi-Region Deployments

  • CloudFormation StackSets extend the capability of stacks by enabling you to create, update, or delete stacks across multiple accounts and Regions with a single operation.
  • Use StackSets for deploying common infrastructure components, compliance controls, or shared services across your organization.
  • Implement service-managed permissions with AWS Organizations for simplified permission management without manually configuring IAM roles in each account.
  • StackSets Deployment Ordering (2025): Supports defining the sequence in which stack instances automatically deploy across accounts and regions using the DependsOn parameter (up to 10 dependencies per stack instance).

Use IAM to Control Access

  • Use IAM to control access to
    • what AWS CloudFormation actions users can perform, such as viewing stack templates, creating stacks, or deleting stacks
    • what actions CloudFormation can perform on resources on their behalf
  • Remember, having access to CloudFormation does not provide user with access to AWS resources. That needs to be provided separately.
  • To separate permissions between a user and the AWS CloudFormation service, use a service role. AWS CloudFormation uses the service role’s policy to make calls instead of the user’s policy.
  • Apply the principle of least privilege – Grant only the permissions necessary for the intended functionality, and avoid using wildcard permissions.
  • Use IAM Access Analyzer to review permissions granted to CloudFormation service roles and identify unused permissions.

Verify Quotas for All Resource Types

  • Ensure that stack can create all the required resources without hitting the AWS account limits.
  • By default, you can only launch 2000 CloudFormation stacks per Region in your AWS account.

Reuse Templates to Replicate Stacks in Multiple Environments

  • Reuse templates to replicate infrastructure in multiple environments
  • Use parameters, mappings, and conditions sections to customize and make templates reusable
  • for e.g. creating the same stack in development, staging and production environment with different instance types, instance counts etc.

Use Nested Stacks to Reuse Common Template Patterns

  • Nested stacks are stacks that create other stacks.
  • Nested stacks separate out the common patterns and components to create dedicated templates for them, preventing copy pasting across stacks.
  • for e.g. a standard load balancer configuration can be created as nested stack and just used by other stacks

Use Modules to Reuse Resource Configurations

  • Modules allow packaging resource configurations for inclusion across stack templates in a transparent, manageable, and repeatable way.
  • Modules can encapsulate common service configurations and best practices as modular, customizable building blocks.
  • Modules can be for a single resource (e.g., best practices for an EC2 instance) or multiple resources (common application architecture patterns).
  • Modules can be nested into other modules for higher-level building blocks.
  • Available in the CloudFormation registry and can be used like a native resource.
  • When using a module, the template is expanded into the consuming template, allowing access to resources inside using Ref or Fn::GetAtt.

Adopt Infrastructure as Code Practices

  • Treat CloudFormation templates as code by implementing Infrastructure as Code (IaC) practices.
  • Store templates in version control systems, implement code reviews, and use automated testing.
  • Implement CI/CD pipelines using AWS CodePipeline, CodeBuild, and CodeDeploy for automated infrastructure deployments.
  • Use CloudFormation Git Sync to automatically trigger deployments whenever a tracked Git repository is updated, with support for Pull Request review workflows (2024).

Creating Templates

Do Not Embed Credentials in Your Templates

  • Use dynamic references in your stack template rather than embedding sensitive information.
  • Dynamic references provide a compact way to reference external values stored in other services:
    • AWS Systems Manager Parameter Store – for configuration data and secure strings
    • AWS Secrets Manager – for passwords, database credentials, API keys, and other secrets with rotation support
  • CloudFormation retrieves the value of the dynamic reference during stack and change set operations but never stores the actual reference value.
  • Use the NoEcho property to obfuscate parameter values if using input parameters. Note that NoEcho doesn’t prevent values from being logged if passed to other services.

Use AWS-Specific Parameter Types

  • For existing AWS-specific values, such as existing Virtual Private Cloud IDs or an EC2 key pair name, use AWS-specific parameter types.
  • AWS CloudFormation can quickly validate values for AWS-specific parameter types before creating your stack.
  • The CloudFormation console shows a drop-down list of valid values, eliminating the need to look up or memorize IDs.

Use Parameter Constraints

  • Use Parameter constraints to describe allowed input values so that CloudFormation catches any invalid values before creating a stack.
  • Set constraints such as minimum length, maximum length, and allowed patterns.
  • For e.g. constraints for database user name with min and max length

Use Pseudo Parameters to Promote Portability

  • Use pseudo parameters (AWS::Partition, AWS::Region, AWS::AccountId, AWS::StackName) as arguments for intrinsic functions to increase template portability across Regions and accounts.
  • Instead of hard-coding ARN values, use !Sub 'arn:${AWS::Partition}:ssm:${AWS::Region}:${AWS::AccountId}:parameter/MySampleParameter'.
  • Use AWS::StackName as a prefix for exports to help ensure unique export names.

Use AWS::CloudFormation::Init to Deploy Software Applications on Amazon EC2 Instances

  • Use AWS::CloudFormation::Init resource and the cfn-init helper script to install and configure software applications on EC2 instances.
  • Describe desired configurations rather than scripting procedural steps.
  • Configurations can be updated without recreating instances.

Use the Latest Helper Scripts

  • Helper scripts are updated periodically. Include yum install -y aws-cfn-bootstrap in the UserData property before calling helper scripts.

Validate Templates Before Using Them

  • Validate templates before creating or updating a stack.
  • Validating a template helps catch syntax and some semantic errors, such as circular dependencies, before AWS CloudFormation creates any resources.
  • During validation, AWS CloudFormation first checks if the template is valid JSON or a valid YAML. If both checks fail, AWS CloudFormation returns a template validation error.
  • Use AWS CloudFormation Guard (cfn-guard) for policy-as-code validation to ensure templates comply with organizational policies, security best practices, and governance requirements.
  • Pre-deployment Validation (2025): CloudFormation now validates templates during change set creation, catching common errors like invalid property syntax, resource name conflicts, and S3 bucket constraints before resource provisioning begins.

Use YAML or JSON for Template Authoring

  • Use YAML when you prioritize human readability, want to include comments, or work with complex nested structures.
  • Use JSON when integrating with tools that prefer JSON, working with programmatic template generation, or requiring strict data validation.
  • YAML is generally recommended for manual template authoring due to readability and comment support.

Implement a Comprehensive Tagging Strategy

  • Implement a consistent tagging strategy for all resources created by CloudFormation templates.
  • Tags help with resource organization, cost allocation, access control, and automation.
  • Include tags for environment, owner, cost center, application, and purpose.
  • Use the stack’s Tags property to apply tags to all supported resources automatically.

Leverage Template Macros for Advanced Transformations

  • CloudFormation macros enable custom processing on templates, from find-and-replace operations to complex transformations that generate additional resources.
  • The AWS Serverless Application Model (SAM) is an example of a macro that simplifies serverless application development.

Managing Stacks

Manage All Stack Resources Through AWS CloudFormation

  • After launching the stack, any further updates should be done through CloudFormation only.
  • Doing changes outside the stack can create a mismatch between the stack’s template and the current state of the stack resources (known as drift), which can cause errors if you update or delete the stack.

Create Change Sets Before Updating Your Stacks

  • Change sets provide a preview of how the proposed changes to a stack might impact the running resources before you implement them.
  • CloudFormation doesn’t make any changes to the stack until you execute the change set, allowing you to decide whether to proceed with the proposed changes or create another change set.
  • Drift-Aware Change Sets (2025): Provides a three-way comparison between your new template, last-deployed template, and actual infrastructure state to prevent unexpected overwrites of drift and help keep infrastructure in sync with templates.

Use Stack Policies

  • Stack policies help protect critical stack resources from unintentional updates that could cause resources to be interrupted or even replaced.
  • During a stack update, you must explicitly specify the protected resources that you want to update; otherwise, no changes are made to protected resources.

Use AWS CloudTrail to Log AWS CloudFormation Calls

  • AWS CloudTrail tracks anyone making AWS CloudFormation API calls in the AWS account.
  • API calls are logged whenever anyone uses the AWS CloudFormation API, the AWS CloudFormation console, a back-end console, or AWS CloudFormation AWS CLI commands.
  • Enable logging and specify an Amazon S3 bucket to store the logs.

Use Code Reviews and Revision Controls to Manage Your Templates

  • Using code reviews and revision controls help track changes between different versions of your templates and changes to stack resources.
  • Maintaining history can help revert the stack to a certain version of the template.

Use Drift Detection Regularly

  • Regularly use the CloudFormation drift detection feature to identify resources that have been modified outside of CloudFormation management.
  • Detecting and resolving drift helps maintain the integrity of your infrastructure as code approach.
  • Consider implementing automated drift detection using AWS Lambda functions triggered by Amazon EventBridge rules to periodically check for drift and notify your team.
  • Use drift-aware change sets to systematically revert drift and keep infrastructure in sync with templates.

Configure Rollback Triggers for Automatic Recovery

  • Use rollback triggers to specify Amazon CloudWatch alarms that CloudFormation monitors during stack creation and update operations.
  • If any specified alarm goes into the ALARM state, CloudFormation automatically rolls back the entire stack operation.
  • Configure rollback triggers for critical metrics such as application error rates, resource utilization, or custom business metrics.

Implement Effective Stack Refactoring Strategies

  • Stack Refactoring (2025) enables reorganizing CloudFormation and CDK infrastructure without disrupting deployed resources.
  • Move resources between stacks, rename logical IDs, and decompose monolithic stacks into focused components while maintaining resource stability.
  • Use cases:
    • Splitting monolithic stacks into smaller, manageable stacks
    • Consolidating related resources from multiple stacks
    • Extracting reusable components into modules or nested stacks
    • Improving resource organization to reflect relationships and dependencies

Use CloudFormation Hooks for Lifecycle Management

  • CloudFormation Hooks provide code that proactively inspects the configuration of AWS resources before provisioning.
  • Hooks check if resources, stacks, and change sets are compliant with your organization’s security, operational, and cost optimization needs.
  • Can provide warnings before provisioning or fail the operation and stop it altogether.
  • Violations and warnings are logged in Amazon CloudWatch for visibility.
  • Managed Proactive Controls (2025): Hooks now supports managed proactive controls from the AWS Control Tower Controls Catalog, eliminating the need to write custom Hooks logic. Controls can run in warn mode for testing before enforcement.

Authoring Tools

Use IaC Generator to Create Templates from Existing Resources

  • IaC Generator (launched 2024) helps create CloudFormation templates from existing AWS resources that are managed outside CloudFormation.
  • Useful for replicating existing infrastructure, documenting manually created resources, or bringing unmanaged resources under CloudFormation management.
  • Targeted Resource Scans (2025): Supports scanning specific resource types instead of all resources, simplifying the template generation process.
  • Works with resource types supported by the Cloud Control API in your Region.

Use AWS Infrastructure Composer for Visual Template Design

  • AWS Infrastructure Composer (formerly AWS Application Composer) is a visual builder that helps create, visualize, and modify CloudFormation templates using drag-and-drop.
  • Useful for architecture planning, template modernization, training, and stakeholder communication.
  • Available in the CloudFormation console and as a VS Code extension via the AWS Toolkit.
  • Maintains a visual representation in sync with your IaC – changes in the visual canvas are reflected in the template and vice versa.

Consider Using AWS Cloud Development Kit (AWS CDK)

  • For complex infrastructure, use AWS CDK to define cloud resources using programming languages like TypeScript, Python, Java, and .NET.
  • AWS CDK generates CloudFormation templates from your code, combining CloudFormation capabilities with high-level programming constructs.
  • Provides high-level constructs that encapsulate best practices and simplify common infrastructure patterns.

Use the AWS IaC MCP Server for AI-Powered Development

  • AWS IaC MCP Server (2025) bridges AI assistants with AWS infrastructure development workflows using the Model Context Protocol (MCP).
  • Enables AI assistants to search CloudFormation and CDK documentation, validate templates, troubleshoot deployments, and follow best practices.
  • Provides remote documentation search tools and local validation/troubleshooting tools (cfn-lint, CloudFormation Guard, CloudTrail integration).

Security and Compliance

Implement Policy as Code with AWS CloudFormation Guard

  • AWS CloudFormation Guard (cfn-guard) is an open-source policy-as-code tool that allows defining and enforcing rules for CloudFormation templates.
  • Ensures templates comply with organizational policies, security best practices, and governance requirements.
  • Integrate cfn-guard into CI/CD pipelines to automatically validate templates against policy rules before deployment.
  • Includes a rulegen feature to extract rules from existing compliant CloudFormation templates.
  • Can be used with CloudFormation Hooks for proactive enforcement during provisioning.

Secure Sensitive Parameters

  • Use AWS Systems Manager Parameter Store or AWS Secrets Manager for sensitive information instead of embedding in templates.
  • Use dynamic references to securely retrieve values during stack operations:
    • {{resolve:ssm:parameter-name}} – for SSM Parameter Store values
    • {{resolve:ssm-secure:parameter-name}} – for SSM SecureString parameters
    • {{resolve:secretsmanager:secret-id}} – for Secrets Manager values
  • CloudFormation never stores the actual resolved secret value when using dynamic references.

AWS Certification Exam Practice Questions

  • Questions are collected from Internet and the answers are marked as per my knowledge and understanding (which might differ with yours).
  • AWS services are updated everyday and both the answers and questions might be outdated soon, so research accordingly.
  • AWS exam questions are not updated to keep up the pace with AWS updates, so even if the underlying feature has changed the question might not be updated
  • Open to further feedback, discussion and correction.
  1. A company has deployed their application using CloudFormation. They want to update their stack. However, they want to understand how the changes will affect running resources before implementing the updated. How can the company achieve the same?
    1. Use CloudFormation Validate Stack feature
    2. Use CloudFormation Dry Run feature
    3. Use CloudFormation Stage feature
    4. Use CloudFormation Change Sets feature
  2. You have multiple similar three-tier applications and have decided to use CloudFormation to maintain version control and achieve automation. How can you best use CloudFormation to keep everything agile and maintain multiple environments while keeping cost down?
    1. Create multiple templates in one CloudFormation stack.
    2. Combine all resources into one template for version control and automation.
    3. Use CloudFormation custom resources to handle dependencies between stacks
    4. Create separate templates based on functionality, create nested stacks with CloudFormation.
  3. You are working as an AWS DevOps admins for your company. You are in-charge of building the infrastructure for the company’s development teams using CloudFormation. The template will include building the VPC and networking components, installing a LAMP stack and securing the created resources. As per the AWS best practices what is the best way to design this template?
    1. Create a single CloudFormation template to create all the resources since it would be easier from the maintenance perspective.
    2. Create multiple CloudFormation templates based on the number of VPC’s in the environment.
    3. Create multiple CloudFormation templates based on the number of development groups in the environment.
    4. Create multiple CloudFormation templates for each set of logical resources, one for networking, and the other for LAMP stack creation.
  4. A team wants to ensure that all CloudFormation templates in their CI/CD pipeline comply with company security policies before deployment. Which approach should they use?
    1. Use CloudFormation drift detection before each deployment
    2. Manually review each template before deployment
    3. Integrate AWS CloudFormation Guard (cfn-guard) into the CI/CD pipeline to validate templates against policy rules
    4. Use CloudFormation Change Sets to validate compliance
  5. A DevOps engineer needs to detect and remediate configuration changes made to CloudFormation-managed resources outside of CloudFormation. What is the most effective approach introduced in 2025?
    1. Use standard Change Sets and manually compare with actual state
    2. Delete and recreate the stack
    3. Use Drift-Aware Change Sets that provide a three-way comparison between the new template, last-deployed template, and actual infrastructure state
    4. Use AWS Config rules to detect drift
  6. A company has manually created resources in their AWS account and wants to bring them under CloudFormation management. What is the recommended approach?
    1. Delete and recreate all resources using CloudFormation templates
    2. Use CloudFormation resource import only
    3. Use the IaC Generator to scan existing resources and generate CloudFormation templates, then import the resources
    4. Manually write CloudFormation templates for each resource
  7. An organization wants to enforce security controls on CloudFormation resource configurations before they are provisioned, without writing custom code. Which feature should they use?
    1. CloudFormation Stack Policies
    2. AWS Config rules in proactive mode
    3. CloudFormation Change Sets
    4. CloudFormation Hooks with managed proactive controls from the AWS Control Tower Controls Catalog

References

3 thoughts on “AWS CloudFormation Best Practices

  1. The blog was absolutely fantastic| Lot of great innovative information which can be very helpful. Thanks for sharing such wonderful information.

  2. What is the best practice for CloudFormation vs SAM?
    I saw some exercise question somewhere:

    How to create the stack following best practices. The stack contains an API GW, Lambda, DynamoDb and ElastiCache:

    – CloudFormation
    – SAM & CloudFormation
    – SAM

    1. SAM is for serverless and works with CloudFormation and CloudFormation can help with other service provisioning as well, so seems better option.

Comments are closed.