0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【簡単Terraform】【初心者向け】Terraform `locals` の使い方

Posted at

🏗️ はじめに

Terraform を使っていると、同じような値や命名ルール、タグ定義を何度も書いていることに気づくことがあります。

そのような重複を減らし、 可読性・保守性を高めるために有効なのがlocals です。

本記事では、Terraform の locals の基本的な使い方 と、タグや命名規則を一元管理する実践例 を紹介します。


🧠 locals とは?

locals は、Terraform 内で使用できるローカル変数(共通値の定義) です。

  • 再利用可能な値を定義できる
  • 複雑な式をまとめて管理できる
  • 命名規則やタグ定義を統一できる

一度定義した locals は、local.<name> で参照できます。


🧩 locals の基本的な定義方法

locals {
  project = "sample"
  env     = "dev"
  region  = "ap-northeast-1"
}

参照する場合は以下のように記述します。

name = "${local.project}-${local.env}"

🏷️ 用例①:タグ定義の一元管理

Terraform では、多くの AWS リソースで tags を指定します。
locals を使うことで、タグを一元管理できます。

locals {
  common_tags = {
    Project = "sample"
    Env     = "dev"
    Owner   = "infra-team"
  }
}
resource "aws_vpc" "this" {
  cidr_block = "10.0.0.0/16"

  tags = local.common_tags
}
resource "aws_instance" "this" {
  ami           = "ami-xxxxxxxx"
  instance_type = "t3.micro"

  tags = merge(
    local.common_tags,
    {
      Name = "app-server"
    }
  )
}

🏷️ 用例②:命名規則の統一

locals {
  project = "sample"
  env     = "dev"

  resource_prefix = "${local.project}-${local.env}"
}
resource "aws_vpc" "this" {
  cidr_block = "10.0.0.0/16"

  tags = {
    Name = "${local.resource_prefix}-vpc"
  }
}
resource "aws_subnet" "this" {
  cidr_block = "10.0.1.0/24"

  tags = {
    Name = "${local.resource_prefix}-subnet"
  }
}

🔄 variable との使い分け

項目 variable locals
値の変更 外部から指定 内部固定
主な用途 環境差分 共通ロジック
上書き 可能 不可

👉 外から変えたい値は variable、内部でまとめたい値は locals が基本方針です。


🧠 ベストプラクティス

  • 命名規則・タグは locals に集約する
  • 複雑な式は locals に切り出して可読性を上げる
  • module 内でも locals を積極的に活用する
  • 過剰に定義しすぎない(シンプルさを保つ)

🧠 まとめ

  • locals は Terraform の 共通定義・整理箱
  • タグや命名規則の統一に非常に有効
  • variable と役割を分けて使うことが重要
  • 中〜大規模構成では必須のテクニック

0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?