Reputation: 155
I need to get subnet id from subnet name or cidr to deploy nat gateway. How can I get the subnet id? Or anyone have a best practice to use function of typescript? Sorry, I am a typescript rookie.
export class VpcTestStack extends cdk.Stack {
svc = 'common';
env = 'test';
cidr = '10.10';
vpc: ec2.CfnVPC;
constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
this.vpc = new ec2.CfnVPC(this, 'vpc', {
...
});
this.subnet_creation(this.availabilityZones[0], 'public-01-a', '.0.0/20');
this.subnet_creation(this.availabilityZones[2], 'public-01-c', '.16.0/20');
...
this.subnet_creation(this.availabilityZones[0], 'private-03-a', '.192.0/20');
this.subnet_creation(this.availabilityZones[2], 'private-03-c', '.208.0/20');
this.nat_creation('a', 'public-02-a')
this.nat_creation('c', 'public-02-c')
}
subnet_creation(availability_zone: string, subnet_name: string, subnet_cidr: string)
{
new ec2.CfnSubnet(this, 'subnet-' + subnet_name, {
availabilityZone: availability_zone,
cidrBlock: this.cidr + subnet_cidr,
vpcId: this.vpc.ref,
tags: [ { key: 'Name', value: this.svc + '-' + this.env + '-' + subnet_name } ]
});
}
nat_creation(az: string, subnet_name: string)
{
const natgw_eip = new ec2.CfnEIP(this, 'natgw-eip-' + az, {
domain: 'vpc'
});
new ec2.CfnNatGateway(this, 'natgw-' + az, {
allocationId: natgw_eip.attrAllocationId,
subnetId: ???, <---------------------------------------------------------------------- Here
tags: [ { key: 'Name', value: this.svc + '-' + this.env + '-natgw' + az } ]
});
}
}
Upvotes: 4
Views: 1416
Reputation: 10393
We can capture the subnet created and refer it (equvalant to !Ref in Cloudformation)
const myPublicSubnetOne: ec2.CfnSubnet = this.subnet_creation(
this.availabilityZones[0],
"public-01-a",
".0.0/20"
);
We need to return subnet from this method
subnet_creation(
availability_zone: string,
subnet_name: string,
subnet_cidr: string
) {
const subnet = new ec2.CfnSubnet(this, "subnet-" + subnet_name, {
availabilityZone: availability_zone,
cidrBlock: this.cidr + subnet_cidr,
vpcId: this.vpc.ref,
tags: [
{ key: "Name", value: this.svc + "-" + this.env + "-" + subnet_name },
],
});
return subnet;
}
Add input to your nat_creation function and refer as subnetId: myPubSubnet.ref,
nat_creation(az: string, myPubSubnet: ec2.CfnSubnet) {
const natgw_eip = new ec2.CfnEIP(this, "natgw-eip-" + az, {
domain: "vpc",
});
new ec2.CfnNatGateway(this, "natgw-" + az, {
allocationId: natgw_eip.attrAllocationId,
subnetId: myPubSubnet.ref,
tags: [{ key: "Name", value: this.svc + "-" + this.env + "-natgw" + az }],
});
}
pass the subnet itself , instead of a string.
this.nat_creation("a", myPublicSubnetOne);
Upvotes: 2