terraformでlocal変数をvariables変数のように使う


  • localだとvar.envとかで呼んだりできる
  • variablesを定義しなくてよくなる

コード

provider "aws" {
  region  = "ap-northeast-1"
}

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 3.36.0"
    }
  }
}

locals {
  variables = {
    development = local.development
    production  = local.production
  }

  variable = local.variables[terraform.workspace]

  development = {
    cidr_block = "10.0.0.0/16"
  }

  production = {
    cidr_block = "10.1.0.0/16"
  }
}


resource "aws_vpc" "main" {
  cidr_block = local.variable["cidr_block"]

  tags = {
    Name = "${terraform.workspace}-vpc-main"
  }
}

development

terraform workspace new development
terraform workspace select development
terraform init
terraform plan

production

terraform workspace new production
terraform workspace select production
terraform init
terraform plan