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

[Terraform] terraform で CloudFront に BASIC 認証追加

Posted at

Terraform で CloudFront Functions を作って、CloudFront に BASIC 認証追加する方法。

terraform の template_file プラグインを使うと、変数を受け取って展開してくれるので便利です。

template_file.tf
variable basic_user           { default = "basic_user" }
variable basic_password       { default = "basic_password" }
variable unauthorized_message { default = "Unauthorized" }

data template_file basic_auth {
    template = file("${path.module}/function.js")

    vars = {
        basic_auth_string    = base64encode("${var.basic_user}:${var.basic_password}")
        unauthorized_message = var.unauthorized_message
    }
}

function.js は、こんな感じで書いておけば basic_auth_stringunauthorized_message を terraform の variables で動的に設定可能。

function.js
function handler(event) {
    var request = event.request;
    var headers = request.headers;
  
    var authString = "Basic ${basic_auth_string}";
  
    if (
      typeof headers.authorization === "undefined" ||
      headers.authorization.value !== authString
    ) {
      return {
        statusCode: 401,
        statusDescription: "${unauthorized_message}",
        headers: { "www-authenticate": { value: "Basic" } }
      };
    }
  
    return request;
}

CloudFront Functions を作成するには aws_cloudfront_function リソースを使います。

aws_cloudfront_function.tf
variable function_name  { default = "basic_auth" }
variable runtime        { default = "cloudfront-js-1.0" }
variable comment        { default = "" }

resource aws_cloudfront_function basic_auth {
    name    = var.function_name
    runtime = var.runtime
    comment = var.comment
    publish = true 
    code    = data.template_file.basic_auth.rendered
}

CloudFront にアタッチするには、ordered_cache_behaviordefault_cache_behavior の中に function_association を追加します。

default_cache_behavior {
    :

    function_association {
        event_type   = "viewer-request"
        function_arn = aws_cloudfront_function.basic_auth.arn
    }
}

CloudFront Functions のコードは、以下の記事を参考にしています
TerraformでCloudFront Functionsを環境ごとに有効化/無効化してみた

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