5章 変数を制御する
variable ブロックで使えるパラメータ
default: 定義されていない場合に入るデフォルト値
type: 型
description: 説明文
validation: 値のルール
sensitive: 秘匿性の高い内容か(e.g. パスワードや API キー)
nullable: null を許可するか
上記のパラメータはすべてオプショナル
堅牢な変数を定義する方法
type による制御
期待と異なる値が代入されることを防ぐ
code:.tf
variable "ebs_storage_size" {
description = "EBS storage size indicated by number."
type = number
}
validation ブロックによる制御
condition パラメータに定義した式で値を評価し、結果が false ならばエラーを出力する
エラーメッセージは error_message で指定する
code:.tf
variable "s3_arn" {
description = "ARN of the S3 bucket to output logs."
type = string
validation {
condition = can(regex("^arn:aws:s3:::", var.s3_arn))
error_message = "s3_arn should start arn:sws:s3:::"
}
}
評価式内でローカル変数を参照する
v1.9 から validation ブロックでは変数の評価式から他の変数やデータリソース、局所変数を参照できるようになった
code:.tf
variable "create_fargate_cluster" {
description = ""
type = bool
default = false
}
variable "fargate_cluster_endpoint" {
description = ""
type = string
default = ""
validation {
condition = var.create_fargate_cluster == false ? length(var.fargate_cluster_endpoint) > 0 : true
error_message = "You must specify a value for fargate_cluster_endpoint if create_fargate_cluster is false."
}
}
より厳格な変数制御
object の各フィールドの制御
code:.tf
resource "aws_instance" "sample" {
ami = "ami-xxxxxxxxx"
instance_type = var.sample_ec2_setting.instance_type
private_ip = var.sample_ec2_setting.private_ip
ebs_optimized = true
...
}
variable "sample_ec2_setting" {
type = object({
instance_type = string
private_ip = string
})
validation {
condition = can(regex("^t", var.sample_ec2_setting.instance_type)) && can(regex("^10.0.10.", var.sample_ec2_setting.private_ip))
error_message = "The instance_type must be t type and private_ip must be 10.0.10.."
}
}
for_each を利用すると、ループを用いて利用するパラメータを制御できる
code:.tf
resource "aws_security_group_rule" "sample" {
for_each = { for setting in var.sample_rule_setting : setting.description => setting }
security_group_id = "sg-xxxxxx"
type = each.value.type
to_port = each.value.to_port
protocol = each.value.protocol
cidr_blocks = each.value.cidr_blocks
description = each.value.description
}
variable "sample_rule_setting" {
type = list(object({
type = string
from_port = string
to_port = string
protocol = string
cidr_blocks = list(string)
description = string
}))
}