0
1

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のデータ型)

0
Last updated at Posted at 2025-08-15

使用教材

データをターミナルで出力する方法

  • 変数を定義したらターミナルで初期化
terraform init
  • terraform consoleでコンソール起動
  • コンソールを抜けたい場合はCtl+Dで抜ける
$ terraform console
>ここに出力したい変数を打ち込む

プリミティブ型

  • string、num、boolの3種類
variable "str_sample" {
  type = string #文字列
  default = "Hello World"
}

variable "num_sample" {
    type =  number #数値
    default = 0  
}

variable "bool_sample" {
    type = bool #真偽値
    default = false  
}

オブジェクト型

  • キーバリューで定義される
variable "obj_sample" {
    type = object({
      name = string
      age = number 
    })
    default = {
      name = "tanaka" 
      age = 28
    }
}

出力時

> var.obj_sample.name
"tanaka"

tuple型

variable "tuple_sample" {
    type = tuple([ 
        string,number
     ])
  default = [ "tanaka", 28 ]
}

出力時

> var.tuple_sample #tuple_sample丸ごと呼び出し
[
  "tanaka",
  28,
]
> var.tuple_sample[0] #tuple_sampleの0番目の要素を呼び出し
"tanaka"

list型

variable "list_sample" {
    type = list(string)
    default = [ "tanaka","sato" ]
}

map型

variable "map_sample" {
    type = map(string)
    default = {
      "High" = "m5.2xlarge"
      "Mid" = "m5.large"
      "Low" = "t2.micro"
    }
}

出力時

> var.map_sample.High
"m5.2xlarge"

set型

  • 重複要素を除いて変数に格納できる
variable "set_sample" {
    type = set(string)
    default = [ "tanaka","sato","tanaka","sasaki","sato" ]

}

for分を使った出力
```hcl
> [for itm in var.set_sample:itm]
[
  "sasaki",
  "sato",
  "tanaka",
]

📊 Terraformデータ型の使い分け表 suport by Copilot

型名 用途・使いどころ 特徴 注意点
string 名前・ID・タグなど単一の文字列 単純で扱いやすい 数値や真偽値と混同しない
number ポート番号・カウント・サイズ指定 整数・小数どちらもOK "3"string 扱いになる
bool フラグ・有効/無効の切り替え true / false のみ "true"string 扱いになる
object 複数の属性をまとめたいとき(例:ユーザー情報) キーと型を明示できる構造化データ 型定義が厳密なのでミスに注意
tuple 異なる型を順序付きで扱いたいとき 型と順序が固定 要素数・型の順番が一致しないとエラー
list 同じ型の値を順序付きで扱いたいとき インデックスでアクセス可能 型が混在するとエラーになる
map 環境別設定・ラベル・条件分岐など キーでアクセスできる キーは文字列のみ、順序は保証されない
set 重複を排除したいとき(例:タグ一覧) 自動で重複除去、順序なし 順序に依存する処理には不向き

🧠 使い分けのヒント

  • 🔹 単純な値string, number, bool
  • 🔸 構造化されたデータobject, map
  • 🔸 順序付きの配列list, tuple
  • 🔸 重複なしの集合set

✨ 実務での選び方例

シーン 適した型 理由
EC2のインスタンスタイプ string 単一の文字列で十分
環境ごとのAMI指定 map env をキーにしてAMIを切り替えられる
タグ一覧 set 重複を排除しつつ一覧化できる
ユーザー情報(名前+年齢) object 属性ごとに型を定義できる
異なる型の組み合わせ tuple 型と順序を固定できる
0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?