Skip to content

Dynamic variable in Cloudformation

0

I'm building a cloud formation template that deploys a vpc, igw, subnets and security groups. Everything is constant except for the second octet in the CIDR block. This will change per region.

Parameters: ClusterId: Type: String Description: Cluster ID

`Resources:

VPC

VPC: Type: 'AWS::EC2::VPC' Properties: CidrBlock: !Sub "10.${ClusterId}.0.0/16" EnableDnsSupport: true EnableDnsHostnames: true`

` #### Subnets ####

InfrastructureSubnetPrivateA: Type: "AWS::EC2::Subnet" Properties: AvailabilityZone: !Select [0, !GetAZs ] CidrBlock: !Sub "10.${ClusterId}.0.0/24" MapPublicIpOnLaunch: false VpcId: !Ref VPC Tags: - Key: Name Value: infrastructure-subnet-private-a - Key: Group Value: infrastructure`

` #### Security Groups ####

SecurityGroup1: Type: AWS::EC2::SecurityGroup Properties: GroupDescription: Security Group 1 VpcId: !Ref VPC SecurityGroupIngress: - CidrIp: !GetAtt InfrastructureSubnetPrivateA.CidrBlock IpProtocol: -1`

Problem: CidrIp under the security group requires a Cidr block. It doesn't accept the current format using !GetAtt. Is there a way to dynamically create and use a variable in Cloudformation? What other options do I have?

asked 3 years ago1K views
1 Answer
0

This is very common use case and every single team using subnet cidr needs this. Unfortunately, there is not a straight way of doing this but solution to this use case is fairly common and fortunately there is a step by step guide, which would help you achieve end result.

AWS::EC2::Subnet type resource can't return its CIDR.

You'd need to create custom resource lambda function and then use that resource in your cloudformation template with syntax as !GetAtt CidrFindr.CidrBlock1 where CidrFindr is custom resource lambda function.

Here is the AWS CIDR Finder Solution, this has very detailed instructions in it and you should be able to use it quite comfortably.

AWS
EXPERT
answered 3 years ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.