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?

2 Antworten
0
Akzeptierte Antwort

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
beantwortet vor einem Jahr
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
beantwortet vor 5 Monaten

Du bist nicht angemeldet. Anmelden um eine Antwort zu veröffentlichen.

Eine gute Antwort beantwortet die Frage klar, gibt konstruktives Feedback und fördert die berufliche Weiterentwicklung des Fragenstellers.

Richtlinien für die Beantwortung von Fragen