Terraform variable omitting leading "0"

Hi All,

I have variables.tf file asking users to input. I am expecting numbers from “01 top 99”

When a number “01” is entered the 0 is omitted and number 1 is used. I did some research and I was told to use variable type as string nut still doesn’t like it.

variable “suffix” {
type = string
description = “Enter the suffix two character in integer of the resource, example (01, 03).”
validation {
condition = length(var.suffix) == 2
error_message = “Validation condition does not meet the number.”
}
}

Can anyone point out the issue?

Thanks in advance

Hi

variable "suffix" {
  type = string
  description = "Enter the suffix two character in integer of the resource, example (01, 03)."
  validation {
    condition = length(format("%2d", var.suffix)) == 2
    error_message = "Validation condition does not meet the number"
  }
}
  • %d: Represents an integer.
  • 2: Specifies that the number must have at least 2 digits

Instead of covering over the problem converting the string to an integer and back to a string again to validate, I would instead try to figure out why your string of "01" is being converted to an integer in the first place.

Are you using a current version of Terraform?
Can you show a complete example of how you end up dropping the 0 from the string?

Bingo!.. it was just the version of azurerm that was causing it.

Thanks mate!