Reputation: 751
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
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.
%
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).%
symbol, to say that you want the parameter to be formatted with leading zeros include a 0
.%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
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