Invalidating AWS Cloudfront cache using Octopus Deploy

AWS + Octopus Deploy

I recently wrote how we submitted our first Octopus Deploy template to their online library for deploying .Net web apps to AWS Elastic Beanstalk using Octopus Deploy.

This time we needed to automate AWS Cloudfront cache invalidation. Turns out there are a few different ways to achieve this. You can either do it from the AWS console, by making a REST request or by using the AWS CLI tool.

Since authenticating against the AWS REST API is a bit more complex than we feel is necessary for the purpose of using it within an Octopus Deploy step, we decided to go with the AWS CLI approach (it's much easier to authenticate).

One more GitHub pull request and one more Octopus Deploy step template in their library in hope it might find someone in need. :)

The PowerShell script that does the hard work in the background of the template is the following (just fill in the AWS configuration variables): 

# AWS credentials profile name (should be unique)
# Used to store your AWS credentials to: ~/.aws/
$CredentialsProfileName = ""

# AWS CLoudfront Region
$Region = ""

# AWS Cloudfront Distribution Id
$DistributionId = ""

# AWS Access Key
$AccessKey = ""

# AWS Secret Key
$SecretKey = ""

# Space-delimited list of paths to invalidate.
# For example: /index.html /images/*
$InvalidationPaths = ""

Write-Host "Setting up AWS profile environment"
aws configure set aws_access_key_id $AccessKey --profile $CredentialsProfileName
aws configure set aws_secret_access_key $SecretKey --profile $CredentialsProfileName
aws configure set default.region $Region --profile $CredentialsProfileName
aws configure set preview.cloudfront true --profile $CredentialsProfileName

Write-Host "Initiating AWS cloudfront invalidation of the following paths:"
Write-Host $InvalidationPaths
aws cloudfront create-invalidation --profile $CredentialsProfileName --distribution-id $DistributionId --paths $InvalidationPaths

Write-Host "Please note that it may take up to 15-20 minutes for AWS to complete the cloudfront cache invalidation"

The script uses profile setup for AWS credentials. If you don't want to use the profiles, you can just remove that bits from the script but then you might have to re-setup credentials for a different project every time.