Logo

dev-resources.site

for different kinds of informations.

Customize VPCs with CloudFormation Conditions

Published at
1/13/2025
Categories
aws
vpc
cloudformation
iac
Author
mawulikode
Categories
4 categories in total
aws
open
vpc
open
cloudformation
open
iac
open
Author
10 person written this
mawulikode
open
Customize VPCs with CloudFormation Conditions

Using CloudFormation Conditions you can decide which resources to create/configure from your CloudFormation template.

In this post, we are going to build a template that can create a VPC with private subnets and a NAT gateway or only public subnets depending on a parameter when creating the CloudFormation stack.

Steps to create and use Conditions

  1. Define the input parameters you want your condition to evaluate.
  2. Define the condition by using the intrinsic condition functions.
  3. Declare the condition in resources or outputs you want to create.

Let's dive into the example!

Define the parameter and condition

In the first part of our template, we'll define our parameter and condition.

We associate the CreatePrivateResources condition with a value/option from our CreateNatGateway parameter. This enables us to do what has been discussed in the intro above.

Parameters:
  CreateNatGateway:
    Type: String
    Description: "Need a NAT Gateway?"
    AllowedValues:
      - yes
      - no
    Default: yes

Conditions:
  CreatePrivateResources: !Equals
    - !Ref CreateNatGateway
    - yes
Enter fullscreen mode Exit fullscreen mode

Define the public resources

Here, we will define our VPC, internet gateway, public subnets, routes and route tables. These resources will always be created. This is because they will not have any condition associated with them.

Resources:
  VPC:
    Type: AWS::EC2::VPC
    Properties:
      CidrBlock: "10.0.0.0/16"
      EnableDnsSupport: true
      EnableDnsHostnames: true
      Tags:
        - Key: Name
          Value: !Sub "${AWS::StackName}-VPC"

  # Public Resources
  InternetGateway:
    Type: AWS::EC2::InternetGateway
    Properties:
      Tags:
        - Key: Name
          Value: !Sub "${AWS::StackName}-InternetGateway"

  AttachGateway:
    Type: AWS::EC2::VPCGatewayAttachment
    Properties:
      VpcId: !Ref VPC
      InternetGatewayId: !Ref InternetGateway

  PublicSubnet1:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref VPC
      CidrBlock: "10.0.1.0/24"
      MapPublicIpOnLaunch: true
      AvailabilityZone: !Select [0, !GetAZs ""]
      Tags:
        - Key: Name
          Value: !Sub "${AWS::StackName}-PublicSubnet1"

  PublicSubnet2:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref VPC
      CidrBlock: "10.0.2.0/24"
      MapPublicIpOnLaunch: true
      AvailabilityZone: !Select [1, !GetAZs ""]
      Tags:
        - Key: Name
          Value: !Sub "${AWS::StackName}-PublicSubnet2"

  PublicRouteTable:
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId: !Ref VPC
      Tags:
        - Key: Name
          Value: !Sub "${AWS::StackName}-PublicRouteTable"

  PublicRoute:
    Type: AWS::EC2::Route
    Properties:
      RouteTableId: !Ref PublicRouteTable
      DestinationCidrBlock: "0.0.0.0/0"
      GatewayId: !Ref InternetGateway

  PublicSubnet1RouteTableAssociation:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      SubnetId: !Ref PublicSubnet1
      RouteTableId: !Ref PublicRouteTable

  PublicSubnet2RouteTableAssociation:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      SubnetId: !Ref PublicSubnet2
      RouteTableId: !Ref PublicRouteTable

Enter fullscreen mode Exit fullscreen mode

Use the condition

We now apply our condition to selected resources which creates a private environment for us, i.e. NatGateway, private subnets and routes etc. If we choose no at the prompt, these will not get created.

We also control the display of outputs using the same conditions.

# Private Resources
  NatGateway:
    Condition: CreatePrivateResources
    Type: AWS::EC2::NatGateway
    Properties:
      AllocationId: !GetAtt EIPNatGateway.AllocationId
      SubnetId: !Ref PublicSubnet1
      Tags:
        - Key: Name
          Value: !Sub "${AWS::StackName}-NatGateway"

  EIPNatGateway:
    Condition: CreatePrivateResources
    Type: AWS::EC2::EIP
    Properties:
      Domain: vpc
      Tags:
        - Key: Name
          Value: !Sub "${AWS::StackName}-EIPNatGateway"

  PrivateSubnet1:
    Condition: CreatePrivateResources
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref VPC
      CidrBlock: "10.0.3.0/24"
      MapPublicIpOnLaunch: false
      AvailabilityZone: !Select [0, !GetAZs ""]
      Tags:
        - Key: Name
          Value: !Sub "${AWS::StackName}-PrivateSubnet1"

  PrivateSubnet2:
    Condition: CreatePrivateResources
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref VPC
      CidrBlock: "10.0.4.0/24"
      MapPublicIpOnLaunch: false
      AvailabilityZone: !Select [1, !GetAZs ""]
      Tags:
        - Key: Name
          Value: !Sub "${AWS::StackName}-PrivateSubnet2"

  PrivateRouteTable:
    Condition: CreatePrivateResources
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId: !Ref VPC
      Tags:
        - Key: Name
          Value: !Sub "${AWS::StackName}-PrivateRouteTable"

  PrivateRoute:
    Condition: CreatePrivateResources
    Type: AWS::EC2::Route
    Properties:
      RouteTableId: !Ref PrivateRouteTable
      DestinationCidrBlock: "0.0.0.0/0"
      NatGatewayId: !Ref NatGateway

  PrivateSubnet1RouteTableAssociation:
    Condition: CreatePrivateResources
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      SubnetId: !Ref PrivateSubnet1
      RouteTableId: !Ref PrivateRouteTable

  PrivateSubnet2RouteTableAssociation:
    Condition: CreatePrivateResources
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      SubnetId: !Ref PrivateSubnet2
      RouteTableId: !Ref PrivateRouteTable

Outputs:
  VPCId:
    Description: "VPC ID"
    Value: !Ref VPC
  PublicSubnet1Id:
    Description: "Public Subnet 1 ID"
    Value: !Ref PublicSubnet1
  PublicSubnet2Id:
    Description: "Public Subnet 2 ID"
    Value: !Ref PublicSubnet2
  PrivateSubnet1Id:
    Condition: CreatePrivateResources
    Description: "Private Subnet 1 ID"
    Value: !Ref PrivateSubnet1
  PrivateSubnet2Id:
    Condition: CreatePrivateResources
    Description: "Private Subnet 2 ID"
    Value: !Ref PrivateSubnet2
  NatGatewayId:
    Condition: CreatePrivateResources
    Description: "NAT Gateway ID"
    Value: !Ref NatGateway

Enter fullscreen mode Exit fullscreen mode

You can now customize your VPC creation just by changing a parameter.
Thanks for reading. Happy Building!

cloudformation Article's
30 articles in total
Favicon
Thrilled to Announce the Launch of My Book "Mastering Infrastructure as Code with AWS CloudFormation"
Favicon
[Solved] AWS Resource limit exceeded
Favicon
A Comparative Analysis of Terraform and CloudFormation
Favicon
AWS CDK Typescript Simple Project for Cloud Formation of Resources Required for Kubernetes Study
Favicon
Customize VPCs with CloudFormation Conditions
Favicon
AWS CloudFormation: Infrastructure as Code for Efficient Cloud Management
Favicon
Using CloudFormation to deploy a web app with HA
Favicon
Automated Control Rollout in AWS Control Tower
Favicon
Launch an EC2 instance in a custom-made VPC using cloud formation
Favicon
AWS Automatically Accept Transit Gateway Attachments for allowed CIDR and Account pairs
Favicon
AWS CloudFormation Git sync now allows you to review your stack changes via Pull Request (PR)
Favicon
Terraform vs. AWS CloudFormation: A Detailed Comparison
Favicon
Terraform vs CloudFormation: Choosing the Best IaC Tool
Favicon
Automating AWS Cost and Usage Report with CloudFormation
Favicon
Calling All Senior DevOps Trailblazers!
Favicon
Move aws resources from one stack to another cloudformation stack
Favicon
Amazon CloudFormation Custom Resources Best Practices with CDK and Python Examples
Favicon
Domesticate AWS nested stacks in Java: doing the chores Cloudformation doesn't do (w/ code samples)
Favicon
Please stop publishing AWS S3 buckets as static websites! Read here for a secure, fast, and free-ish approach [1st episode]
Favicon
App runner with CloudFormation AWS (json, nodejs, java )
Favicon
Introducing AWS CloudFormation
Favicon
Simple steps to create AWS EKS Cluster and Nodes
Favicon
Deep Dive on Amazon Managed Workflows for Apache Airflow Using CloudFormation
Favicon
Importing CloudFormation Resources to help fix deployments to Production
Favicon
Update Github token in Codepipeline with Cloudformation
Favicon
Integration of Chatbot(Amazon Lex) in a static website (Hosted on S3 and cloud front)
Favicon
AWS CloudFormation - Automating Cloud Infrastructure
Favicon
Creating an AWS Auto Scaling Architecture with a monitoring dashboard
Favicon
Terraform vs. AWS CloudFormation
Favicon
Use AWS StepFunctions for SSM Patching Alerts

Featured ones: