'Invalidate Cloudfront cache with AWS CDK Pipelines

As part of my CodePipeline in CDK I would like, as the last step, to invalidate the Cloudfront cache.

This is my current Deploy action step:

{
  stageName: 'Deploy',
  actions: [
    new codepipelineActions.S3DeployAction({
      actionName: 'S3Deploy',
      bucket: frontendCodeBucket, // See bucket config below
      input: buildOutput, // Output from Build step
    }),
  ]
}

And here is my code bucket and CF distribution:

const frontendCodeBucket = new s3.Bucket(this, 'FrontendBucketStaging', {
  websiteIndexDocument: 'index.html',
  encryption: s3.BucketEncryption.S3_MANAGED,
  blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL,
  bucketName: 'something',
  removalPolicy: RemovalPolicy.DESTROY,
});


const distribution = new cloudfront.CloudFrontWebDistribution(this, 'FrontendCloudfrontStaging', {
  originConfigs: [
    {
      s3OriginSource: {
        s3BucketSource: frontendCodeBucket,
        originAccessIdentity: oai,
      },
      behaviors : [ {isDefaultBehavior: true}]
    }
  ],

I can't find any way to invalidate the cache through S3DeployAction. It seems like one of the most common thing one would want to do when working with a static website and Cloudfront. Is it simply just not possible?

If it's not. Is there a workaround? For example, in a non pipeline-process, something like this should work (what I've read):

new s3deploy.BucketDeployment(this, 'DeployWithInvalidation', {
  sources: [<some assets>],
  destinationBucket: bucket,
  distribution,
  distributionPaths: ['/*'],
});

Is there then a way to add such a step in the pipeline, that is not an "Action"?

Very happy for any help or pointers. I'm quite new to CDK, but this just felt like such a common thing that someone would want to do, so I hope I'm just missing something here. Apart from this last step, the pipeline works great.



Solution 1:[1]

I ended up adding another CodeBuildAction step after the S3DeployAction with the sole purpose of running this AWS CLI command:

aws cloudfront create-invalidation --distribution-id ${CLOUDFRONT_ID} --paths "/*"

Maybe not the prettiest solution, but it works :) It would be nice if invalidation would be an option in S3DeployAction though

Reference: https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_codepipeline_actions-readme.html#invalidating-the-cloudfront-cache-when-deploying-to-s3

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 papiro