# Day05 : Terraform Variables

# Mastering Terraform Variables in AWS: Input, Output, and Local Variables

Day 5 of 30 Days of AWS Terraform – Learn how to use variables effectively to make your Terraform code reusable, maintainable, and environment-agnostic.

## Why Do We Need Variables in Terraform?

In real-world scenarios, you'll manage hundreds or thousands of resources like S3 buckets, VPCs, and EC2 instances.

Problems without variables:

* Repetition of the same values across multiple files
    
* Typos creating inconsistent setups
    
* Hard to maintain when you need to update values everywhere
    

The fix is to define values once using variables and reference them everywhere.

## Terraform Variable Types Flow:

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1764349675134/cc304ea1-322b-4f42-baa5-5e4b986b11ac.png align="center")

Flow 2: Detailed View

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1764349830190/bf5e67ca-ce1a-479d-b2de-e8a801a331b4.png align="center")

## Terraform Variable Types

## 1\. Input Variables

Input variables accept values from the user and are used across the configuration.

Basic example:

```plaintext
variable "environment" {
  default = "dev"
  type    = string
}
```

---

## 2\. Local Variables

Local variables help you create reusable or computed values inside the same module.

Example:

```plaintext
// locals
# locals {
#     // can use like this also 
#  env = var.environment
#  vpc_name = "${local.env}-VPC"
#  instance_name = "${local.env}-Instance"
# }


locals {
  vpc_name = "${var.environment}-VPC"
  instance_name = "${var.environment}-Instance"
}
```

Useful for naming patterns or reusable strings.

---

## 3\. Output Variables

Outputs show values after terraform apply or pass values to other modules.

Example:

```plaintext
output "vpc_id" {
  value = aws_vpc.main.id
}

output "instance_id" {
    value = aws_instance.example.id
}
```

---

## Variable Precedence

Terraform follows this priority order:

1. Default value
    
2. Environment variables
    
3. terraform.tfvars
    
4. CLI -var flag
    

![Important Terraform Concepts- Everything You Should Know](https://k21academy.com/wp-content/uploads/2023/06/TF-variables-1.png align="left")

---

## Complete Working Example (Your Code Added)

Your full code with variables, locals, S3 backend, VPC, EC2, and outputs is inserted here.

```plaintext
terraform {

    backend "s3" {
        bucket = "anjali-gupta-bucket-76"
        key    = "terraform.tfstate"
        region = "eu-north-1"
        use_lockfile = true
    }

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 6.0"
    }
  }
}

provider "aws" {
  region = "eu-north-1"
}

variable "environment" {
  type        = string
  default     = "dev"
}

variable "region" {
  type        = string
  default     = "eu-north-1"
}

locals {
  vpc_name = "${var.environment}-VPC"
  instance_name = "${var.environment}-Instance"
}

resource "aws_s3_bucket" "first_bucket" {
  bucket = "anjali-gupta-bucket-76"
  region = var.region

  tags = {
    Name        = "My bucket"
    Environment = var.environment
  }
}

resource "aws_vpc" "sample" {
    cidr_block = "10.0.1.0/24"
    region = var.region
    tags = {
      Environment = var.environment
      Name = local.vpc_name
    } 
}

resource "aws_instance" "example" {
  ami           = "resolve:ssm:/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64"
  instance_type = "t2.micro"
  region        = var.region

  tags = {
    Environment = var.environment
    Name = local.instance_name
  }
}

output "instance_id" {
    value = aws_instance.example.id
}

output "vpc_id" {
    value = aws_vpc.sample.id
}
```

---

## Commands to Run

```plaintext
terraform init
terraform plan
terraform apply --auto-approve
terraform output
terraform destroy --auto-approve
```

---

## Best Practices Checklist

Use input variables for environment-specific values  
Use local variables for naming conventions  
Define outputs for important resource IDs  
Store defaults in terraform.tfvars  
Use CLI -var for sensitive values  
Destroy test resources after practice

## **Common Errors & Solutions**

| **Error** | **Cause** | **Solution** |
| --- | --- | --- |
| `invalid resource type` | Wrong resource name | [Check AWS Provider Docs](https://registry.terraform.io/providers/hashicorp/aws/latest/docs) <sup>s</sup> |
| [`AMI invalid`](https://registry.terraform.io/providers/hashicorp/aws/latest/docs) | [Wrong AMI ID](https://registry.terraform.io/providers/hashicorp/aws/latest/docs) | [Use valid AMI](https://registry.terraform.io/providers/hashicorp/aws/latest/docs) from AWS [console or docs](https://registry.terraform.io/providers/hashicorp/aws/latest/docs) <sup>s</sup> |
| [`Permission denie`](https://registry.terraform.io/providers/hashicorp/aws/latest/docs)`d` | IAM lacks [permissions](https://registry.terraform.io/providers/hashicorp/aws/latest/docs) | [Add EC2/VPC permissions <sup>s</sup>](https://registry.terraform.io/providers/hashicorp/aws/latest/docs) |
| [`v`](https://registry.terraform.io/providers/hashicorp/aws/latest/docs)`ariable not found` | Wrong pr[ecedence](https://registry.terraform.io/providers/hashicorp/aws/latest/docs) | [Check](https://registry.terraform.io/providers/hashicorp/aws/latest/docs) var[iable definition](https://registry.terraform.io/providers/hashicorp/aws/latest/docs) & preced[ence <sup>s</sup>](https://registry.terraform.io/providers/hashicorp/aws/latest/docs) |

### Video:

%[https://youtu.be/V-2yC39BONc?si=_4Di4j-mRT31X63K] 

## **Key Takeaway**

Variables transform Terraform from script to **infrastructure factory**. Define once, deploy everywhere. Environment promotion? Just swap `tfvars` files. 💪

**Practice challenge**: Create input vars for region/environment, locals for resource names, outputs for IDs. Run precedence tests!

Huge thanks to **Piyush Sachdeva** for the crystal-clear hands-on demo!

#30DaysOfAWSTerraform Day 5 complete!
