2
0

AWS CDKでCloudfront - Lambda FunctionURLsのOACを定義する

Last updated at Posted at 2024-08-01

以前の記事

TL;DR

import * as iam from 'aws-cdk-lib/aws-iam';
import * as cloudfront from 'aws-cdk-lib/aws-cloudfront';
import * as lambda from 'aws-cdk-lib/aws-lambda';

// 以下のようなリソースが定義されているとして(当然このままでは動かない)
const distribution = new cloudfront.Distribution({hoge:fuga});
const lambdaFunc = new lambda.DockerImageFunction({{hoge:fuga}};
const funcUrl = lambdaFunc.addFunctionUrl({
    authType: lambda.FunctionUrlAuthType.AWS_IAM
});

// Cfn Constructを参照
const cfnDistribution = distribution.node.defaultChild as cloudfront.CfnDistribution;

// OAC設定: Cloudfront側
const cfnOriginAccessControl = new cloudfront.CfnOriginAccessControl(
    this,
    'OriginAccessControl',
    {
        originAccessControlConfig: {
            name: 'oac-lambda',
            originAccessControlOriginType: 'lambda',
            signingBehavior: 'always',
            signingProtocol: 'sigv4',
            description: 'Access Control'
        }
    }
);
cfnDistribution.addPropertyOverride(
    // CloudfrontのオリジンにFunction Urlが設定されていて、0=lambdaの場合
    'DistributionConfig.Origins.0.OriginAccessControlId',
    cfnOriginAccessControl.attrId
);

// OAC設定: Lambda側
lambdaFunc.addPermission('allowCf', {
    action: 'lambda:InvokeFunctionUrl',
    principal: new iam.ServicePrincipal('cloudfront.amazonaws.com'),
    sourceArn: `arn:aws:cloudfront::${this.account}:distribution/${distribution.distributionId}`
});

参考

L2 ConstructではOACは未実装で、2022年からIssueが立っている。we are actively workingというコントリビュータがおられるので、そのうちもっと簡素に書けるようになるかもしれない。

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0