Kavin404
Kavin404

Reputation: 1029

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?

Upvotes: 11

Views: 12333

Answers (2)

Megan
Megan

Reputation: 1

Here is an example of clearing cloudfronts' cache. The command runs every time you perform a terraform apply.

resource "null_resource" "run_command" {
  # Optional: define triggers to ensure this command runs
  # when certain conditions change, for example:
  triggers = {
    run_id = timestamp()
  }

  provisioner "local-exec" {
    command = "aws cloudfront create-invalidation --distribution-id ${aws_cloudfront_distribution.example_distribution.id} --paths '/*'"
  }
}

Upvotes: 0

Ermiya Eskandary
Ermiya Eskandary

Reputation: 23702

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 '...'"
  }
}

Upvotes: 16

Related Questions