1. 概要
base64encode/base64decode— Base64エンコード・デコードmd5— MD5ハッシュを生成するsha256— SHA-256ハッシュを生成するuuid— ランダムUUIDを生成する- 実際のユースケース
これらの関数はリソース名の一意化、ファイル変更の検出、パスワードのハッシュ化、ユーザーデータのエンコードといった用途に使います。
2. base64encode / base64decode
base64encode(string)は文字列をBase64エンコードし、base64decode(string)はBase64文字列をデコードします。
# terraform consoleで確認
> base64encode("Hello, Terraform!")
"SGVsbG8sIFRlcnJhZm9ybSE="
> base64decode("SGVsbG8sIFRlcnJhZm9ybSE=")
"Hello, Terraform!"
EC2ユーザーデータをBase64エンコードする
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"
}
data "aws_ami" "amazon_linux_2023" {
most_recent = true
owners = ["amazon"]
filter {
name = "name"
values = ["al2023-ami-*-x86_64"]
}
}
locals {
user_data_script = <<-EOT
#!/bin/bash
set -e
dnf update -y
dnf install -y nginx
systemctl enable nginx
systemctl start nginx
EOT
}
resource "aws_instance" "web" {
ami = data.aws_ami.amazon_linux_2023.id
instance_type = "t3.micro"
# aws_instanceはuser_dataを自動でBase64エンコードするが、
# 一部のリソースではbase64encodeが必要
user_data = base64encode(local.user_data_script)
root_block_device {
volume_size = 20
volume_type = "gp3"
encrypted = true
}
tags = {
Name = "${var.environment}-web"
Environment = var.environment
ManagedBy = "terraform"
}
}
3. md5 — MD5ハッシュを生成する
md5(string)は文字列のMD5ハッシュ(16進数文字列)を返します。
# terraform consoleで確認
> md5("hello")
"5d41402abc4b2a76b9719d911017c592"
> md5("terraform")
"62b3ddc0fa0d7e1069c8f5e36fd5b0f2"
ファイル変更を検出してLambdaを再デプロイする
resource "aws_lambda_function" "api" {
function_name = "${var.environment}-api"
role = aws_iam_role.lambda.arn
handler = "index.handler"
runtime = "nodejs20.x"
filename = "${path.module}/lambda/function.zip"
# ZIPファイルのハッシュ値でコードの変更を検出
# ファイルが変わればハッシュが変わり、Lambdaが更新される
source_code_hash = filebase64sha256("${path.module}/lambda/function.zip")
tags = {
Name = "${var.environment}-api"
Environment = var.environment
ManagedBy = "terraform"
}
}
4. sha256 — SHA-256ハッシュを生成する
sha256(string)は文字列のSHA-256ハッシュ(16進数文字列)を返します。MD5より衝突耐性が強く、セキュリティ用途にはsha256を推奨します。
# terraform consoleで確認
> sha256("hello")
"2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
sensitiveな変数のハッシュ値をタグに使う
variable "api_key" {
description = "APIキー"
type = string
sensitive = true
}
locals {
# APIキー自体はsensitiveだが、ハッシュ値はタグに使える
api_key_hash = sha256(var.api_key)
}
resource "aws_s3_bucket" "api_data" {
bucket = "${var.environment}-api-data"
tags = {
Name = "${var.environment}-api-data"
Environment = var.environment
ManagedBy = "terraform"
ApiKeyHash = substr(local.api_key_hash, 0, 8) # 先頭8文字のみ
}
}
5. uuid — ランダムUUIDを生成する
uuid()はランダムなUUID v4(xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx形式)を返します。
# terraform consoleで確認
> uuid()
"a7b3c9d1-e5f2-4a08-b6c4-d8e0f1a2b3c4"
> uuid()
"91c5d2e3-f4a5-4b16-c7d8-e9f0a1b2c3d4" # 毎回異なる値
注意:
uuid()はtimestamp()と同様にplanのたびに異なる値を返します。リソース名に使うと毎回再作成が必要と判定されます。一意な名前が必要な場合はrandom_idリソース(HashiCorp Random Provider)の使用を検討してください。
# ✅ 一時的なリソース名の生成(applyのたびに変わってもよい場合)
locals {
temp_bucket_name = "temp-${substr(uuid(), 0, 8)}"
}
6. 関連記事
- file / fileexists / fileset の使い方 — filebase64sha256との組み合わせ
- sensitive変数の使い方 — sha256でsensitive値のハッシュをタグに使う
- timestamp / formatdate / timeadd の使い方 — 同じく「実行ごとに変わる」注意が必要な関数
- urlencode / base64gzip
- filebase64 / filesha256 — ファイルハッシュ・エンコード
- bcrypt / rsadecrypt — 暗号関数
7. まとめ
base64encode(str)/base64decode(str)— Base64エンコード・デコード。ユーザーデータなどに使うmd5(str)— MD5ハッシュ生成。軽量な変更検出に使う(セキュリティ用途には非推奨)sha256(str)— SHA-256ハッシュ生成。セキュリティ用途・ファイル変更検出に推奨uuid()— ランダムUUIDを生成。planのたびに変わるため、リソース名への直接使用は注意filebase64sha256(path)— ファイルのSHA-256ハッシュをBase64で返す(Lambda更新検出に定番)
動作確認バージョン: Terraform >= 1.9 公式ドキュメント: https://developer.hashicorp.com/terraform/language/functions/base64encode