Skip to content

Instantly share code, notes, and snippets.

@crohr
Created January 19, 2024 10:21
Show Gist options
  • Save crohr/70483dc8f8a6030349e3ef12d7364366 to your computer and use it in GitHub Desktop.
Save crohr/70483dc8f8a6030349e3ef12d7364366 to your computer and use it in GitHub Desktop.
Cloudformation template to get a dynamically generated CIDR block for subnets based on the selected availability zone
Mappings:
Networking:
AzSuffixToIndex:
1a: 0
1b: 1
1c: 2
1d: 3
1e: 4
1f: 5
1g: 6
2a: 0
2b: 1
2c: 2
2d: 3
2e: 4
2f: 5
2g: 6
3a: 0
3b: 1
3c: 2
3d: 3
3e: 4
3f: 5
3g: 6
4a: 0
4b: 1
4c: 2
4d: 3
4e: 4
4f: 5
4g: 6
Resources:
VPC:
Type: AWS::EC2::VPC
Properties:
CidrBlock: 10.0.0.0/16
EnableDnsSupport: true
EnableDnsHostnames: true
PublicSubnet:
Type: AWS::EC2::Subnet
Properties:
VpcId:
Ref: VPC
AvailabilityZone:
Ref: AvailabilityZone
# Dynamically generate a CIDR block with non-overlapping IP ranges for each possible AZ in the region
# https://docs.aws.amazon.com/fr_fr/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-cidr.html
CidrBlock: !Select [
!FindInMap [Networking, AzSuffixToIndex, !Select [ 2, !Split [ "-", !Ref AvailabilityZone]]],
!Cidr [!GetAtt [VPC, CidrBlock], 16, 12]
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment