AWS CloudFormation Nested Stacks: Simplifying Infrastructure Management with Cloudformation Best Practices

AWS CloudFormation Nested Stacks: Simplifying Infrastructure Management with Cloudformation Best Practices

What is a Stack ?

A stack is a collection of AWS resources that you can manage as a single unit. In other words, you can create, update, or delete a collection of resources by creating, updating, or deleting stacks. All the resources in a stack are defined by the stack's AWS CloudFormation template.


What is a Nested Stack?

Nested stacks are stacks created as part of other stacks created in AWS cloudformation

Why we Need?

As your infrastructure scales, you may encounter repeated patterns where you define the same components across multiple templates. To manage this effectively, you can isolate these common components into dedicated templates. By doing so, you can reference these templates within your main template, effectively creating nested stacks. This approach helps streamline your infrastructure management and promotes the reusability of components across your stack configurations.


Example Using Nested to Provision EKS cluster with custom VPC.

Complete Code:

AWSTemplateFormatVersion: "2010-09-09"
Description: "Amazon EKS Cluster with VPC"
    Type: String
    Default: my-eks-cluster

  ## Nested Stack - VPC Setup
    Type: AWS::CloudFormation::Stack
      TemplateURL: "" # S3 URL to VPC template
  ## Eks Cluster
        SubnetIds: !Split [",", !GetAtt VpcStack.Outputs.PrivateSubnetIds]

This template utilizes nested stacks to separate concerns and manage resources more efficiently.

  • The VpcStack nested stack is responsible for creating the VPC resources required by the EKS cluster, such as subnets and security groups.

  • IAM roles (EksRole and EksNodeRole) are defined for the EKS cluster and node group to interact securely with AWS services.

  • The EksCluster and EksNodegroup resources configure the EKS cluster and its associated node group, leveraging the VPC resources created by the VpcStack nested stack.

To use this template, replace TemplateURL in the VpcStack resource with the S3 URL pointing to your VPC CloudFormation template, which should define the necessary VPC resources. Adjust other parameters and configurations as needed based on your specific requirements.

By leveraging nested stacks, you can modularize and reuse components such as VPC setups and IAM roles across templates, promoting better organization and reducing redundancy in your CloudFormation scripts. This approach not only enhances the maintainability of your infrastructure but also enables smoother deployments and scalability as your AWS environment grows. Take advantage of nested stacks to streamline your AWS CloudFormation workflows and optimize your infrastructure management practices.

Did you find this article valuable?

Support Muhammad Usama by becoming a sponsor. Any amount is appreciated!