【Terraform】Terraform ~ 基本編 / 変数 ~

■ はじめに

Terraform の 変数について扱う。

目次

【0】Terraform の変数
【1】variable
 1)Hello world
 2)変数呼び出し方
【2】local
 1)Hello world
【3】variable の 構文
 1)description
 2)type
 3)default
 4)validation
 5)nullable
 6)sensitive
【4】try

【0】Terraform の変数

* 以下の2種類。
~~~~
1)変数 - variable
2)ローカル変数 - local
~~~~

* 以下のサイト、すごくいい記事、、、

https://zenn.dev/sway/articles/terraform_biginner_varliable

【1】variable

* 変数の定義
 => variable セクションで定義

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

1)Hello world

variables.tf (変数の定義)

variable content {
  description = <<-EOD
  (Optional) This value is an explanation
  EOD
  type = string
  default = "hello world!!!?"
}
variable filename {
  description = <<-EOD
  (Required) This value is an output file name (e.g. hello.txt)
  EOD
  type = string
}

main.tf (呼び出し元)

# var.<変数名>で参照
resource "local_file" "input_sample" {
  content  = "[Result] ${var.content}
  filename = var.filename
}

実行例

$ terraform init

# terraform plan -var "content=Hi, World"
$ terraform apply -var "content=Hi, World"
var.filename
  (Required) This value is an output file name (e.g. hello.txt)

  Enter a value: output.txt << 必須となっている出力ファイル名を入力

Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only 'yes' will be accepted to approve.

  Enter a value:yes <<デプロイしてよければ「yes」を入力

# 確認
$ more output.txt
[Result] Hi, World

2)変数呼び出し方

* 以下の公式ドキュメントに記載されている

https://developer.hashicorp.com/terraform/language/values/variables#assigning-values-to-root-module-variables
[1] -var option
https://developer.hashicorp.com/terraform/language/values/variables#variables-on-the-command-line

terraform apply -var="image_id=ami-abc123"
terraform apply -var='image_id_list=["ami-abc123","ami-def456"]' -var="instance_type=t2.micro"
terraform apply -var='image_id_map={"us-east-1":"ami-abc123","us-east-2":"ami-def456"}'

[2] .tfvars files
https://developer.hashicorp.com/terraform/language/values/variables#variable-definitions-tfvars-files

terraform apply -var-file="testing.tfvars"

[3] 環境変数 TF_VAR_XXX
https://developer.hashicorp.com/terraform/language/values/variables#environment-variables

export TF_VAR_image_id=ami-abc123
terraform plan

【2】local

* ローカル変数の定義
 => locals セクションで定義

https://developer.hashicorp.com/terraform/language/values/locals

1)Hello world

locals.tf (ローカル変数の定義)

locals {
  content  = "hello world!!!?"
  filename = "hello.txt"
}

main.tf (呼び出し元)

# ローカル変数の参照
#  => local.<key>で変数
resource "local_file" "helloworld" {
  content  = local.content
  filename = local.filename
}

【3】variable の 構文

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

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

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/values/variables#type-constraints

基本系

* string
* number
* bool

その他

* list(<TYPE>)
* set(<TYPE>)
* map(<TYPE>)
* object({<ATTR NAME> = <TYPE>, ... })
* tuple([<TYPE>, ...])

例: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 "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\"."
  }
}

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

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)
* パスワード等で使用する

【4】try

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

https://developer.hashicorp.com/terraform/language/functions/try
サンプル

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

参考文献

https://qiita.com/ringo/items/3af1735cd833fb80da75
https://capsulecloud.io/terraform-variable

関連記事

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 ~ 基本編 / Module ~
https://dk521123.hatenablog.com/entry/2023/05/19/113544
Terraform ~ Terraformあれこれ ~
https://dk521123.hatenablog.com/entry/2023/05/15/205352