2
0

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 1 year has passed since last update.

CloudFront関数をTerraformで管理しよう

Last updated at Posted at 2023-08-25

経緯

上記記事に有るように、末尾が「/」や「.」で終わるURIの時にリロードを行うと、空のフォルダをダウンロードしてしまう不具合があった。
それを解決する手段として擬似的に「inde.html」を付与する関数を作成。

従来はCloudFrontの関数に直接書き込んでいたが、それをTerraformで管理することになった。

CloudFront関数をTerraformで管理しよう

CloudFrontの関数をTerraformを使用して管理する方法を紹介します。具体的には、URLの末尾が / もしくは . で終わる場合に、index.html を追加してダウンロードを制御する関数をテラフォームで設定する方法を解説します。

CloudFront関数の設定

まず、CloudFrontで現在使用している関数を確認します。以下は、hogehoge.js という名前の関数の一例です。

function handler(event) {
    var request = event.request;
    var uri = request.uri;

    if (uri.endsWith('/')) {
        request.uri += 'index.html';
    } else if (!uri.includes('.')) {
        request.uri += '/index.html';
    }

    return request;
}

この関数は、URLの最後が / で終わる場合やファイル拡張子が含まれない場合に、リクエストされたURIに index.html を追加します。

Terraformでの設定

以下は、上記の関数をTerraformで管理する方法を示したコード例です。

resource "aws_cloudfront_function" "example" {
  name    = "example"
  runtime = "cloudfront-js-1.0"
  comment = "example function"
  publish = true
  code    = file("hogehoge.js")
}

resource "aws_cloudfront_distribution" "example" {
  # ... 他の設定 ...

  # function_association is also supported by default_cache_behavior
  default_cache_behavior {
  # ... 他の設定 ...

    function_association {
      # specific event_type viewer-request or viewer-response
      event_type   = "viewer-request"
      function_arn = aws_cloudfront_function.example.arn
    }
  }
}

このコードは、CloudFront関数をTerraformで定義する例です。関数は aws_cloudfront_function リソースで定義されており、関数のコードはファイル hogehoge.js から読み込まれます。

参考文献

2
0
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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?