1. 概要
upper/lower— 大文字・小文字変換title— タイトルケースに変換substr— 部分文字列の抽出strrev— 文字列を逆順に- 実際のユースケース
Terraformの文字列ケース変換関数は、AWSリソース名のタグ値の正規化・環境名の統一・文字数制限のある名前の切り出しなどに活用できます。
2. upper / lower — 大文字・小文字変換
# terraform consoleで確認
> upper("hello")
"HELLO"
> lower("HELLO")
"hello"
> lower("Dev-MyApp")
"dev-myapp"
タグ値を統一ケースで管理する
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 "service_name" {
description = "サービス名"
type = string
default = "MyApp"
}
locals {
# リソース名はlower()で統一(AWSリソース名は小文字推奨)
env = lower(var.environment)
service = lower(var.service_name)
# タグのEnvironmentはCapitalize(先頭大文字)にしたい場合
env_tag = title(local.env)
}
data "aws_ami" "amazon_linux_2023" {
most_recent = true
owners = ["amazon"]
filter {
name = "name"
values = ["al2023-ami-*-x86_64"]
}
}
resource "aws_instance" "web" {
ami = data.aws_ami.amazon_linux_2023.id
instance_type = "t3.micro"
root_block_device {
volume_size = 20
volume_type = "gp3"
encrypted = true
}
tags = {
Name = "${local.env}-${local.service}-web"
Environment = local.env_tag # "Dev", "Stg", "Prd"
ManagedBy = "terraform"
}
}
3. title — タイトルケースに変換
title(string)は各単語の先頭を大文字に変換します。
# terraform consoleで確認
> title("hello world")
"Hello World"
> title("dev environment")
"Dev Environment"
> title("my-app-service")
"My-App-Service"
4. substr — 部分文字列の抽出
substr(string, offset, length)は文字列の一部を抽出します。offsetは開始位置(0始まり)、lengthは抽出する文字数(-1で末尾まで)です。
# terraform consoleで確認
> substr("hello world", 0, 5)
"hello"
> substr("hello world", 6, -1)
"world"
> substr("hello world", 6, 3)
"wor"
S3バケット名の長さ制限に対応する
locals {
# S3バケット名の最大63文字制限への対応
# プレフィックスに長い名前を使う場合に切り詰め
long_name = "very-long-application-name-that-might-exceed-limits"
short_name = substr(local.long_name, 0, 20) # 先頭20文字のみ
bucket_name = "${var.environment}-${local.short_name}"
}
UUIDの短縮版(先頭8文字)
locals {
# uuidの先頭8文字をユニークサフィックスとして使う
unique_id = substr(uuid(), 0, 8)
resource_name = "${var.environment}-web-${local.unique_id}"
}
5. strrev — 文字列を逆順に
strrev(string)は文字列を逆順にします。
# terraform consoleで確認
> strrev("hello")
"olleh"
> strrev("terraform")
"mrrofret"
実用的な用途は限られますが、特定のハッシュ・識別子生成のパターンで使われることがあります。
6. 関連記事
- chomp / trimspace / trim / trimprefix / trimsuffix — 文字列のトリム処理
- startswith / endswith / regex / regexall — 文字列のマッチング
- join / split / format / replace — 文字列の結合・分割・フォーマット
- join / split / format / replace — 文字列操作
- formatlist — リストの各要素をフォーマット
- locals(ローカル値)— DRYなコードを書く
7. まとめ
upper(str)— すべて大文字に変換lower(str)— すべて小文字に変換。リソース名の正規化に定番title(str)— 各単語の先頭を大文字に変換substr(str, offset, length)— 部分文字列の抽出。長さ制限のある名前の切り詰めに使うstrrev(str)— 文字列を逆順に変換
動作確認バージョン: Terraform >= 1.9 公式ドキュメント: https://developer.hashicorp.com/terraform/language/functions/upper