1. 概要
sort— リストを昇順ソートするdistinct— リストから重複を除去するcompact— リストからnullと空文字を除去するreverse— リストの順序を逆にする- 各関数の実用パターンと組み合わせ例
これらの関数はリストを「整形・クリーニング」するために使います。sortで並び替え、distinctで重複排除、compactでnull除去、reverseで順序反転という用途がそれぞれ明確に分かれています。
2. sort — リストを昇順ソートする
sort(list)は、文字列リストをアルファベット(辞書)順に昇順ソートして返します。
# terraform consoleで確認
> sort(["banana", "apple", "cherry"])
["apple", "banana", "cherry"]
> sort(["10.0.2.0/24", "10.0.0.0/24", "10.0.1.0/24"])
["10.0.0.0/24", "10.0.1.0/24", "10.0.2.0/24"]
> sort(["c", "a", "b"])
["a", "b", "c"]
タグキーを昇順で並べる
terraform {
required_version = ">= 1.9"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
provider "aws" {
region = "ap-northeast-1"
}
variable "environment" {
description = "環境名"
type = string
default = "dev"
}
variable "availability_zones" {
description = "使用するAZのリスト"
type = list(string)
default = ["ap-northeast-1c", "ap-northeast-1a", "ap-northeast-1d"]
}
locals {
# AZリストをソートして一貫した順序を保証
sorted_azs = sort(var.availability_zones)
# → ["ap-northeast-1a", "ap-northeast-1c", "ap-northeast-1d"]
}
output "primary_az" {
description = "プライマリAZ(ソート後の最初の要素)"
value = local.sorted_azs[0]
}
3. distinct — 重複を除去する
distinct(list)は、リストから重複する要素を除去して最初の出現順を保持したリストを返します。
# terraform consoleで確認
> distinct(["a", "b", "a", "c", "b"])
["a", "b", "c"] # 最初の出現順を保持
> distinct(["dev", "prd", "dev", "stg"])
["dev", "prd", "stg"]
> distinct([1, 2, 1, 3])
[1, 2, 3]
複数ソースからのセキュリティグループIDを重複なしで結合する
variable "web_sg_ids" {
description = "WebサーバーのSGIDリスト"
type = list(string)
default = ["sg-001", "sg-002", "sg-001"]
}
variable "app_sg_ids" {
description = "アプリサーバーのSGIDリスト"
type = list(string)
default = ["sg-002", "sg-003"]
}
locals {
# concatで結合してdistinctで重複除去
all_sg_ids = distinct(concat(var.web_sg_ids, var.app_sg_ids))
# → ["sg-001", "sg-002", "sg-003"]
}
data "aws_ami" "amazon_linux_2023" {
most_recent = true
owners = ["amazon"]
filter {
name = "name"
values = ["al2023-ami-*-x86_64"]
}
}
resource "aws_instance" "app" {
ami = data.aws_ami.amazon_linux_2023.id
instance_type = "t3.micro"
vpc_security_group_ids = local.all_sg_ids
root_block_device {
volume_size = 20
volume_type = "gp3"
encrypted = true
}
tags = {
Name = "${var.environment}-app"
Environment = var.environment
ManagedBy = "terraform"
}
}
4. compact — nullと空文字を除去する
compact(list)は、文字列リストからnullと空文字列("")を除去して返します。
# terraform consoleで確認
> compact(["a", "", "b", null, "c"])
["a", "b", "c"]
> compact(["", "", ""])
[]
> compact(["dev", null, "stg"])
["dev", "stg"]
オプション値を含むリストをクリーニングする
variable "extra_tags" {
description = "追加タグのリスト(空の場合はnullを設定)"
type = list(string)
default = ["tag1", "", "tag2", null, "tag3"]
}
locals {
# null・空文字を除去してから処理
valid_tags = compact(var.extra_tags)
# → ["tag1", "tag2", "tag3"]
# 環境に応じてオプション値を含むリストを構築
log_groups = compact([
"/aws/app/${var.environment}",
var.environment == "prd" ? "/aws/app/${var.environment}/audit" : null,
var.environment != "dev" ? "/aws/app/${var.environment}/slow-query" : null,
])
}
5. reverse — リストの順序を逆にする
reverse(list)は、リストの要素順序を逆にして返します。
# terraform consoleで確認
> reverse(["a", "b", "c"])
["c", "b", "a"]
> reverse([1, 2, 3])
[3, 2, 1]
ソートして最後の要素(最大値)を取得する
locals {
versions = ["1.0.0", "1.2.0", "1.1.0", "2.0.0"]
# ソートして逆順にすることで最新バージョンを先頭に
sorted_desc = reverse(sort(local.versions))
# → ["2.0.0", "1.2.0", "1.1.0", "1.0.0"]
latest_version = local.sorted_desc[0]
# → "2.0.0"
}
6. 関連する関数との組み合わせパターン
| 関数 | よく組み合わせる関数 | 用途 |
|---|---|---|
sort | reverse | 降順ソート |
distinct | concat, flatten | 複数リストをマージして重複排除 |
compact | 条件式(nullを返す) | オプション値を含むリストの構築 |
reverse | sort | 降順で先頭要素を取得 |
7. 関連記事
- merge / concat / flatten の使い方 — リスト結合と組み合わせる
- for式の使い方 — フィルタリングを伴う場合はfor式を使う
- range / element / index / slice の使い方 — リスト生成・操作
- length / keys / values / contains — コレクション検査
- chunklist / coalescelist / one
- setintersection / setunion / setsubtract / setproduct
8. まとめ
sort(list)— 文字列リストをアルファベット順(昇順)でソートするdistinct(list)— 重複を除去し、最初の出現順を保持するcompact(list)—nullと空文字列を除去するreverse(list)— リストの順序を逆にするsort+reverseで降順ソート、concat+distinctで重複なし結合が典型パターン
動作確認バージョン: Terraform >= 1.9 公式ドキュメント: https://developer.hashicorp.com/terraform/language/functions/sort