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

Terraformのvalidationで文字数制限をかける(10文字以内の例)

Posted at

Terraformのvariableにはvalidationがあり、入力値の条件を事前にチェックできます。
この記事では「10文字以内」という文字数制限にフォーカスして、validationの書き方と挙動を紹介します。

この記事でやること

  • 10文字以内の制約をvalidationで実装する
  • ルール違反時のエラー表示を確認する

validationの書き方

今回のポイントはこの3行です。

validation {
  condition     = length(var.bucket_name) <= 10
  error_message = "bucket_name must be 10 characters or fewer."
}

何をしているか

  • condition: 真偽値を返す式を書く(今回は長さが10以下かどうか)
  • error_message: conditionfalseのときに表示されるメッセージ

このブロックがあるだけで、入力時点で文字数チェックが走ります。

サンプル構成

ファイル配置構成
.
├── main.tf
├── variables.tf
└── outputs.tf

main.tf

main.tf
terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = ">= 5.0"
    }
  }
}

provider "aws" {
  region = var.aws_region
}

resource "aws_s3_bucket" "this" {
  bucket = var.bucket_name
  tags   = var.tags
}

variables.tf(validationの実装例)

variables.tf
variable "aws_region" {
  type        = string
  description = "AWS region."
  default     = "ap-northeast-1"
}

variable "bucket_name" {
  type        = string
  description = "Name of the S3 bucket (max 10 characters)."

  validation {
    condition     = length(var.bucket_name) <= 10
    error_message = "bucket_name must be 10 characters or fewer."
  }
}

variable "tags" {
  type        = map(string)
  description = "Tags to apply to the bucket."
  default     = {}
}

outputs.tf

outputs.tf
output "bucket_id" {
  value       = aws_s3_bucket.this.id
  description = "ID of the S3 bucket."
}

output "bucket_arn" {
  value       = aws_s3_bucket.this.arn
  description = "ARN of the S3 bucket."
}

使い方(確認方法)

terraform
% terraform init
% terraform plan -var="bucket_name=example10"

実行結果(OK: 10文字以内)

OK
% terraform plan -var="bucket_name=example10"

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated
with the following symbols:
  + create

Terraform will perform the following actions:

  # aws_s3_bucket.this will be created
  + resource "aws_s3_bucket" "this" {
      + acceleration_status         = (known after apply)
      + acl                         = (known after apply)
      + arn                         = (known after apply)
      + bucket                      = "example10"
      + bucket_domain_name          = (known after apply)
      + bucket_prefix               = (known after apply)
      + bucket_region               = (known after apply)
      + bucket_regional_domain_name = (known after apply)
      + force_destroy               = false
      + hosted_zone_id              = (known after apply)
      + id                          = (known after apply)
      + object_lock_enabled         = (known after apply)
      + policy                      = (known after apply)
      + region                      = "ap-northeast-1"
      + request_payer               = (known after apply)
      + tags_all                    = (known after apply)
      + website_domain              = (known after apply)
      + website_endpoint            = (known after apply)

      + cors_rule (known after apply)

      + grant (known after apply)

      + lifecycle_rule (known after apply)

      + logging (known after apply)

      + object_lock_configuration (known after apply)

      + replication_configuration (known after apply)

      + server_side_encryption_configuration (known after apply)

      + versioning (known after apply)

      + website (known after apply)
    }

Plan: 1 to add, 0 to change, 0 to destroy.

Changes to Outputs:
  + bucket_arn = (known after apply)
  + bucket_id  = (known after apply)

Note: You didn't use the -out option to save this plan, so Terraform can't guarantee to take exactly these
actions if you run "terraform apply" now.

実行結果(NG: 10文字超)

NG
% terraform plan -var="bucket_name=too-long-name"

Planning failed. Terraform encountered an error while generating this plan.

╷
│ Error: Invalid value for variable
│ 
│   on variables.tf line 7:
│    7: variable "bucket_name" {
│     ├────────────────
│     │ var.bucket_name is "too-long-name"
│ 
│ bucket_name must be 10 characters or fewer.
│ 
│ This was checked by the validation rule at variables.tf:11,3-13.
╵

上記のように10文字を超えると、validationのメッセージが表示されます。

補足

  • 実際のS3バケット名の制約はもっと多いです(文字種や長さなど)。
  • ここではvalidationの書き方に集中するため、あえてシンプルなルールにしています。

まとめ

validationを使うと、入力ミスを早い段階で発見できます。
まずは文字数制限のようなシンプルなルールから導入するのがおすすめです。

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