2
votes

Hi I am working on AWS CDK to create load balancer. I am familiar with cloud formation. During creation of Load Balancer I want to give subnets as below.

LB:
    Type: AWS::ElasticLoadBalancingV2::LoadBalancer
    Properties:
      Tags:
        -
          Key: "Name"
          Value: !Ref "AWS::StackName"
      Subnets:
        -
          Fn::ImportValue: "infra-vpc-base::SubnetIdPrivateAz1"
        -
          Fn::ImportValue: "infra-vpc-base::SubnetIdPrivateAz2"

I tried to create LB in cdk as below.

lb = elbv2.ApplicationLoadBalancer(
        self, "LB",
        load_balancer_name="Load Balancer CDK",
        vpc = vpc,
        internet_facing= False,
        security_group= mws_vpc_sg_alb,
        vpc_subnets= ???
    )

In the above code vpc_subnets I want to give two subnets. In the above code vpc_subnets is of type typing.optional[aws_cdk.aws_ec2.SubnetSelection]= none.

Can someone help me to get subnet selection in AWS CDK?

4

4 Answers

2
votes

this is from an auto scaling group but should be the same:

vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType('PUBLIC'))
2
votes

Other way to find subnets in VPC - no need to hardcode IDs:

vpc_subnets=ec2.SubnetSelection(
            subnets=vpc.select_subnets(subnet_name='Private').subnets
        )
1
votes

Below code fixed my issue.

    subnetid1 = ec2.Subnet.from_subnet_attributes(self,'subnetid1', availability_zone = 'apse2-az1', subnet_id = 'subnet-9bb42fed')
    subnetid2 = ec2.Subnet.from_subnet_attributes(self,'subnetid2', availability_zone = 'apse2-az1', subnet_id = 'subnet-cfbfceab')
    vpc_subnets_selection = ec2.SubnetSelection(subnets = [subnetid1, subnetid2])


    #create application load balancer
    lb = elbv2.ApplicationLoadBalancer(
        self, "MWSLoadBalancer",
        load_balancer_name="MerchWebServices Load Balancer CDK",
        vpc = vpc,
        internet_facing= False,
        security_group= mws_vpc_sg_alb,
        vpc_subnets= vpc_subnets_selection
    )
0
votes

There is from_subnet_id() now:

from aws_cdk import aws_ec2 as cdk_ec2


subnet_ids = ["subnet-firstsubnet", "subnet-secndsubnet"]
subnets = []
for idx, subnet_id in enumerate(subnet_ids):
    subnets.append(
        cdk_ec2.Subnet.from_subnet_id(
            scope=self,
            id=f"subnet{idx}",
            subnet_id=subnet_id
        )
    )

This will create a list of ISubnet objects, which can then be used with other methods like SubnetSelection, which can in turn be passed to some constructs. For example, FargateService accepts an argument vpc_subnets, which can use the above list like this (ignored the other arguments):

FargateService(
    (...)
    vpc_subnets=cdk_ec2.SubnetSelection(subnets=subnets)
)

What is the difference to Niranjan's answer? Well, seeing as AZ and RouteID are optional on from_subnet_attributes(), I don't know. I'll just leave this answer here because it has some additional links.