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?

More than 5 years have passed since last update.

Terraform0.12での変数定義と参照

Last updated at Posted at 2020-03-22

はじめに

Terraform使ってこなかった系SREやってた系エンジニアです。
アプリケーションエンジニアに僕は戻る。

とある案件でTerraform0.12つかうことになったんだけど、なんかうまくいかねえなあ、と思ってたこの基本的になやつ。
あちこちに書いてあるようで書いてなかった。基本的なことなのになあ。

日本語にQiitaとかみると0.11時代の書き方をそのまま持ち込んでいる人がおおかったりして、うーん、という感じ。
時代にのろう。

変数定義

varaiableなんとかで書く。

variable.tf
variable "project_name" {
  default = {
    production = "srockstyle-prd"
    staging = "srockstyle-stg"
    development = "srockstyle-dev"
  }
}

variable "region" {
  default = {
    production = "asia-northeast1"
    staging = "asia-northeast1"
    development = "asia-northeast1"
  }
}

variable "vpc_network_name" {
  default = "srockstyle"
}

terraformにはworkspaceっていう機能があって、環境ごとに違う変数を割り当てたいときに使う。
workspaceごとの設定なのでproduction = "~~~"ってのはproductionっていう名前のworkspaceの時に使われる。

workspaceごとに変更なんてしなくてもいいのなら、defaultにそのまま指定で構わない。

変数参照

参照する際はvar.[変数名] で参照する。

main.tf
resource "google_compute_network" "srockstyle-main" {
  name = var.vpc_network_name
  project = lookup(var.project_name, "${terraform.workspace}")
]

workspaceごとの設定をしている場合はlookupを使う。
二つ引数でlookup(var.[変数名], ${terraform.workspace)で参照できる。
0.11?のときのように変数を"${}"とかで囲んで指定すると「そんな古い書き方してんじゃねーよ」って怒られる。

僕は0.11つかったことないんでいいんだけど。

まとめ

完璧に理解した。

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?