Katulus
Katulus

Reputation: 751

How to format numeric variable in Terraform

I have a following (simplified) Terraform code:

variable "cluster_id" {
    default = 1
}

resource "aws_instance" "instance" {
    ... some instance properties ...
    tags {
        "Name" = "${format("cluster-%02d", var.cluster_id)}"
    }
}

And when I run terraform apply the plan shows:

tags.Name: "%!d(string=1)"

The cluster_id in format() is not handled as a number so formatting fails. I would expect that I get cluster-01 but that's not the case.

Am I doing something wrong or is it really not possible to use custom variables as numbers in formatting?

Upvotes: 16

Views: 16189

Answers (2)

ydaetskcoR
ydaetskcoR

Reputation: 56987

Terraform, pre 0.12, only supports string, list and map types as an input variable so despite you providing an integer (or a float or a boolean) it will be cast to a string.

Both Terraform and Go allow you to use the same padding for integers and strings though so you can just use the following to 0 pad the cluster_id:

resource "aws_instance" "instance" {
    # ... some instance properties ...
    tags {
        "Name" = "${format("cluster-%02s", var.cluster_id)}"
    }
}

Specifically you use the format function, passing a format string as the first argument, then a list of values for the remaining arguments.

  • The format string should contain a % symbol for each place where you want one of the parameters to be substituted (the first % symbol is replaced by the first parameter after the format string, the second by the second, etc).
  • After the % symbol, to say that you want the parameter to be formatted with leading zeros include a 0.
  • Next, say how many digits to display; e.g. to pad to 5 characters put a 5.
  • Finally put an S to say that this should output a string
  • So the above format string would be %05s, and we'd expect 1 additional parameter to be passed to take the place of this placeholder.

Example

output demo {
    format("%04s %04s %02s", 93, 2, 7)
}

Output

demo = "0093 0002 07"

Upvotes: 21

Katulus
Katulus

Reputation: 751

Another option I found is to do ${format("cluster-%02d", var.cluster_id+0)}. Adding zero produces real number and then %02d works correctly. But using %02s is cleaner.

Upvotes: 0

Related Questions