How to grant s3 access to cloudfront using the CDK?

0

I'm confused within the CDK how I can set up CloudFront only permissions on an S3 bucket. I crated the bucket, with publicReadAccess: false then am trying to grant cloudformation permissions like this:

import * as s3 from "aws-cdk-lib/aws-s3";
import * as cf from "aws-cdk-lib/aws-cloudfront";
import * as iam from "aws-cdk-lib/aws-iam";

export function grantCloudFrontAccessToBucket(stack: cdk.Stack, cfInstance: cf.CloudFrontWebDistribution, bucket: s3.Bucket) {
    const bucketObjects = `${bucket.bucketArn}:*`;
    const cfArn =`arn:aws:cloudfront::${stack.account}:distribution/${cfInstance.distributionId}`;

    const policy = new iam.PolicyStatement({
            actions: ["s3:GetObject"],
            resources: [bucketObjects],
            principals: [
                new iam.ServicePrincipal('cloudfront.amazonaws.com')
            ],
            conditions: [
                {
                    "StringEquals": {
                        "AWS:SourceArn": cfArn
                    }
                }
            ]
        });

    bucket.addToResourcePolicy(policy);
}

It complains that it is an invalid condition type, but I think StringEquals should be okay? The only other thing I can think of is I built the ARNs wrong?

Update: I found This Article that explains how to do what I was trying to do using OIN. But, the console help seems to suggest OAC is better. Can you use OAC in a similar way from the CDK?

profile picture
wz2b
질문됨 일 년 전4084회 조회
2개 답변
0
수락된 답변

I'm closing this for now. I settled on just using the old way first until the CDK catches up.

const oin = new OriginAccessIdentity(stack, 'washnet-cf-origin-access-identity');
sourceBucket.grantRead(oin);

then in the cloudfront config:

s3OriginSource: {
    s3BucketSource: source,
    originAccessIdentity: oin
},

Good enough for now.

profile picture
wz2b
답변함 일 년 전
0

The policy statement syntax is wrong: conditions is not a list. Annoyingly IDEs do not catch this error. Try:

conditions: { StringEquals: { "AWS:SourceArn": `arn:aws:cloudfront::${this.account}:distribution/${distribution.distributionId}` } }
MarkusR
답변함 5달 전

로그인하지 않았습니다. 로그인해야 답변을 게시할 수 있습니다.

좋은 답변은 질문에 명확하게 답하고 건설적인 피드백을 제공하며 질문자의 전문적인 성장을 장려합니다.

질문 답변하기에 대한 가이드라인

관련 콘텐츠