ツナワタリマイライフ

日常ネタから技術ネタ、音楽ネタまで何でも書きます。

AWS S3上の静的コンテンツをCircleCIでdeploy時にCloudFrontのキャッシュを削除する

はじめに

以前、S3上の静的コンテンツを独自ドメインで公開ということでバンドのHPを2つほど作りました。

take-she12.hatenablog.com

take-she12.hatenablog.com

で、CloudFrontのcacheはデフォルトのままなので24時間有効。そのためHPを更新しても最大24時間更新されないんですね。最初は別にいいかと思っていたんですが、ローカルでテストしているとはいえ本番デプロイまで見届けたいということと、更新後の告知まで一緒にやってしまいたいと思ったので、自動でキャッシュを削除させました。

tl;dr

- aws configure set preview.cloudfront true
- aws cloudfront create-invalidation --distribution-id <your-distribution-id> --paths '/*'

詰まった点

検索のためにエラーログを残しておきます。

まず最初にcreate-invalidationだけ実施すると設定が足りませんよーと怒られました。

aws cloudfront create-invalidation --distribution-id <my-distribution-id> --paths '/*'
AWS CLI support for this service is only available in a preview stage.

However, if you'd like to use the "aws cloudfront" commands with the
AWS CLI, you can enable this service by adding the following to your CLI
config file:

    [preview]
    cloudfront=true

or by running:

    aws configure set preview.cloudfront true


aws cloudfront create-invalidation --distribution-id <my-distribution-id> --paths '/*' returned exit code 1

Action failed: aws cloudfront create-invalidation --distribution-id <my-distribution-id> --paths '/*'

そうですかと1行追加しましたが、公式リファレンスにある通り、aws-cliでcloudfrontの操作はまだpreview版なんですね。

cloudfront — AWS CLI 1.11.83 Command Reference

そうして1行追加すると権限がないぞと怒られる

aws cloudfront create-invalidation --distribution-id <my-distribution-id> --paths '/*'

An error occurred (AccessDenied) when calling the CreateInvalidation operation: User: arn:aws:iam::<my-iam-user> is not authorized to perform: cloudfront:CreateInvalidation

aws cloudfront create-invalidation --distribution-id <my-distribution-id> --paths '/*' returned exit code 255

Action failed: aws cloudfront create-invalidation --distribution-id <my-distribution-id> --paths '/*'

ユーザにcloudfront:CreateInvalidationの権限がないぞと。そういえばS3へのフルアクセスしか与えてなかったので、CloudFrontへのアクセス権を与えてあげればOKでした。

f:id:take_she12:20170506175630p:plain

おわりに

緊急性のないHPとはいえ、その後の告知をわざわざ24時間待って確認してからするのはイケてないので、これを機にcache削除まで組み込めてよかったです。はじめからやっておけばよかったな。