LoginSignup
7
5

More than 5 years have passed since last update.

Terraformでパラメータのデフォルト値を取得する

Last updated at Posted at 2018-06-27

概要

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.largedevelopmentstagingといった環境であれば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のルールの配列を取得することで問題を回避できる。

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