Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format numeric variable in Terraform

Tags:

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?

like image 716
Katulus Avatar asked Feb 19 '19 16:02

Katulus


People also ask

How do you change a variable value in Terraform?

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.

What is format in Terraform?

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.

How can Terraform input variables be defined?

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.


1 Answers

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)}"
    }
}
like image 200
ydaetskcoR Avatar answered Sep 23 '22 13:09

ydaetskcoR