Waiting on AWS CloudFront Invalidations

1 minute read

Lately, we’ve been playing with AWS and waiting around - let’s combine the two.

CloudFront is AWS’ CDN. As with any CDN (or any cache for that matter), sometimes you need to clear it in a hurry. In CloudFront, this is don’t with an invalidation and “a hurry” means about 15 minutes. More waiting. The AWS console give you a spinner, but who wants to stare at that? If you have the AWS CLI installed, you can get the status of an invalidation using the aws cloudfront get-invalidation command.

wait-for-invalidation() {
    until aws cloudfront get-invalidation --id $1 --distribution-id $2 | grep -q Completed; do sleep 30; done
    notify "Invalidation $1 completed";
}

It takes two arguments, the ID of the invalidation and the ID of the CloudFront distribution. You could get fancier and create the invalidation from the CLI as well, but I usually do it in the GUI, cut and pasting the IDs.

One refinement from my ping and Netcat wait functions, I’m using until. until is identical to while !, but makes your intentions clearer. I simply didn’t know about it when I developed my earlier functions.

The above approach works fine, the AWS CLI actually provides an easier way to wait, the wait command. However, it’s in beta and before you can use it you need to enable it with:

aws configure set preview.cloudfront true

You call it thusly:

aws cloudfront wait invalidation-completed --id XXXXXXXXXXXXXX --distribution-id XXXXXXXXXXXXX

Which lets us rewrite the function as:

wait-for-invalidation() {
    aws cloudfront wait invalidation-completed --id $1 --distribution-id $2 && notify "Invalidation $1 completed";
}

Since the AWS command does the waiting for us, this version of the function doesn’t need a loop. && will execute the notification function only if the wait exits without an error. If the wait exits with an error, say an invalid ID the && insures that the doesn’t fire.

Now, if you wanted to be really cool, you could start the invalidation from the command line, capture the invalidation ID and fire up the wait automatically. But I’m too lazy. If you’re not, share it in the comments.

Comments