问题
I'm writing terraform templates to create two S3 buckets, however, my requirement is to concatenate their names in vars.tf and then pass it to main tf file. Below is the vars.tf and main s3.tf file.
vars.tf:
variable TENANT_NAME {
default = "Mansing"
}
variable BUCKET_NAME {
type = "list"
default = ["bh.${var.TENANT_NAME}.o365.attachments", "bh.${var.TENANT_NAME}.o365.eml"]
}
s3.tf:
resource "aws_s3_bucket" "b" {
bucket = "${element(var.BUCKET_NAME, 2)}"
acl = "private"
}
When do terraform plan I get an error indicating that var may not work here.
Error: Variables not allowed
on vars.tf line 10, in variable "BUCKET_NAME":
10: default = ["bh.${var.TENANT_NAME}.o365.attachments", "bh.${var.TENANT_NAME}.o365.eml"]
Variables may not be used here.
Error: Variables not allowed
on vars.tf line 10, in variable "BUCKET_NAME":
10: default = ["bh.${var.TENANT_NAME}.o365.attachments", "bh.${var.TENANT_NAME}.o365.eml"]
Variables may not be used here.
I tried replacing var in vars file with locale but did not work.
回答1:
You can use Terraform locals
block to concatenate variable values in the s3.tf
file:
locals {
BUCKET_NAME = [
"bh.${var.TENANT_NAME}.o365.attachments",
"bh.${var.TENANT_NAME}.o365.eml"
]
}
resource "aws_s3_bucket" "b" {
bucket = "${element(local.BUCKET_NAME, 2)}"
acl = "private"
}
来源:https://stackoverflow.com/questions/56651118/how-to-concatenate-s3-bucket-name-in-terraform-variable-and-pass-it-to-main-tf-f