Terraform output variables store results from configuration files for later use, enhancing resource management and integration with other tools.
Terraform output variables are a powerful feature that allow you to store the results of expressions from your configuration files for later use. In previous lessons, we covered input variables and reference expressions; output variables complement these by enabling you to retrieve and present important output information after your infrastructure has been provisioned.
Consider a configuration that creates a random pet name using Terraform’s resource definitions. In this example, a resource called random_pet generates a pet name, and an output variable called pet-name captures the generated id. This is especially useful for passing data to other tools or for quick resource verification.Below is an example configuration:
Copy
Ask AI
resource "local_file" "pet" { filename = var.filename content = "My favorite pet is ${random_pet.my-pet.id}"}resource "random_pet" "my-pet" { prefix = var.prefix separator = var.separator length = var.length}output "pet-name" { value = random_pet.my-pet.id desc = ""}
The output block starts with the keyword output followed by the variable name. Inside the block, the value argument is required and uses a reference expression (random_pet.my-pet.id). Although the desc argument is optional, it is a good practice to include a brief description of the output’s purpose.
Use meaningful descriptions for your output variables. This practice enhances code readability and aids in documentation, especially when collaborating with other team members.
You can also retrieve the value of output variables at any time using the terraform output command. Running the command without any arguments lists all outputs:
Copy
Ask AI
$ terraform outputpet-name = Mrs.gibbon
To display an individual output variable, simply specify its name:
Copy
Ask AI
$ terraform output pet-nameMrs.gibbon
Output variables are invaluable for quickly viewing details about your provisioned resources and for integrating with other infrastructure as code tools, ad hoc scripts, or configuration management systems like Ansible.
By incorporating output variables into your Terraform configurations, you can streamline the process of accessing essential resource details and improve the overall management of your infrastructure.