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.
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")}"
}
##############################################
# 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='
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.
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.
What's New in the AzureRM Provider Version 4?
August 27, 2024
Debugging the AzureRM Provider with VSCode
August 20, 2024
State Encryption with OpenTofu
August 1, 2024
July 24, 2024