I have a subnet declaration like the following which creates one subnet for each AWS AZ in us-west-2
:
const dataAwsAvailabilityZonesAll =
new aws.datasources.DataAwsAvailabilityZones(this, "all", {});
const zoneNames = Fn.lookup(
dataAwsAvailabilityZonesAll.fqn,
"names",
undefined
);
const availabilityZone = Fn.element(
zoneNames,
Token.asNumber("count.index")
);
const publicSubnet = new aws.vpc.Subnet(this, "pub_subnet", {
availabilityZone,
cidrBlock: "${cidrsubnet(aws_vpc.vpc.cidr_block, 8, count.index)}",
mapPublicIpOnLaunch: true,
tags: {
name: environment + "-public-subnet-${(count.index + 1)}",
["kubernetes.io/cluster/" + eksClusterName]: "shared",
"kubernetes.io/role/elb": "1",
environment: environment,
public: "true",
},
vpcId: "${aws_vpc.vpc.id}",
});
publicSubnet.addOverride("count", Fn.lengthOf(zoneNames));
I'd like to refactor this to get rid of the usages of Fn.count
, Fn.lookup
, count.index
, etc. Instead, I'd like to have direct references to each subnet in typescript. I've tried doing the following:
const testSubnets = []
for (let i = 0; i++; i < Fn.lengthOf(zoneNames)) {
const s = Fn.element(zoneNames, i)
testSubnets.push(new aws.vpc.Subnet(this, `subnet-${s}`, {
availabilityZone: s,
cidrBlock:
`\${cidrsubnet(aws_vpc.vpc.cidr_block, 4, ${i + 3*dataAwsAvailabilityZonesAll.names.length})}`,
mapPublicIpOnLaunch: true,
tags: {
name: environment + `${environment}-large-public-subnet-${i}`,
["kubernetes.io/cluster/" + eksClusterName]: "shared",
"kubernetes.io/role/elb": "1",
environment: environment,
public: "true",
},
vpcId: clusterVpc.id
}))
}
but this alternative doesn't create any subnets at all. I've also tried using dataAwsAvailabilityZonesAll.names.length
and dataAwsAvailabilityZonesAll.names
directly but couldn't figure those out either. It seems that dataAwsAvailabilityZonesAll.names
is empty at runtime and that it doesn't resolve until much later in the CDKTF lifecycle.
How can I get the names of each AZ in a given region when using CDKTF? Instead of trying to automate each AZ, should I declare the AZs as a constant and use those when creating a subnet?