Skip to content

Instantly share code, notes, and snippets.

@claylo
Created June 5, 2011 17:09
Show Gist options
  • Save claylo/1009169 to your computer and use it in GitHub Desktop.
Save claylo/1009169 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
* 2. Set your AWS secret_key
* 3. Set your CloudFront Distribution ID
* 4. Define the batch of paths to invalidate
* 5. Run it on the command-line with: php cf-invalidate.php
*
* The author disclaims copyright to this source code.
*
* Details on what's happening here are in the CloudFront docs:
* http://docs.amazonwebservices.com/AmazonCloudFront/latest/DeveloperGuide/Invalidation.html
*
*/
$access_key = 'AWS_ACCESS_KEY';
$secret_key = 'AWS_SECRET_KEY';
$distribution = 'DISTRIBUTION_ID';
$epoch = date('U');
$xml = <<<EOD
<InvalidationBatch>
<Path>/index.html</Path>
<Path>/blog/index.html</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;
@ZE3kr
Copy link

ZE3kr commented Jan 28, 2017

Cool things! AWS SDK is too big and complex and I already give it up.

@Resvina
Copy link

Resvina commented Mar 31, 2017

Need help!

We are ruby bashed env. I'm looking for a bash script to do invalidation without having to use awscli. is there anything available?

Thanks,
Resvina

@jamescridland
Copy link

Suggest you use $epoch = date('Uu'); rather than $epoch = date('U'); - it adds microseconds, and means that if you're sending two invalidations in quick succession, one of them won't randomly break.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment