Terraform – FotD – pathexpand()

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

What is it?

Function name: pathexpand(string)

Returns: Takes a string that should be a file path, and expands the ~ to the current user’s home directory

Example:

# Returns /home/ned/test.txt
output "path_expand_output" {
  value = "${path_expand("~/test.txt")}"
}

Example file:

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

##############################################
# Resources
##############################################
##############################################
# Outputs
##############################################
output "pathexpand_output" {
  value = "${pathexpand(var.pathexpand)}"
}

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

#Windows tests
#Try the home directory
terraform apply -var 'pathexpand=~\'

#Try with a file extension
terraform apply -var 'pathexpand=~\test.txt'

#Try non home path
terraform apply -var 'pathexpand=C:\test.txt'

#Linux tests
#Try with home directory
terraform apply -var 'pathexpand=~/'

#Try with file
terraform apply -var 'pathexpand=~/test.txt'

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

Why use it?

I would assume that this is mostly used by provisioning scripts to return the full path to a file or directory that is sitting in the user’s home directory. Since different operating systems might be using different usernames for connection or deployment, it’s probably important to get back the actual path and not some type of shorthand.

Lessons Learned

The function will expand a path that starts with the ‘~’ character to the current user’s home directory path. If you submit a path that does not begin with a tilda, then it just returns back the same path. The function also handles an empty string by returning the empty string with nothing additional.

Coming up next is the pow() function.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.