Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I invalidate AWS CloudFront Distribution cache using Terraform?

I am looking for a way to invalidate the CloudFront distribution cache using Terraform.

I could not find any information in the docs.

Is this possible and if so, how?

like image 545
Kavin404 Avatar asked Mar 10 '26 22:03

Kavin404


1 Answers

There is no in-built support within the aws_cloudfront_distribution or aws_cloudfront_cache_policy resource for cache invalidation.

As a last resort, the local_exec provisioner can be used.


Typically, from my experience, the cache is invalidated within the CI/CD pipeline using the AWS CLI create-invalidation command.

However, if this must be done within Terraform, you can use the local-exec provisioner to run commands on the local machine running Terraform after the resource has been created/updated.

We can use this to run the above CLI invalidation command to invalidate the distribution cache.

Use the self object to access all of the CloudFront distribution's attributes, including self.id to reference the CloudFront distribution ID for the invalidation


Example:

resource "aws_cloudfront_distribution" "s3_distribution" {
  # ...

  provisioner "local-exec" {
    command = "aws cloudfront create-invalidation --distribution-id ${self.id} --paths '...'"
  }
}
like image 89
Ermiya Eskandary Avatar answered Mar 12 '26 16:03

Ermiya Eskandary



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!