-
-
Save claylo/1009169 to your computer and use it in GitHub Desktop.
<?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; |
Thanks for this. Can't believe they don't have this avail in the console. Couple confusing points that could use a comment: required preceding slash in path of invalidation files, and the API date in the POST. I thought it needed to be the current date. Appreciate it!
Thanks for this. It was useful
Very useful. Thank you very much!
Man... you deserve an ecological award to help me clean a ton of trash code
Cool things! AWS SDK is too big and complex and I already give it up.
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
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.
Steve, thanks for your tweak -- even more useful! Glad my script was able to give you a head start down that path. :)