> ## Documentation Index
> Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Introduction

> Guide to Terraform input variables explaining declaration, types, value provisioning methods, and best practices for reusable environment-agnostic configurations and secure handling of sensitive data

In this lesson we cover Terraform variables: how to declare them, how they make configurations reusable and environment-agnostic, and the common patterns for supplying values.

Variables let you parameterize your Terraform configuration instead of hard-coding values. This makes code easier to reuse across environments (dev, staging, prod), simplifies CI/CD automation, and reduces duplication.

Agenda for this lesson:

1. Define input variables in Terraform
   * Externalize values such as region, resource names, SKUs, subscriptions, and environment-specific settings.

2. Understand the `variable` block
   * Learn the structure and purpose of the `variable` block, including metadata such as `type`, `default`, and `description`. Note that the variable's `name` is declared in the block header (e.g., `variable "name" { ... }`) rather than as a field inside the block.

3. Supply values to variables
   * Explore ways to provide variable values: `.tfvars` files, command-line arguments (`-var` and `-var-file`), environment variables, and interactive prompts.

4. Work with Terraform variable types
   * Review primitive types (`string`, `number`, `bool`) and complex types (`list`, `map`, `object`) with usage examples.

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/ULo-8LXeWHtPzvMr/images/Terraform-On-Azure/Variables/Introduction/terraform-input-variables-agenda.jpg?fit=max&auto=format&n=ULo-8LXeWHtPzvMr&q=85&s=005795e1248b5f657e9e59cc322755fe" alt="The image presents an agenda with four points about using input variables in Terraform configurations, including defining variables, understanding variable blocks, setting variable values, and identifying data types. The agenda is visually organized with numbered markers and a gradient background." width="1920" height="1080" data-path="images/Terraform-On-Azure/Variables/Introduction/terraform-input-variables-agenda.jpg" />
</Frame>

<Callout icon="lightbulb" color="#1CB2FE">
  Use variables to decouple environment-specific data from configuration. This enables the same Terraform codebase to provision different environments by supplying different variable values.
</Callout>

We will now start by looking at how to declare input variables and the structure of a `variable` block.

## Declaring input variables

A `variable` block defines an input variable for a module or root module. The block header contains the variable name; attributes inside define metadata and constraints.

Basic example:

```hcl theme={null}
variable "location" {
  description = "Azure region where resources will be deployed"
  type        = string
  default     = "eastus"
}
```

Key attributes:

* `description` — human-readable context for the variable
* `type` — the data type (e.g., `string`, `number`, `bool`, `list(string)`, `map(string)`, `object({...})`)
* `default` — optional value used if none is supplied
* `sensitive` — optional boolean to mark values as sensitive (prevents them from being shown in CLI output)

Example showing a mix of types, including `map` and `object`:

```hcl theme={null}
variable "tags" {
  description = "Tags applied to resources"
  type        = map(string)
  default = {
    environment = "dev"
    owner       = "team-a"
  }
}

variable "vm_sizes" {
  description = "Allowed VM SKUs for this environment"
  type        = list(string)
  default     = ["Standard_B1s", "Standard_B2s"]
}

variable "service_config" {
  description = "Configuration object for the service"
  type = object({
    sku               = string
    capacity          = number
    enable_monitoring = bool
  })
  default = {
    sku               = "standard"
    capacity          = 2
    enable_monitoring = true
  }
}
```

Referencing variables inside your configuration uses the `var` namespace:

```hcl theme={null}
resource "azurerm_resource_group" "rg" {
  name     = "rg-${var.service_config.sku}"
  location = var.location
  tags     = var.tags
}
```

## Variable types — quick reference

| Type            | Description                             | Example                                       |
| --------------- | --------------------------------------- | --------------------------------------------- |
| `string`        | Simple text                             | `variable "name" { type = string }`           |
| `number`        | Numeric values                          | `variable "replicas" { type = number }`       |
| `bool`          | True / false                            | `variable "enabled" { type = bool }`          |
| `list(...)`     | Ordered list                            | `list(string)` — `["a", "b"]`                 |
| `map(...)`      | Key/value collection                    | `map(string)` — `{ env = "dev" }`             |
| `object({...})` | Structured object with typed attributes | `object({ sku = string, capacity = number })` |

When providing examples or inline values that include braces (`{}`) or double-curly syntax, wrap them in backticks to avoid MDX parsing issues. For example: `` `[{ "object": "person", "bbox": [0,0,10,10] }]` ``.

## Ways to supply variable values

Terraform supports multiple ways to provide values for input variables. Choose the method that fits your workflow (local testing, automation, CI/CD, or secret management).

| Method                | Use case                                                       | Example                                          |
| --------------------- | -------------------------------------------------------------- | ------------------------------------------------ |
| `.tfvars` file        | Grouped values per environment (recommended for repeated runs) | `terraform.tfvars` or `prod.tfvars`              |
| `-var-file`           | Explicitly pass a tfvars file on the CLI                       | `terraform apply -var-file="prod.tfvars"`        |
| `-var`                | Quick one-off values                                           | `terraform apply -var='location=westus2'`        |
| Environment variables | CI/CD or secrets via env vars                                  | `export TF_VAR_location="westus2"`               |
| Interactive prompt    | When no default is provided and automation isn't used          | Terraform prompts for missing required variables |

Example `terraform.tfvars`:

```hcl theme={null}
resource_name = "my-rg"
location      = "westus2"
```

Environment variable example:

```bash theme={null}
export TF_VAR_location="westus2"
terraform apply
```

CLI example:

```bash theme={null}
terraform apply -var='location=westus2' -var='resource_name=my-rg'
```

<Callout icon="warning" color="#FF6B6B">
  Do not commit secrets (passwords, API keys) into `.tfvars` files stored in version control. Use a secrets manager or mark variables `sensitive = true` and supply values via secure pipelines or Terraform Cloud/Enterprise variable sets.
</Callout>

## Best practices

* Prefer `tfvars` files for environment-level defaults and `-var-file` to select them at runtime.
* Use typed variables (`list(...)`, `map(...)`, `object(...)`) to validate inputs and catch mistakes early.
* Document variable `description` values to aid collaborators and automation.
* Avoid hard-coding environment-specific values inside modules—pass them as inputs to keep modules reusable.

## Links and references

* [Terraform Input Variables — HashiCorp Documentation](https://developer.hashicorp.com/terraform/language/values/variables)
* [Best practices for using Terraform variables](https://developer.hashicorp.com/terraform/tutorials/local-development/terraform-modules)

We will next walk through concrete examples of using variables in modules and how to organize `tfvars` files per environment.

<CardGroup>
  <Card title="Watch Video" icon="video" cta="Learn more" href="https://learn.kodekloud.com/user/courses/terraform-on-azure/module/6909fa70-4ccc-40c3-a918-1188673d8985/lesson/fb6658ce-0f7a-4c42-b3a7-9cdd5dd21331" />
</CardGroup>
