šŸ¶
Terraform

Print Terraform Variables: A Quick Guide & Examples

By Filip on 11/17/2024

Learn different techniques to easily print and view Terraform variable values during your infrastructure deployments.

Print Terraform Variables: A Quick Guide & Examples

Table of Contents

Introduction

When working with Terraform, understanding how to inspect and manage variables is crucial for debugging and ensuring your infrastructure is deployed correctly. This guide provides various techniques to view and work with Terraform variables, including sensitive data, while emphasizing best practices for security.

Step-by-Step Guide

  1. Basic Variable Inspection:

    • After running terraform init, use terraform console.
    • Inside the console, type var.<variable_name> to see its value.
      terraform console
      > var.example_variable
      
  2. Outputting Values:

    • Define output values in your Terraform code to expose specific information.
      output "example_output" {
        value = var.example_variable
      }
    • After applying your configuration, use terraform output to retrieve the value.
      terraform output example_output
      
  3. Debugging During Plan/Apply:

    • Terraform doesn't directly support printing variables during plan or apply if they cause failures.
    • Use TF_LOG=debug environment variable to increase log verbosity, which might offer clues.
    • Consider adding validation rules to your variables to catch issues early.
      variable "example_variable" {
        type = string
        validation {
          condition     = length(var.example_variable) > 0
          error_message = "Variable 'example_variable' cannot be empty."
        }
      }
  4. Sensitive Values:

    • Terraform masks sensitive values by default.
    • To see sensitive values in outputs, use terraform output -json and inspect the JSON output.
    • There's no built-in way to show sensitive values during terraform apply.

Remember: Avoid printing sensitive information directly to the console or logs. Use outputs and appropriate security practices to handle such data.

Code Example

This Terraform code deploys an Azure storage account within a resource group. It defines variables for resource names and location, with default values for convenience. The code includes validation for the resource group name and marks the storage account name as sensitive. Outputs provide access to the deployed resource information, including the resource group location and the storage account name.

# Configure the Azure Provider
terraform {
  required_providers {
    azurerm = {
      source  = "hashicorp/azurerm"
      version = "~> 3.0"
    }
  }
}

# Configure Variables
variable "resource_group_name" {
  type = string
  description = "Name of the resource group"
  validation {
    condition     = length(var.resource_group_name) > 0
    error_message = "Variable 'resource_group_name' cannot be empty."
  }
}

variable "location" {
  type = string
  description = "Azure region to deploy resources"
  default = "westus2"
}

variable "storage_account_name" {
  type = string
  description = "Name of the storage account"
  sensitive = true
}

# Create a Resource Group
resource "azurerm_resource_group" "example" {
  name = var.resource_group_name
  location = var.location
}

# Create a Storage Account
resource "azurerm_storage_account" "example" {
  name                     = var.storage_account_name
  resource_group_name      = azurerm_resource_group.example.name
  location                 = azurerm_resource_group.example.location
  account_tier             = "Standard"
  account_replication_type = "LRS"
}

# Define Outputs
output "resource_group_location" {
  value = azurerm_resource_group.example.location
}

output "storage_account_name" {
  value     = azurerm_storage_account.example.name
  sensitive = true
}

Explanation:

  1. Basic Variable Inspection:

    • After running terraform init, you can use terraform console and var.<variable_name> to inspect values. For example:
      terraform console
      > var.location
      "westus2"
      
  2. Outputting Values:

    • The code defines two outputs: resource_group_location and storage_account_name.
    • After applying the configuration, you can retrieve their values:
      terraform output resource_group_location
      terraform output storage_account_name
      
    • Note that storage_account_name is marked as sensitive and will be masked in the standard output.
  3. Debugging During Plan/Apply:

    • The resource_group_name variable has a validation rule to ensure it's not empty.
    • You can increase log verbosity using TF_LOG=debug to get more information during plan/apply.
  4. Sensitive Values:

    • The storage_account_name variable and output are marked as sensitive.
    • To see the sensitive output value, use terraform output -json and inspect the JSON output.

Remember: This is a basic example. You can adapt it to your specific needs and cloud provider. Always prioritize security and avoid exposing sensitive information directly in logs or console outputs.

Additional Notes

General:

  • Context is Key: The methods for inspecting variables can differ slightly depending on where you are in the Terraform workflow (development, planning, applying, etc.).
  • Variable Scope: Remember that variable values can be influenced by their scope (local, module, workspace). Ensure you're inspecting the variable in the correct context.
  • Interpolation: When inspecting variables within Terraform code, be mindful of string interpolation. Use ${} to embed variable values within strings.

1. Basic Variable Inspection:

  • Alternative to Console: For simple inspections, you can also use terraform output <variable_name> if the variable is also defined as an output.
  • Data Sources: The console is also useful for inspecting data retrieved from data sources.

2. Outputting Values:

  • Descriptive Outputs: Use clear and concise names for your outputs to make them self-documenting.
  • Output Organization: For complex projects, consider grouping related outputs for better readability.

3. Debugging During Plan/Apply:

  • Conditional Expressions: Use conditional expressions in your Terraform code to handle potential edge cases and provide more informative error messages.
  • External Tools: For advanced debugging, consider integrating Terraform with external tools that offer more comprehensive logging and tracing capabilities.

4. Sensitive Values:

  • Secure Storage: Never hardcode sensitive values directly in your Terraform code. Use environment variables, configuration files, or dedicated secret management tools.
  • State File Protection: The Terraform state file can contain sensitive information. Ensure it's stored securely and access is restricted.

Additional Tips:

  • Version Control: Always keep your Terraform code in version control to track changes and revert to previous states if needed.
  • Testing: Implement automated testing for your Terraform code to catch errors early and ensure the reliability of your infrastructure deployments.

Summary

This table summarizes various methods for inspecting and debugging Terraform variables:

| Method | Description

Conclusion

By mastering these techniques, you can effectively manage, inspect, and debug Terraform variables, ensuring smooth and secure infrastructure deployments. Remember to prioritize security by protecting sensitive values and following best practices for handling such data. This comprehensive guide equips you with the knowledge to confidently work with Terraform variables, paving the way for robust and secure infrastructure automation.

References

Were You Able to Follow the Instructions?

šŸ˜Love it!
šŸ˜ŠYes
šŸ˜Meh-gical
šŸ˜žNo
šŸ¤®Clickbait