4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JavaScriptでAWS CloudFrontのキャッシュを削除(Invalidate)する

Last updated at Posted at 2017-12-07

概要

  • メモ
  • AWS-SDKを利用(初めて使った)

コード

package.json
{
    "dependencies": {
        "aws-sdk": ">= 2.0.9",
        "node-uuid": ">= 1.4.1"
    }
}

これでnpm install

実際にキャッシュをinvalidateするJavaScriptは以下

invalidate.js
// Load the SDK and UUID
var AWS = require('aws-sdk');
var uuid = require('node-uuid');

var cloudfront = new AWS.CloudFront({
    apiVersion: '2017-03-25',
    accessKeyId: YOUR_AWS_ACCESS_KEY,
    secretAccessKey: YOUR_AWS_SECRET_KEY,
});

var timestamp = new Date();
var string_timestamp = String(timestamp.getTime());

var invalidate_items = ['/* Subject to invalidate */',];
var item_count = invalidate_items.length

var params = {
  DistributionId: YOUR_CLOUDFRONT_ID,
  InvalidationBatch: {
    CallerReference: string_timestamp,
    Paths: {
      Quantity: item_count,
      Items: invalidate_items
    }
  }
};

cloudfront.createInvalidation(params, function(err, data) {
  if (err) console.log(err, err.stack);
  else     console.log(data);
});

invalidate_itemというリストにキャッシュを削除したい対象(エンドポイント)を格納し、parmsのItemsに渡す
キャッシュ削除対象の個数をitem_countに渡して、それをparamsのQuantityに渡す
accessKeyId、secretAccessKey、DistributionIdについてはそれぞれ自分の環境のやつを入れる
あと、apiVersionについては2017年12月現在のものです

とりあえず、これで node invalidate.js すればcloud frontへキャッシュ削除してくれる
結果はこんな感じで返ってくる

{ Location: 'https://cloudfront.amazonaws.com/2017-03-25/distribution/{YOUR_CLOUDFRONT_ID}/invalidation/{invalidation_id}',
  Invalidation: 
   { Id: '{invalidation_id}',
     Status: 'InProgress',
     CreateTime: 2017-12-06T04:40:16.628Z,
     InvalidationBatch: { Paths: [Object], CallerReference: '{string_timestamp}' } } }

まあ、これだけだと実際に運用することはできないのだけど、とりあえず、動いてよかったですね、という感じです

参考

4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?