Course contentsShow
← Cloud and Infrastructure
Lesson 755 of 2,98914. Terraform FundamentalsFree lesson

Variable Declaration Syntax

Learn how to declare variables using the variable block with type and description.

Variable Declaration Syntax

You'll learn how to formally define input variables in Terraform using the variable block.

Now that you understand variables conceptually, it's time to declare them properly in your Terraform configuration. A variable declaration tells Terraform "I expect this input to be provided" and defines its characteristics.

The variable Block Structure

Variables are declared using the variable block, followed by a unique name. Think of this like filling out a form that describes what kind of input you're expecting:

variable "instance_type" {
  type        = string
  description = "The EC2 instance type to provision"
}

This declaration says: "I need a variable called instance_type, it must be a string, and here's what it's for."

Core Variable Attributes

type - Specifies what kind of data this variable accepts (like string, number, bool, list, or map). This acts as a safety check, preventing someone from accidentally passing a number when you need text.

description - A human-readable explanation of the variable's purpose. While optional, it's invaluable documentation for anyone using your configuration, including your future self.

variable "enable_monitoring" {
  type        = bool
  description = "Enable CloudWatch monitoring for the instance"
}

variable "tag_environment" {
  type        = string
  description = "Environment name to apply as a tag (e.g., dev, staging, prod)"
}

Think of variable declarations as creating labeled input slots on a control panel—each slot is shaped to accept only the right kind of data and has a label explaining its purpose.

Key Takeaway: Variable declarations use the variable block with a name, type to enforce data constraints, and description to document purpose—creating a clear contract for inputs your configuration expects.