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?
Edit the provider block in main.tf to use the new aws_region variable. Add a declaration for the vpc_cidr_block variable to variables.tf . Now, replace the hard-coded value for the VPC's CIDR block with a variable in main.tf . module "vpc" { source = "terraform-aws-modules/vpc/aws" version = "2.66.
The format function produces a string by formatting a number of other values according to a specification string. It is similar to the printf function in C, and other similar functions in other programming languages.
Set the instance name with a variable Add a variable to define the instance name. Create a new file called variables.tf with a block defining a new instance_name variable. Note: Terraform loads all files in the current directory ending in . tf , so you can name your configuration files however you choose.
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)}"
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With