Jeff
Jeff Cloud Systems Architect
1 min read / TL;DR

Pad Integers in Terraform

Pad Integers in Terraform

How to pad integers less than 10 in Terraform

Overview

I recently had a request to create N number of resources using Terraform and add a double digit ID to the end of the resource name.

Terraform Code

Here is the loop code used in an Azure VM Resource block

resource "azurerm_virtual_machine" "vm" {
  count = var.vm_count
  name  = "${var.vm_prefix}${format("%02d", count.index + 1)}
  //remaining terraform code here
}

Let's breakdown the code above

format() is built into Terraform 0.12

"%02d" basic printf syntax for Pad with a 0 up to 2 digits

count.index The current loop iteration

+ 1 The customer wanted their objects to start at 01 instead of 00