indent — 文字列のインデントを追加する

1. 概要

  • indent — 文字列の2行目以降にスペースを追加
  • ヒアドキュメントとの組み合わせ
  • JSON・YAML埋め込みでの活用

indent(spaces, string)は文字列の2行目以降にスペースを追加します。ヒアドキュメントや複数行のJSONをインデントされた文字列の中に埋め込む場合に使います。


2. 基本的な使い方

# terraform consoleで確認
> indent(2, "line1\nline2\nline3")
"line1\n  line2\n  line3"

> indent(4, "first\nsecond\nthird")
"first\n    second\n    third"

1行目はそのまま、2行目以降に指定したスペース数が追加されます。


3. ヒアドキュメントとの組み合わせ

indentが最も役立つのは、ヒアドキュメント(heredoc)を別のヒアドキュメントの中に埋め込む場面です。

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"
}

locals {
  # 複数行のスクリプトをインデント付きで埋め込む
  setup_script = <<-EOT
    #!/bin/bash
    dnf update -y
    dnf install -y nginx
    systemctl enable nginx
  EOT

  # Nginx設定ファイル(setup_scriptを4スペースインデントで埋め込む)
  cloud_config = <<-EOT
    #cloud-config
    runcmd:
      - |
        ${indent(6, trimspace(local.setup_script))}
  EOT
}

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"

  user_data = base64encode(local.cloud_config)

  root_block_device {
    volume_size = 20
    volume_type = "gp3"
    encrypted   = true
  }

  tags = {
    Name        = "${var.environment}-web"
    Environment = var.environment
    ManagedBy   = "terraform"
  }
}

4. JSONをインデントして埋め込む

locals {
  policy_statements = jsonencode([
    {
      Effect   = "Allow"
      Action   = ["s3:GetObject"]
      Resource = "*"
    }
  ])

  # IAMポリシードキュメントをインデントして可読性を高める
  full_policy = <<-EOT
    {
      "Version": "2012-10-17",
      "Statement": ${indent(4, local.policy_statements)}
    }
  EOT
}

5. indentを使わなくて済む代替手段

jsonencode()yamlencode()でJSONやYAMLを生成する場合は、indentは不要です。indentが必要になるのは、主にヒアドキュメント内に複数行テキストを埋め込む特殊なケースです。

# ✅ indentが不要なパターン(こちらが推奨)
resource "aws_iam_role_policy" "example" {
  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [{
      Effect   = "Allow"
      Action   = ["s3:GetObject"]
      Resource = "*"
    }]
  })
}

6. 関連記事


7. まとめ

  • indent(spaces, str) — 文字列の2行目以降にスペースを追加する
  • 1行目はインデントされない(ヒアドキュメントに埋め込む際に先頭位置が固定されているため)
  • ヒアドキュメント内に複数行テキストを適切なインデントで埋め込む場面で活躍
  • jsonencode()/yamlencode()で代替できる場合はそちらを使う方がシンプル

動作確認バージョン: Terraform >= 1.9 公式ドキュメント: https://developer.hashicorp.com/terraform/language/functions/indent