AWS CDK: enabling access logging for classical load balancer

Viewed 960

We are using Classical load balancer in our Infra deployed via CDK. For deploying Load balancer we are using level 2 Constructs. The code is like this:

const lb = new elb.LoadBalancer(this, 'LB', {
            vpc: vpcRef,
            
            internetFacing: true,
            healthCheck: {
                port: 80
            },
        
        });
        
        
        lb.addListener({
            externalPort: 80,
        });
    }

We are not able to find any property using which we can enable the access logging. Someone suggested me to use AccessLoggingPolicyProperty. I checked that and found that this property can be used with Level 1 constructs only. Can some please guide me on how we can enable the access logs via CDK on a classical load balancer using Level 2 constructs.

1 Answers

As per the documentation you need S3 bucket with right permissions configured. With that you can follow aws-cdk documentation on how to get access to L1 Construct.

It is going to look roughly like the following code

const lbLogs = new Bucket(this, 'LB Logs');

const elbAccountId = 'TODO: find right account for you region in docs';

lbLogs.grantPut(new AccountPrincipal(elbAccountId));

lbLogs.grantPut(
  new ServicePrincipal('delivery.logs.amazonaws.com', {
    conditions: {
      StringEquals: {
        's3:x-amz-acl': 'bucket-owner-full-control',
      },
    },
  })
);

lbLogs.grantRead(new ServicePrincipal('delivery.logs.amazonaws.com'));

const cfnLoadBalancer = lb.node.defaultChild as CfnLoadBalancer;
cfnLoadBalancer.accessLoggingPolicy = {
  enabled: true,
  s3BucketName: lbLogs.bucketName,
};
Related