Home > Software design >  How to re-use existing OAI for CloudFront distribution using CDK
How to re-use existing OAI for CloudFront distribution using CDK

Time:04-04

How can I stop CDK from creating a new OAI everytime I create a new CloudFront distribution?

I want to use XXXXXXXXXXXXX1 for all distributions, but XXXXXXXXXXXXX2 is created, not sure why because I am explicitly saying to use the other with: cloudfront.OriginAccessIdentity(this, "XXXXXXXXXXXXX1")

enter image description here

Here is my CDK stack with TypeScript

import { Construct } from "constructs"

import {
  Stack,
  StackProps,
  aws_s3 as s3,
  aws_s3_deployment as s3Deploy,
  aws_cloudfront as cloudfront,
  aws_cloudfront_origins as cloudFrontOrigins,
  aws_certificatemanager as acm,
  CfnOutput,
} from "aws-cdk-lib"

export class CdkStack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props)

    const websiteBucket = new s3.Bucket(this, "ReferenceBucket", {
      bucketName: "my-unique-bucket-name-xd",
      blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL,
    })

    new s3Deploy.BucketDeployment(this, "DeployReactApp", {
      sources: [s3Deploy.Source.asset("./deploy")],
      destinationBucket: websiteBucket,
    })

    const originAccessIdentity = new cloudfront.OriginAccessIdentity(this, "XXXXXXXXXXXXX1")

    const arn = "arn:aws:acm:us-east-1:123451234512:certificate/something-something"
    const certificate = acm.Certificate.fromCertificateArn(this, "TheCertificate", arn)

    const distribution = new cloudfront.Distribution(this, "CloudFrontDist", {
      defaultBehavior: {
        origin: new cloudFrontOrigins.S3Origin(websiteBucket, {
          originAccessIdentity: originAccessIdentity,
        }),
        allowedMethods: cloudfront.AllowedMethods.ALLOW_GET_HEAD_OPTIONS,
        viewerProtocolPolicy: cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
      },
      domainNames: ["s3.example.com"],
      certificate: certificate,
      priceClass: cloudfront.PriceClass.PRICE_CLASS_100,
      minimumProtocolVersion: cloudfront.SecurityPolicyProtocol.TLS_V1_2_2021,
    })

    new CfnOutput(this, "DistroName", {
      value: distribution.distributionDomainName,
      description: "Distribution assigned URL",
      exportName: "TheAwesomeDistro",
    })
  }
}

CodePudding user response:

This is the expected behaviour as written. new cloudfront.OriginAccessIdentity(this, "XXXXXXXXXXXXX1") creates a new OAI for each stack instance deployed. The second parameter is the CDK id, not an OAI id.

To get a read-only reference to an existing OAI created outside the CDK App, use the static OriginAccessIdentity.fromOriginAccessIdentityName method, passing "XXXXXXXXXXXXX1" as the third argument.

  • Related