LoginSignup
3
2

More than 1 year has passed since last update.

CloudFront FunctionsをTerraformで書いてみた

Last updated at Posted at 2021-05-24

はじめに

awsのproviderバージョンが v3.41.0 から aws_cloudfront_function リソースがリリースされ、CloudFront FunctionsをTerrafromで管理することができました。

リリースされたので、コード化をしてみようと思います。

provider.tf
terraform {
  required_providers {
    aws = {
      source = "hashicorp/aws"
      version = "3.41.0"
    }
  }
}

前提条件

  • Terraformのバージョンは v0.13 以降であること
  • awsのproviderは v3.41.0 以降であること

Terraformコード

CloudFront FunctionsでBasic認証ができるか試してみた で書いたコードをTerraform管理します。
aws_cloudfront_function リソースでCloudFront Functionsを記載します。
現状(2021/05/24) runtimecloudfront-js-1.0 しかありません。
また、 publish = true を設定することにより、 code が変更・作成されたときにCloudFrontへ適用してくれます。

main.tf
resource "aws_cloudfront_function" "example" {
  name    = "example"
  runtime = "cloudfront-js-1.0"
  comment = "example function"
  publish = true
  code    = file("${path.module}/function.js")
}

resource "aws_cloudfront_distribution" "example" {
  # ... other configuration ...

  # function_association is also supported by default_cache_behavior
  default_cache_behavior {
    # ... other configuration ...

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

コード化してみた感想

aws_cloudfront_distribution リソースの取り回しが難しいとは思いました。

aws_cloudfront_distribution を公式ではなく自前でmodule化していると新たに default_cache_behavior or ordered_cache_behavior を追加しなければならず、
コードの大幅な変更が求められます。

現在、cache_behavioraws_cloudfront_distribution でしか変更ができないので、
コードを書いていて不便に感じました。リソースを切り出してくれないかなと思ってます。

公式のCloudFrontモジュールは良くできているので、自作するよりも公式を採用した方が良かったと反省してます。

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