Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
2
Help us understand the problem. What are the problem?

More than 3 years have passed since last update.

@xKxAxKx

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

概要

  • メモ
  • 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
2
Help us understand the problem. What are the problem?