Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

概要

  • メモ
  • 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}' } } }

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

参考

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした