aws-cdk 将 Lambda 函数与 CloudFront Web 分配相关联

aws-cdk Associate Lambda Function with CloudFront Web Distribution

我正在尝试使用 aws-cdk 创建 CloudFront Web 分发。我能够成功创建网络分发,但我还没有弄清楚如何关联 lambda 函数。

下面是我的 Typescript aws-cdk 代码片段,用于创建 CloudFront Web 分发。我删除了一些不相关的代码。

new cloudfront.CloudFrontWebDistribution(this, 'RetsFilesCDN', {
        originConfigs: [
            {
                s3OriginSource: {
                    originAccessIdentity: cfAccess, /* A CfnCloudFrontOriginAccessIdentity object created in earlier code */
                    s3BucketSource: files /* S3 bucket created in earlier code */
                },
                behaviors: [
                    {
                        compress: true,
                        defaultTtlSeconds: 172800,
                        isDefaultBehavior: true,
                        maxTtlSeconds: 31536000,
                        minTtlSeconds: 0
                    }
                ]
            }
        ]
    });

我试图让它生成的 CloudFormation 代码是这样的:

RetsFilesCDNCFDistribution6F414E1A:
Type: AWS::CloudFront::Distribution
Properties:
  DistributionConfig:
    CacheBehaviors:
      []
    Comment: CDN for files from the Real Estate RETS services that BranchCMS
      integrates with
    DefaultCacheBehavior:
      AllowedMethods:
        - GET
        - HEAD
      CachedMethods:
        - GET
        - HEAD
      Compress: true
      DefaultTTL: 172800
      ForwardedValues:
        Cookies:
          Forward: none
        QueryString: false
      MaxTTL: 259200
      MinTTL: 172800
      LambdaFunctionAssociations:
        - EventType: origin-response
          LambdaFunctionARN: lambdaFunctionArnHere
      TargetOriginId: origin1
      ViewerProtocolPolicy: redirect-to-https
    DefaultRootObject: index.html
    Enabled: true
    HttpVersion: http2
    IPV6Enabled: true
    Origins:
      - DomainName:
          Fn::GetAtt:
            - RetsFilesC9F78E92
            - DomainName
        Id: origin1
        S3OriginConfig:
          OriginAccessIdentity:
            Fn::Join:
              - ""
              - - origin-access-identity/cloudfront/
                - Ref: RetsFilesAccess
    PriceClass: PriceClass_100
    ViewerCertificate:
      AcmCertificateArn: arn:aws:acm:us-east-1:666445282096:certificate/25d4967c-c29a-4d11-983f-86d709769372
      SslSupportMethod: sni-only

我似乎无法生成的确切部分是:

LambdaFunctionAssociations:
   - EventType: origin-response
     LambdaFunctionARN: lambdaFunctionArnHere

预先感谢您的帮助。

您可以使用此 属性 将 lambda 函数关联到您的云端缓存行为

import { CfnDistribution.CacheBehaviorProperty } from '@aws-cdk/aws-cloudfront';
CfnDistribution.CacheBehaviorProperty.LambdaFunctionAssociations

for more information click on this link

我不确定这是否是最好的技术,但以下方法对我有用。

import cdk = require('@aws-cdk/cdk');
import cloudfront = require('@aws-cdk/aws-cloudfront');
import lambda = require('@aws-cdk/aws-lambda');


export class MyStack extends cdk.Stack {
    constructor(parent: cdk.App, name: string, props?: cdk.StackProps) {
        super(parent, name, props);

        // Create the Lambda function
        const lambdaFunc = new lambda.Function(this, 'MyLambda', {
             YOUR_LAMBDA_PROPERTIES: HERE
        });

        // Create the CloudFront Web Distribution
        const cf = new cloudfront.CloudFrontWebDistribution(this, 'MyCDN', {
            YOUR_CLOUDFRONT_PROPERTIES: HERE
        });

        /**
         * THIS IS THE BEGINNING OF THE SOLUTION
         */

        // Get the CloudFront Distribution object to add the LambdaFunctionAssociations to
        const cfDist = cf.findChild('CFDistribution') as cloudfront.CfnDistribution;

        // Manually add the LambdaFunctionAssociations by adding an override
        cfDist.addOverride('Properties.DistributionConfig.DefaultCacheBehavior.LambdaFunctionAssociations', [{
            EventType: 'origin-response',
            LambdaFunctionARN: lambdaFunc.functionArn + ':2'
        }]);

        /**
         * END OF SOLUTION
         */ 
    }
}

是否可以将新创建​​的函数(lamda@edge / cloudfront 函数)与现有的 cloudfront 分布相关联? 上面的代码似乎只适用于新创建的发行版。