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.