Home > Mobile >  YAML code to create multiple VPC using count in AWS cloudformation
YAML code to create multiple VPC using count in AWS cloudformation

Time:07-20

I'm new to CloudFormation and want to create a template using YAML. I need to figure out is there any way we can create multiple VPCs using UserInput. As of now, I've used the following code:

  Parameters:
      EnvironmentName:
        Description: An environment name that is prefixed to resource names
        Type: String
    
    vpcCIDR1:
      Description: Please enter the IP range (CIDR notation) for this VPC
      Type: String
      Default: 10.3.0.0/16
    vpcCIDR2:
      Description: Please enter the IP range (CIDR notation) for this VPC
      Type: String
      Default: 10.4.0.0/16
Resources:
  VPC1:
    Type: AWS::EC2::VPC
    Properties:
      CidrBlock: !Ref vpcCIDR1
      EnableDnsSupport: true
      EnableDnsHostnames: true
      Tags:
        - Key: Name
          Value: !Ref EnvironmentName
  VPC2:
    Type: AWS::EC2::VPC
    Properties:
      CidrBlock: !Ref vpcCIDR2
      EnableDnsSupport: true
      EnableDnsHostnames: true
      Tags:
        - Key: Name
          Value: !Ref EnvironmentName

Instead of writing the same code again, I need the code to take user input for the VPCs count and create the VPCs according to the user input.

CodePudding user response:

Yes, you can do that if you develop your own macro. There are no loops nor any complex processing of user input in CloudFormation. But with macro, you can program any logic you want. Alternatively, you could also use custom resources, if you don't want macros.

CodePudding user response:

What about using a rudimentary bash script like this (I haven't fully tested the deployment and you'll need to modify your file name etc), but something like this would be a starting point:

#!/bin/bash

while read -n1 -r -p "Would you like to create another VPC: [y]es|[n]o"; do
  case $REPLY in
    y)  echo
        echo "Enter a VPC name: "
        read vpcName
        echo
        echo "Enter a VPC CIDR: "
        read vpcCIDR
        echo
        echo "Enter a VPC Environment: "
        read Environment
        echo
        echo "Creating VPC with:
        VPC Name: $vpcName
        VPC CIDR: $vpcCIDR
        VPC Environment: $Environment"
        echo
        aws cloudformation create-stack --stack-name myteststack --template-body file://sampletemplate.json \
        --parameters ParameterKey=vpcCIDR,ParameterValue=$vpcCIDR \
        ParameterKey=vpcName,ParameterValue=$vpcName \
        ParameterKey=Environment,ParameterValue=$Environment
        ;;

    n)  echo
        echo "Nothing further to do, good bye!"
        exit;;
  esac
done
  • Related