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.
Read More at https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/stacks.html
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
Example Using Nested to Provision EKS cluster with custom VPC.
Complete Code: https://github.com/Muhammad-Usama-1/aws-eks-cloudformation
AWSTemplateFormatVersion: "2010-09-09"
Description: "Amazon EKS Cluster with VPC"
Parameters:
ClusterName:
Type: String
Default: my-eks-cluster
Resources:
## Nested Stack - VPC Setup
VpcStack:
Type: AWS::CloudFormation::Stack
#PLEASE PLACE THE TemplateURL OF YOUR VPC
Properties:
TemplateURL: "" # S3 URL to VPC template
#Parameters:
## Eks Cluster
EksCluster:
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
andEksNodeRole
) are defined for the EKS cluster and node group to interact securely with AWS services.The
EksCluster
andEksNodegroup
resources configure the EKS cluster and its associated node group, leveraging the VPC resources created by theVpcStack
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.