Thursday, November 19, 2020

Snake Case in Terraform

 How do you convert from camel case to snake case in Terraform? How do you go from "MyProjectName" to "my-project-name"? Here is a simple solution:

locals {
# convert to snake case
snake_case_name = lower(replace(var.camel_case_name
"/(\\w)([A-Z])/""$${1}_$2"))
}

Basically, you add an underscore before each capital letters. The strange syntax with the double dollars is a workaround to a strange bug in Terraform, which considers '$1_' as meaning something. 

This line works well if you have simple cases like "MyDatabaseName". However, I had to handle some more complex cases, like "ABCProject", or "ProjectABC". In that case, you have to work a bit more.

My solution was to implement two replace functions:

  • One for a series of capital letters anywhere in my word. I insert an underscore only if my capital letter is followed by a lower case.
  • One for a series of capital letters at the end of my word. I insert an underscore before the first letter of the series.
This gives this more complex command:

locals {
  # convert to snake case
  snake_case_name lower(replace(replace(var.camel_case_name,
      # add underscore before capital letter followed by lowcase
      "/(\\w)([A-Z][a-z])/""$${1}_$2"),
      # add underscore before capital letters at the end of the word
      "/([A-Z]+)$/""_$1"))
}