概要
TerraformでWorkspaceを利用する際に、環境ごとのデフォルトパラメータを取得する方法を紹介します。
文字列型のデフォルト値
モジュール呼び出し元
module "ec2" {
source "modules/ec2"
instance_type = {
default = "t2.micro"
production = "m5.large"
}
...
}
モジュール呼び出し先
variable "instance_type" {
default = {}
}
resource "aws_instance" "this" {
instance_type = "${lookup(var.instance_type, terraform.workspace, var.name["default"])}"
...
}
上記例の場合、Workspaceがproduction
の場合はm5.large
、development
やstaging
といった環境であればt2.small
が適用される。
Map型のデフォルト値
production
環境では172.29.0.0/16
、その他の環境では172.30.0.0/16
を許可したい。
モジュール呼び出し元
module "security_group" {
source "modules/security_group"
ingress_rules = {
default = [
{
from_port = "22"
to_port = "22"
protocol = "tcp"
cidr_blocks = "172.30.0.0/16"
description = ""
}
],
production = [
{
from_port = "22"
to_port = "22"
protocol = "tcp"
cidr_blocks = "172.29.0.0/16"
description = ""
}
]
}
...
}
モジュール呼び出し先
variable "security_group" {
default = {}
}
locals {
ingress_rules = "${var.ingress_rules[contains(keys(var.ingress_rules), terraform.workspace) ? terraform.workspace : "default"]}"
}
resource "aws_security_group" "this" {
# (省略)
}
resource "aws_security_group_rule" "ingress_rules" {
count = "${length(local.ingress_rules)}"
security_group_id = "${aws_security_group.this.id}"
type = "ingress"
from_port = "${lookup(local.ingress_rules[count.index], "from_port")}"
to_port = "${lookup(local.ingress_rules[count.index], "to_port")}"
protocol = "${lookup(local.ingress_rules[count.index], "protocol")}"
cidr_blocks = ["${split(",", lookup(local.ingress_rules[count.index], "cidr_blocks"))}"]
description = "${lookup(local.ingress_rules[count.index], "description")}"
...
}
文字列同様、lookup
を使おうとするとlookup: argument 2 should be type string, got type list in
エラーが出てしまう。
This function only works on flat maps and will return an error for maps that include nested lists or maps.
という訳でMapには使えない。
${var.ingress_rules[contains(keys(var.ingress_rules), terraform.workspace) ? terraform.workspace : "default"]}
このようにMapでキーリストを取得後、Workspaceがキーに含まれてる場合はWorkspaceのルール、含まれていない場合はdefault
のルールの配列を取得することで問題を回避できる。