0

I'm creating an Application Load Balancer using the AWS CDK v2.

This is my code:

    const lb = new elb.ApplicationLoadBalancer(this, 'LB', {
      vpc: ec2.Vpc.fromLookup(this, 'vpc-lookup', {
        isDefault: true
      }),
      internetFacing: true
    });

    const listener = lb.addListener('Listener', {
      port: 80,
    });

My question is how do I get the URL (DNS name) of the load balancer? I need it in the CDK after to update something

Moshe Shaham
  • 15,448
  • 22
  • 74
  • 114

1 Answers1

0

TL;DR The name's actual value is resolved at deploy-time. At synth-time, you can pass loadBalancerDnsName to other constructs and CDK will create the necessary references.

Resource identifiers like DNS addresses are generally known only only at deploy-time. The CDK uses Tokens to "represent values that can only be resolved at a later time in the lifecycle of an app" . ApplicationLoadBalancer's loadBalancerDnsName: string property is one of those properties whose value resolves to a string Token placeholder at synth-time and an actual value at deploy-time.

Here's an example of passing the loadBalancerDnsName between constructs:

export class AlbStack extends cdk.Stack {
  constructor(scope: Construct, id: string, props: cdk.StackProps) {
    super(scope, id, props);

    const alb = new elb.ApplicationLoadBalancer(this, 'MyALB', {
      vpc: ec2.Vpc.fromLookup(this, 'DefaultVpc', { isDefault: true }),
    });

    // WON'T WORK: at synth-time, the name attribute returns a Token, not the expected DNS name
    console.log(alb.loadBalancerDnsName); // ${Token[TOKEN.220]}

    // WILL WORK - CDK will wire up the token in CloudFormation as
    new ssm.StringParameter(this, 'MyAlbDns', {
      stringValue: alb.loadBalancerDnsName,
    });
  }
}

The CDK's CloudFormation template output has Fn::GetAtt placeholder for the DNS name that resolves at deploy-time:

// CDK CloudFormation stack template
// Resources section
"MyAlbDnsFD44EB27": {
  "Type": "AWS::SSM::Parameter",
  "Properties": {
    "Type": "String",
    "Value": { "Fn::GetAtt": [ "MyALB911A8556", "DNSName" ] }  // this will resolve to the string at deploy
  },
  "Metadata": {
    "aws:cdk:path": "TsCdkPlaygroundAlbStack/MyAlbDns/Resource"
  }
},
fedonev
  • 20,327
  • 2
  • 25
  • 34