amazon-web-servicesterraformamazon-cloudfrontterraform-provider-aws

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?


Solution

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