4

I want to have different s3 names based on different environments using terraform.

If I define the name in terraform.tfvar, it won't work:

s3_bucket_name          = "tf-${terraform.workspace}"

If I hardcode s3 bucket name in s3.tf, it works:

resource "aws_s3_bucket" "s3" {
   bucket        = "tf-${terraform.workspace}"
   ....
}

how to define the workspace related name from terraform.tfvar? I do not want to hard code it in tf file.

4

Variables are static, literal inputs to your configuration that come from either the command line or from tfvars files. It is not possible to use interpolations here, since the variable values are processed before interpolation begins in order to make them available to other expressions.


If the goal is to define the S3 bucket name in one place and re-use it several times in the same configuration, the Local Values feature can do this if you are using Terraform v0.10.4 or newer. You can declare the named value in one of your .tf files:

locals {
  s3_bucket_name = "tf-${terraform.workspace}"
}

You can then interpolate this value in various places in your configuration using the name local.s3_bucket_name, like this:

resource "aws_s3_bucket" "s3" {
  bucket = "${local.s3_bucket_name}"
  ...
}

Local values are conceptually similar to module outputs but they are exposed within the same module they are defined in, rather than passing a value up to the parent module.


If the goal is to allow this generated default name to be overriden optionally by a variable, then that can be achieved with some conditional logic:

variable "override_s3_bucket_name" {
  default = ""
}

locals {
  s3_bucket_name = "${var.override_s3_bucket_name != "" ? var.override_s3_bucket_name : "tf-${terraform.workspace}"}"
}

resource "aws_s3_bucket" "s3" {
  bucket = "${local.s3_bucket_name}"
  ...
}

The above will generate a default name based on the selected workspace if override_s3_bucket_name is not set, but if that variable is set then its value will be used instead.

1
  • Thanks @Martin. I will use your local variable solutions!
    – user389955
    Jan 12 '18 at 21:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.