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 indent() function. The example file is on GitHub here.
Function name: indent(spaces, string)
Returns: Takes a string and indents all lines after the first line by the number of spaces specified. Returns the string.
Example:
variable "string" {
default = "My\nmulti-line\nstring"
}
variable "spaces" {
default = 2
}
# Returns "My\n multi-line\n string"
output "indent_output" {
value = "${indent(var.spaces,var.string)}"
}
##############################################
# Function: indent
##############################################
##############################################
# Variables
##############################################
variable "indent" {
default = "This is line one\nThis is line two\nThis is line three"
}
variable "spaces" {
default = 4
}
variable "sourcefile" {
default = "textFile.txt"
}
##############################################
# Resources
##############################################
data "local_file" "source" {
filename = "${var.sourcefile}"
}
##############################################
# Outputs
##############################################
output "indent_output" {
value = "${indent(var.spaces,var.indent)}"
}
output "file_output" {
value = "${indent(var.spaces, data.local_file.source.content)}"
}
Run the following from the indent folder to get example output for a number of different cases:
#We have to get the local resource first
terraform init
#Default values
terraform apply
#negative spaces will crash Terraform
terraform apply -var "spaces=-1"
#Empty string test works just fine
terraform apply -var "indent="
This function is just completely baffling to me. I guess it has something to do with YAML? I don’t know. There are so many possibly useful functions out there, and this seems to be frivolous at best. How about a function hard types a variable? That would be nice. PLEASE let me know if you use this function and why.
There’s not much to learn here. Well, I did learn that if you give the function a negative value for the spaces it will crash Terraform. So that’s bug number three for me! Beyond that, the function does exactly what you would expect.
Coming up next is the index() function. That’s one I’ve used before. Very useful!
Resourcely Guardrails and Blueprints
November 15, 2024
Deploying Azure Landing Zones with Terraform
November 12, 2024
October 18, 2024
What's New in the AzureRM Provider Version 4?
August 27, 2024