LibraryVariables and Outputs

Variables and Outputs

Learn about Variables and Outputs as part of Terraform Infrastructure as Code Mastery

Terraform Variables and Outputs: Dynamic Infrastructure

Terraform's power lies in its ability to manage infrastructure as code. To make your configurations flexible and reusable, understanding variables and outputs is crucial. Variables allow you to parameterize your Terraform code, making it adaptable to different environments and needs. Outputs, on the other hand, expose important information about your infrastructure after it's been provisioned.

Understanding Terraform Variables

Variables are placeholders in your Terraform configuration that can be set when Terraform is run. They allow you to customize your infrastructure without modifying the core code. This is essential for creating reusable modules and managing sensitive information like API keys or passwords.

Variables make Terraform configurations dynamic and reusable.

Variables act like input parameters for your Terraform code, allowing you to change values without altering the configuration files themselves. This promotes flexibility and reduces duplication.

In Terraform, you declare variables in .tf files using the variable block. Each variable can have a type (like string, number, bool, list, map, object, set), a description, and a default value. When you run Terraform commands like terraform plan or terraform apply, you can provide values for these variables through various methods: command-line flags, environment variables, or variable definition files (.tfvars).

Variable Types and Usage

Terraform supports several data types for variables, each serving a specific purpose. Choosing the correct type ensures data integrity and predictable behavior.

Variable TypeDescriptionExample Usage
StringTextual data.Instance type for a virtual machine (e.g., 't2.micro').
NumberNumeric data (integers or floats).Number of CPU cores for a database server.
BooleanTrue or false values.Enable or disable a feature (e.g., enable_monitoring = true).
ListAn ordered collection of values of the same type.List of IP addresses for a firewall rule.
MapAn unordered collection of key-value pairs, where keys are strings.Tags for a resource (e.g., {'Environment': 'Production', 'Project': 'Web'}).
ObjectA collection of named fields, each with its own type.Configuration for a database connection (e.g., { username = 'admin', password = 'securepassword' }).
SetAn unordered collection of unique values of the same type.A list of unique port numbers.

Providing Variable Values

There are several ways to supply values to your Terraform variables, offering flexibility in how you manage your infrastructure configurations.

The order of precedence for variable assignment is: command-line flags > environment variables > .tfvars files > default values.

  1. Command-line Flags: Use the
    code
    -var
    flag with
    code
    terraform plan
    or
    code
    terraform apply
    . Example:
    code
    terraform apply -var='region=us-east-1'
  2. Environment Variables: Prefix variable names with
    code
    TF_VAR_
    . Example:
    code
    export TF_VAR_region='us-east-1'
  3. Variable Definition Files (
    code
    .tfvars
    )
    : Create files (e.g.,
    code
    production.tfvars
    ,
    code
    staging.tfvars
    ) containing key-value pairs. You can specify these files using the
    code
    -var-file
    flag. Example:
    code
    terraform apply -var-file='production.tfvars'
  4. Interactive Prompt: If a variable doesn't have a default value and isn't provided through other means, Terraform will prompt you to enter it.

Understanding Terraform Outputs

Outputs are used to extract information from your managed infrastructure and display it after Terraform has applied your configuration. This is invaluable for retrieving resource IDs, IP addresses, hostnames, or any other data that might be needed by other systems or for manual reference.

Outputs expose useful information about your provisioned infrastructure.

Outputs are like return values from your Terraform code, providing access to critical details of your deployed resources.

You define outputs in your .tf files using the output block. Each output has a name, a value (which can be a resource attribute or a computed value), and an optional description. After running terraform apply, you can view the defined outputs by running terraform output. This allows you to easily access information like the public IP address of a newly created EC2 instance or the connection string for a database.

Output Values and Attributes

The

code
value
attribute of an output block can reference any attribute of a provisioned resource, or even the values of variables. This makes outputs highly flexible for reporting.

Consider a scenario where you provision an AWS EC2 instance. You'd define an output to display its public IP address. The value would reference the public_ip attribute of the aws_instance resource. This allows you to easily retrieve the IP after the instance is running.

resource "aws_instance" "example" {
  ami           = "ami-0abcdef1234567890"
  instance_type = "t2.micro"

  tags = {
    Name = "HelloWorld"
  }
}

output "instance_public_ip" {
  description = "The public IP address of the EC2 instance."
  value       = aws_instance.example.public_ip
}

When terraform apply completes, running terraform output instance_public_ip would display the IP address.

📚

Text-based content

Library pages focus on text content

Best Practices for Variables and Outputs

Adhering to best practices ensures your Terraform configurations are robust, secure, and maintainable.

Why is it important to use variables for sensitive information like API keys?

Using variables for sensitive information prevents them from being hardcoded directly into your Terraform configuration files, which are often stored in version control systems. This enhances security by keeping secrets out of your codebase.

  1. Use Descriptions: Always provide clear descriptions for your variables and outputs. This helps other users (and your future self) understand their purpose and expected values.
  2. Define Variable Types: Explicitly define the type for each variable to ensure data integrity and prevent unexpected behavior.
  3. Avoid Hardcoding: Never hardcode values that might change or are sensitive. Use variables instead.
  4. Use
    code
    .tfvars
    for Environment-Specific Values
    : Create separate
    code
    .tfvars
    files for different environments (dev, staging, prod) to manage configurations cleanly.
  5. Output Essential Information: Ensure your outputs provide the necessary data for interacting with or monitoring your infrastructure.

Learning Resources

Terraform Variables - Official Documentation(documentation)

The official HashiCorp documentation detailing how to declare, use, and manage variables in Terraform.

Terraform Outputs - Official Documentation(documentation)

Comprehensive guide from HashiCorp on defining and using outputs to expose information from your infrastructure.

Terraform Input Variables Tutorial(tutorial)

A hands-on tutorial from HashiCorp demonstrating how to use input variables to customize Terraform configurations for AWS.

Terraform Output Values Tutorial(tutorial)

A practical tutorial from HashiCorp showing how to use output values to display information about your provisioned AWS resources.

Understanding Terraform Variables and Outputs - HashiCorp Learn(documentation)

An introductory overview of variables and outputs, explaining their role in creating reusable Terraform modules.

Terraform Variable Types Explained(video)

A clear video explanation of the different data types available for Terraform variables and how to use them effectively.

Terraform Outputs: How to Display Information(video)

A video tutorial demonstrating the practical application of Terraform outputs to retrieve and display infrastructure details.

Terraform Best Practices: Variables and Outputs(blog)

A blog post discussing best practices for using variables and outputs to create maintainable and secure Terraform code.

Terraform Variable Precedence(documentation)

Details the order in which Terraform evaluates variable assignments from different sources.

Terraform Object and Tuple Types(documentation)

Explains the more complex object and tuple variable types, useful for structured data.