How to concatenate S3 bucket name in Terraform variable and pass it to main tf file

痞子三分冷 提交于 2021-01-27 06:50:56

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!