Skip to content

Instantly share code, notes, and snippets.

@lucasjhall
Forked from claylo/cf-invalidate.php
Last active November 21, 2018 01:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lucasjhall/9e900e6436ac1b31a76f77f5b3ee2ad2 to your computer and use it in GitHub Desktop.
Save lucasjhall/9e900e6436ac1b31a76f77f5b3ee2ad2 to your computer and use it in GitHub Desktop.
How to invalidate items in AWS CloudFront
<?php
/**
* Super-simple AWS CloudFront Invalidation Script
*
* Steps:
* 1. Set your AWS access_key in gitlab CI/CD
* 2. Set your AWS secret_key in gitlab CI/CD
* 3. Set your CloudFront DISTRIBUTION_ID in gitlab CI/CD
* 4. Define the batch of paths to invalidate
* 5. Run it on the command-line with: php invalidate-cloudfront.php $AWS_ACCESS_KEY_ID $AWS_SECRET_ACCESS_KEY $DISTRIBUTION_ID
*
*/
date_default_timezone_set('America/Los_Angeles');
$access_key = $argv[1];
$secret_key = $argv[2];
$distribution = $argv[3];
$epoch = date('U');
$xml = <<<EOD
<InvalidationBatch>
<Path>/manifests/*</Path>
<Path>/catalogs/*</Path>
<CallerReference>{$distribution}{$epoch}</CallerReference>
</InvalidationBatch>
EOD;
/**
* You probably don't need to change anything below here.
*/
$len = strlen($xml);
$date = gmdate('D, d M Y G:i:s T');
$sig = base64_encode(
hash_hmac('sha1', $date, $secret_key, true)
);
$msg = "POST /2010-11-01/distribution/{$distribution}/invalidation HTTP/1.0\r\n";
$msg .= "Host: cloudfront.amazonaws.com\r\n";
$msg .= "Date: {$date}\r\n";
$msg .= "Content-Type: text/xml; charset=UTF-8\r\n";
$msg .= "Authorization: AWS {$access_key}:{$sig}\r\n";
$msg .= "Content-Length: {$len}\r\n\r\n";
$msg .= $xml;
$fp = fsockopen('ssl://cloudfront.amazonaws.com', 443,
$errno, $errstr, 30
);
if (!$fp) {
die("Connection failed: {$errno} {$errstr}\n");
}
fwrite($fp, $msg);
$resp = '';
while(! feof($fp)) {
$resp .= fgets($fp, 1024);
}
fclose($fp);
echo $resp;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment