以下の内容はhttps://dk521123.hatenablog.com/entry/2025/09/20/002058より取得しました。


【Terraform】Terraform ~ variable / 基本編 ~

◾️はじめに

https://dk521123.hatenablog.com/entry/2023/12/24/173633
https://dk521123.hatenablog.com/entry/2025/09/19/093537

の続き。

Terraform の variable の 構文やTipsをまとめておく

目次

【1】variable の 構文
 1)description ... 説明文
 2)type ... データ型
 3)default ... デフォルト値
 4)validation ... 値の検証
 5)nullable ... Null許容かどうか
 6)sensitive ... Outputで表示するかどうか
【2】Tips
 1)try
 2)for / for_each
 3)jsonencode

【1】variable の 構文

* 詳細は、以下の公式ドキュメントを参照

https://developer.hashicorp.com/terraform/language/values/variables#arguments

# Items Explanations Memo
1 description 説明文
2 type データ型
3 default デフォルト値
4 validation 値の検証
5 nullable Null許容かどうか
6 sensitive Outputで表示するかどうか

1)description

* 説明文

https://developer.hashicorp.com/terraform/language/values/variables#input-variable-documentation

* 複数行になる場合、「<<-EOD~EOD」で指定

例:複数行の指定

variable filename {
  description = <<-EOD
  (Required) This value is an output file name (e.g. hello.txt)
  EOD
  type = string
}

2)type

* データ型

https://developer.hashicorp.com/terraform/language/expressions/types#types

type Explanation
string 文字列
number 数字。e.g. 6.283185, 5
bool 真偽(true or false)
list (or tuple) リスト。e.g. list(string) => ["us-west-1a", "us-west-1c"]
set セット(ユニークな値のみのリスト)
map (or object) マップ e.g. {name = "Mabel", age = 52}

例:string / list / object
https://developer.hashicorp.com/terraform/language/values/variables#declaring-an-input-variable

variable "image_id" {
  type = string
}

variable "availability_zone_names" {
  type    = list(string)
  default = ["us-west-1a"]
}

variable "docker_ports" {
  type = list(object({
    internal = number
    external = number
    protocol = string
  }))
  default = [
    {
      internal = 8300
      external = 8300
      protocol = "tcp"
    }
  ]
}

3)default

* デフォルト値

4)validation

* 値の検証

https://github.com/aws-ia/terraform-aws-mwaa/blob/main/variables.tf

のコードが勉強になった

例1:環境

variable "env" {
  description = "Environmental"
  type        = string
  default     = "dev"

  validation {
    condition     = contains(["dev", "stage", "prod"], env)
    error_message = "Only dev / stage / prod"
  }
}

例2:設定の確認

variable "environment_class" {
  description = <<-EOD
  (Optional) Environment class for the cluster. Possible options are mw1.small, mw1.medium, mw1.large.
  Will be set by default to mw1.small. Please check the AWS Pricing for more information about the environment classes.
  EOD
  type        = string
  default     = "mw1.small"

  validation {
    condition     = contains(["mw1.small", "mw1.medium", "mw1.large"], var.environment_class)
    error_message = "Invalid input, options: \"mw1.small\", \"mw1.medium\", \"mw1.large\"."
  }
}

例3:数字の最小値・最大値

variable "max_workers" {
  description = <<-EOD
  (Optional) The maximum number of workers that can be automatically scaled up.
  Value need to be between 1 and 25. Will be 10 by default
  EOD
  type        = number
  default     = 10

  validation {
    condition     = var.max_workers > 0 && var.max_workers < 26
    error_message = "Error: Value need to be between 1 and 25."
  }
}

5)nullable

* Null許容かどうか(true/false)

6)sensitive

* Outputで表示するかどうか(true/false)
* パスワード等で使用する

【2】Tips

1)try

* try で囲むと、エラーになった場合、デフォルト値で設定できる

https://developer.hashicorp.com/terraform/language/functions/try

サンプル

locals {
  raw_value = yamldecode(file("${path.module}/example.yaml"))
  normalized_value = {
    name   = tostring(try(var.raw_value.name, null))
    groups = try(var.raw_value.groups, [])
  }
}

2)for / for_each

* 詳細は、以下の関連記事を参照

Terraform ~ ループ ~
https://dk521123.hatenablog.com/entry/2024/08/12/231256

サンプル

data "aws_s3_bucket" "target" {
  for_each = toset(var.s3_buckets)
  bucket   = each.value
}

3)jsonencode

* 与えられた値を JSON 構文を使用して文字列にエンコードする

https://developer.hashicorp.com/terraform/language/functions/jsonencode

variable "sample_list" {
  type    = list(string)
  default = ["Hello", "World"]
}

resource "aws_lambda_function" "demo_lambda" {
  function_name    = local.lambda_function_name
  handler          = "main.lambda_handler"
  # ...
  environment {
    variables = {
      SAMPLE_VARS = jsonencode(var.sample_list)
    }
}

関連記事

Terraform ~ 環境構築編 ~
https://dk521123.hatenablog.com/entry/2023/04/05/000224
Terraform ~ 入門編 ~
https://dk521123.hatenablog.com/entry/2019/12/09/222057
Terraform ~ 基本編 ~
https://dk521123.hatenablog.com/entry/2023/05/03/000000
Terraform ~ local ~
https://dk521123.hatenablog.com/entry/2023/12/24/173633
Terraform ~ variable / 入門編 ~
https://dk521123.hatenablog.com/entry/2025/09/19/093537
Terraform ~ ループ ~
https://dk521123.hatenablog.com/entry/2024/08/12/231256
Terraform ~ 複数環境へデプロイすることを考える ~
https://dk521123.hatenablog.com/entry/2023/05/06/003645




以上の内容はhttps://dk521123.hatenablog.com/entry/2025/09/20/002058より取得しました。
このページはhttp://font.textar.tv/のウェブフォントを使用してます

不具合報告/要望等はこちらへお願いします。
モバイルやる夫Viewer Ver0.14