Skip to content

Invalidate (re-cache) Content on AWS CloudFront

This is a handy script I use to invalidate (re-cache) content on AWS’s CloudFront.

using System;
using System.Collections.Generic;
using System.Configuration;
using Amazon;
using Amazon.CloudFront.Model;
using Amazon.S3.Model;

namespace AwsConsoleApp1
{
  internal class Program
  {
    /// <summary>
    /// Invalidates only one file. e.g. /images/profile.gif
    /// </summary>
    /// 
    public static void InvalidateFiles(string file)
    {
      InvalidateFiles(new List() { file });
    }

    /// <summary>
    /// Invalidates only one file. Enter bucket name and key (file in the bucket).
    /// </summary>
    /// 
    /// 
    public static void InvalidateFiles(string bucket, string key)
    {
      InvalidateFiles(new List() { bucket + "/" + key });
    }

    /// <summary>
    /// Invalidates a list of files. e.g. /images/profile.gif, /home/index.html
    /// </summary>
    /// 
    public static void InvalidateFiles(List files)
    {
      // AWS client. You always create one.
      var cfClient = AWSClientFactory.CreateAmazonCloudFrontClient();

      // Create paths to files we want to invalidate
      Paths invalidationPaths = new Paths();
      // invalidationPaths.Items = new List() { "/images/dan1g.zip" };
      invalidationPaths.Items = files;
      invalidationPaths.Quantity = invalidationPaths.Items.Count;

      // Now... let's build the request...
      CreateInvalidationRequest invalidationRequest = new CreateInvalidationRequest();
      invalidationRequest.DistributionId = ConfigurationManager.AppSettings["DistributionID"];

      // ... and other required paramaters
      invalidationRequest.InvalidationBatch = new InvalidationBatch();
      invalidationRequest.InvalidationBatch.Paths = invalidationPaths;
      invalidationRequest.InvalidationBatch.CallerReference = Guid.NewGuid().ToString();

      // Execute the request and get back a response object.
      CreateInvalidationResponse response = cfClient.CreateInvalidation(invalidationRequest);

      // Starting
      System.Console.WriteLine("Initiated On: " + response.CreateInvalidationResult.Invalidation.CreateTime);
      System.Console.WriteLine("InvalidationID: " + response.CreateInvalidationResult.Invalidation.Id);
      System.Console.WriteLine("Status: " + response.CreateInvalidationResult.Invalidation.Status);
    }

    /// <summary>
    /// Check if a file exists on S3.
    /// </summary>
    /// 
    /// 
    /// 
    public static bool IsFileInBucket(string bucket = "", string key = "")
    {
      bool exist = true;
      var s3Client = AWSClientFactory.CreateAmazonS3Client();
      try
      {
        GetObjectResponse oResponse = s3Client.GetObject(new GetObjectRequest() { BucketName = bucket, Key = key });       
      }
      catch (Exception e)
      {
        Console.WriteLine("\n" + e.Message);
        exist = false;
      }

      return exist;
    }

    /// <summary>
    /// Main Caller.
    /// </summary>
    /// 
    public static void Main(string[] args)
    {
      if (args.Length == 2)
      {
        string bucketName = args[0];
        string key = args[1];

        if (args != null &amp;&amp; IsFileInBucket(bucketName, key))
        {
          InvalidateFiles(bucketName, key);
        }
        else
        {
          Console.WriteLine("\n\nDone.");
        }
      }
      else
      {
        Console.WriteLine("\nUse:\n   S3-Invalidate BUCKETNAME KEY\n\ne.g.\n   S3-Invalidate images photo.gif\n");
      }

      // Console.ReadKey();
    }
  }
}

Categories

ASP.NET MVC, C#

Dan View All

Blog owner.

%d bloggers like this: