0

I need to pass a configuration value from one CDK stack to another and use that value in the second stack's construct code bundling step. E.g. first stack is S3 bucket and the second stack is Lambda@Edge function which doesn't support environment variables and needs to embed S3 bucket name in code during bundling in a custom construct. When I do this I get values like ${Token[TOKEN.214]} instead of a real bucket name.

let bucket: Bucket

// This function builds and bundles the code for Lambda@Edge
buildLambdaCode(..., { env: { S3_BUCKET: bucket.bucketName } })
serega
  • 564
  • 1
  • 5
  • 14
  • How you are injecting the bucket name (=[Token](https://docs.aws.amazon.com/cdk/v2/guide/tokens.html)) into your lambda code? Please add a code snippet to the question. – fedonev Feb 16 '22 at 10:06
  • Thanks @fedonev, I've added a simplified code example. – serega Feb 16 '22 at 14:40
  • @fedonev, Reading the docs about Tokens makes me think that the real bucket name can't be known until deployment is done and thus there would be no way to use it in code bundling as it must happen during synthesis. Am I right? I referred to [these restrictions](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/edge-functions-restrictions.html#lambda-at-edge-function-restrictions) of lambda@edge. I need to check the API again. Thanks for the hint! – serega Feb 16 '22 at 14:46

1 Answers1

1

Indeed, CDK-generated resource names are Tokens at code-time, CloudFormation Refs at synth-time, and "actual names" only at deploy-time. So your options to pass the bucket name to your Lambda@Edge are:

  1. Environment Variable: the default solution, but Lambda@Edge does not support them*, as you say.
  2. SSM Parameter + SDK Call: another typical solution, but the added latency defeats the purpose of the edge function.
  3. CloudFront Custom Header: as in this SO Question. You can set customHeaders in CDK Cloudfront Origin constructs.
  4. Hardcode the Bucket Name: the best-practice gods may forgive you setting an explicit bucketName in this case.

* The experimental cloudfront.experimental.EdgeFunction construct dangerously permits env var props (error or ignored at deploy?). The stable cloudfront.Function does not, in line with the service docs.

fedonev
  • 20,327
  • 2
  • 25
  • 34
  • Thanks for the custom headers suggestion, that is a clever hack. And good to know about SSM pitfall. – serega Feb 16 '22 at 20:47