How to create a CloudFront invalidation Request?
To create an Invalidation request you need to create an InvalidationRequest Object with the explained parameters and sent it with your cloudfrontClient to aws cloudfront.
Bellow i have an example for invalidating cloudfront cache in c# .net 6, but the code will work pretty much the same for other programming languages and frameworks. Just see the official docs for the different speciffications.
parameters for the invalidation request
InvalidationBatch: content to invalidate
CallerReference: some unique ID, i use the actual time.
Path: the files you want to invalidate, the name would be the same like when accessing from cloudfront.
DistributionID: your Cloudfront DistributionId
string imageToInvalidate = <image name>;
var client = new AmazonCloudFrontClient(accessKey,
accessSecret,
Amazon.RegionEndpoint.EUCentral1);
var result = await client.CreateInvalidationAsync(new CreateInvalidationRequest
{
DistributionId = cloudfrontDistributionId,
InvalidationBatch = new InvalidationBatch
{
Paths = new Paths
{
Quantity = 1,
Items = new System.Collections.Generic.List<string>
{ imageToInvalidate }
},
CallerReference = DateTime.Now.Ticks.ToString()
}
});
}
If everything went fine you will get a System.Net.HttpStatusCode.Created inside your request, otherwise, an exception will be thrown.
You can also see that an invalidation has been performed inside your CloudFront dashboard.
Troubleshooting
Amazon.CloudFront.Model.AccessDeniedException:
Mostly because your API user has no or insufficient access to CloudFront.
You can find out the CloudFront user in the exception details
Go to IAM/Users and add cloudFrontFullAccess to the IAM your API is using.
Conclusion
I hope I could provide you with some value with this article and helped you to clear your cache!. If you want to support me and the work I´m doing you can buy me a coffee. I will donate half of it to Ukraine.
Happy clearing,
Alex
sources:
https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_CreateInvalidation.htmlhttps://stackoverflow.com/questions/22021651/amazon-s3-and-cloudfront-cache-how-to-clear-cache-or-synchronize-their-cachehttps://stackoverflow.com/questions/3632785/amazon-cloudfront-invalidation-in-asp-net