slide

Terraform fot d basename()

Ned Bellavance
2 min read

Cover

This is part of an ongoing series of posts documenting the built-in interpolation functions in Terraform. For more information, check out the beginning post. In this post I am going to cover the basename() function. The example file is on GitHub here.

What is it?

Function name: basename(string) Returns: The basename function returns the last portion of a file path. Example:

variable "basic_path" {
  default = "/usr/bin"
}

# Returns bin
output "basic_path" {
  value = "${basename(var.basic_path)}"
}

Example file:

##############################################
# Function: basename
##############################################
##############################################
# Variables
##############################################
variable "basename" {}

##############################################
# Resources
##############################################
##############################################
# Outputs
##############################################
output "basename_output" {
  value = "${basename(var.basename)}"
}

Run the following from the basename folder to get example output for a number of different cases:

terraform apply -var 'basename=C:\\'
terraform apply -var 'basename=C:\\level0\\level1\\level2'
terraform apply -var 'basename=C:\\level0\\level1\\level2\\'
terraform apply -var 'basename=C:\\level0\\level1\\level2\\file1.txt'
terraform apply -var 'basename=/'
terraform apply -var 'basename=/level0/level1/level2'
terraform apply -var 'basename=/level0/level1/level2/'
terraform apply -var 'basename=/level0/level1/level2/file1.txt'
terraform apply -var 'basename='

Why use it?

If you really need to extract a file name from a long path, or just the directory name at the end of the path, this is really helpful.

Lessons learned

From my testing I determined a few things. You need to double escape any backslash characters for Windows files since ‘\’ is the escape character that Terraform uses for adding newlines and other special characters to a string. The function will return the last file name or folder name on either Linux or Windows file system paths. If the path is just the root of the file system then you’ll get back the root ‘/’. If you leave a trailing slash on the value, such as /level0/level1/ it will be ignored and level1 will be returned. I did try a 256 character directory with a 256 character filename to see if basename would choke, but it just shrugged like Whatevs. I also tried an empty string which surprisingly gave me a ‘.’ as output. Which I guess makes sense since the ‘.’ refers to the current directory.

Coming up next is base64decode().