如何使用 CDK 将现有 OAI 重新用于 CloudFront 分发

How to re-use existing OAI for CloudFront distribution using CDK

如何阻止 CDK 在我每次创建新的 CloudFront 分配时创建新的 OAI?

我想对所有发行版使用 XXXXXXXXXXXXX1,但创建了 XXXXXXXXXXXXX2,不知道为什么,因为我明确表示要使用另一个发行版:cloudfront.OriginAccessIdentity(this, "XXXXXXXXXXXXX1")

这是我使用 TypeScript 的 CDK 堆栈

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",
    })
  }
}

这是所写的预期行为。 new cloudfront.OriginAccessIdentity(this, "XXXXXXXXXXXXX1") 为部署的每个堆栈实例创建一个新的 OAI。 second parameter is the CDK id,不是 OAI id。

要获取对在 CDK 应用程序之外创建的现有 OAI 的 read-only 引用,请使用静态 OriginAccessIdentity.fromOriginAccessIdentityName 方法,将 "XXXXXXXXXXXXX1" 作为第三个参数传递。