slide

Terraform fot d dirname()

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 dirname() function. The example file is on GitHub here.

What is it?

Function name: dirname(path)

Returns: Takes a file path and returns the directory path containing the file, without the file name.

Example:

variable "dirname" {
  default = "/bin/bash"
}

# Returns /bin
output "dirname_output" {
  value = "${dirname(var.dirname)}"
}

Example file:

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

##############################################
# Resources
##############################################
##############################################
# Outputs
##############################################
output "dirname_output" {
  value = "${dirname(var.dirname)}"
}

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

#Windows tests
#Try the root directory
terraform apply -var 'dirname=C:\\'

#Try without a file extension
terraform apply -var 'dirname=C:\\level0\\level1\\level2'

#Try with trailing Windows backslash
terraform apply -var 'dirname=C:\\level0\\level1\\level2\\'

#Try with file
terraform apply -var 'dirname=C:\\level0\\level1\\level2\\file1.txt'

#Linux tests
#Try the root directory
terraform apply -var 'dirname=/'

#Try without a file extension
terraform apply -var 'dirname=/level0/level1/level2'

#Try with trailing forward slash
terraform apply -var 'dirname=/level0/level1/level2/'

#Try with file
terraform apply -var 'dirname=/level0/level1/level2/file1.txt'

#Try empty value
terraform apply -var 'dirname='

Why use it?

Sometimes you need the directory path to put some other files in it. Other times you want to grab all the files from a directory given a particular file’s path. There are a ton of potential uses here. You could even combine this with basename to get the name of the directory holding a file.

Lessons Learned

The function is happy working with either Windows or Linux file paths. For Windows you still need to double-escape the backslash (\) since the backslash is the escape character for HCL. Whether the file has an extension or not doesn’t matter, the function is just looking for the last path separator and returning everything to the left of it. If you leave the slash on the end of the path, the function gives you everything to the left of the slash, as you might expect. If you give it an empty path, then it will give you a “.” representing the current directory, which I find clever.

Coming up next is the distinct() function.