Terraform Variables Comparisons Conditions

0

 Lesson 1

Topic: Terraform Variables + Comparisons + Conditions

You will learn:

  1. Types of variables

  2. Small definitions

  3. For each variable → comparison examples

  4. For each variable → conditional (if-else) examples


1. Terraform Variable Types (Simple Definitions)

Variable Type Small Definition
string Text value like "dev", "prod"
number Numeric value like 10, 3.14, 100
bool True/False values
list Ordered collection ["dev", "stage"]
map Key-value pairs { size = "large" }
object Structured group of attributes
set Unique list with no duplicates
tuple List with fixed types in order

Now let’s learn them one by one with comparison operators and conditions.


🔥 2. STRING VARIABLE

Define string variable

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

String Comparisons

Comparison Example
Equal var.env == "prod"
Not Equal var.env != "prod"

Example local variable:

locals {
is_production = var.env == "prod"
}

String Conditions (if-else)

Use ternary operator:

locals {
instance_type = var.env == "prod" ? "t3.large" : "t3.micro"
}

🔥 3. NUMBER VARIABLE

Define:

variable "cpu"{
type = number
default = 2
}

Number Comparisons

Comparison Example
Greater than var.cpu > 2
Less than var.cpu < 4
>= var.cpu >= 4
<= var.cpu <= 8
Equal var.cpu == 4

Number Conditions (if-else)

Example: choose instance based on CPU:

locals {
instance_type = var.cpu >= 4 ? "m5.large" : "t3.medium"
}

Example: limit CPU:

locals {
safe_cpu = var.cpu > 10 ? 10 : var.cpu
}

🔥 4. BOOLEAN VARIABLE

Define:

variable "enable_logs" {
type = bool
default = true
}

Boolean Comparisons

You can compare with true / false

locals {
logging_enabled = var.enable_logs == true
}

OR simply:

locals {
logging_enabled = var.enable_logs
}

Boolean Conditions

Enable resource only when boolean is true:

resource "aws_s3_bucket" "logs" {
count = var.enable_logs ? 1 : 0
bucket = "log-bucket"
}

Another example:

locals {
log_level = var.enable_logs ? "INFO" : "NONE"
}

🔥 5. LIST VARIABLE

Define:

variable "regions" {
type = list(string)
default = ["us-east-1", "us-west-2"]
}

List Comparisons

Check if item exists in list:

locals {
contains_us_east = contains(var.regions, "us-east-1")
}

List Conditions (if-else)

Pick first region if more than one:

locals {
primary_region = length(var.regions) > 1 ? var.regions[0] : "us-east-1"
}

Pick instance size based on count:

locals {
region_size = length(var.regions) >= 3 ? "large" : "small"
}

🔥 6. MAP VARIABLE

Define:

variable "sizes" {
type = map(string)
default = {
dev = "t3.micro"
prod = "t3.large"
}
}

Map Comparisons

Check if key exists:

locals {
has_prod = contains(keys(var.sizes), "prod")
}

Map Conditions

Select instance based on environment:

locals {
instance_type = lookup(var.sizes, var.env, "t3.small")
}

🔥 7. OBJECT VARIABLE

Define:

variable "app_config" {
type = object({
cpu = number
memory = number
tier = string
})
default = {
cpu = 2
memory = 2048
tier = "standard"
}
}

Object Comparisons

Compare fields:

locals {
is_high_memory = var.app_config.memory >= 4096
}

Object Conditions

Set pricing tier dynamically:

locals {
price_tier = var.app_config.cpu > 4 ? "premium" : "basic"
}

🔥 8. SET VARIABLE

Define:

variable "unique_tags" {
type = set(string)
default = ["app", "backend"]
}

Set Comparisons

Check membership:

locals {
has_backend = contains(var.unique_tags, "backend")
}

Set Conditions

Choose deployment type:

locals {
deploy_type = contains(var.unique_tags, "critical") ? "high" : "normal"
}

🔥 9. TUPLE VARIABLE

Define:

variable "app_info" {
type = tuple([string, number, bool])
default = ["webapp", 3, true]
}

Tuple Comparisons

locals {
replicas_high = var.app_info[1] > 2
}

Tuple Conditions

locals {
app_mode = var.app_info[2] ? "active" : "passive"
}

1. Difference Between map and object in Terraform

MAP — Key–Value Pair (Flexible)

Definition (Simple):

A map is a collection of key–value pairs where all values must have the same type.

Example:

variable "instance_sizes" {
type = map(string)
default = {
dev = "t3.micro"
prod = "t3.large"
test = "t3.small"
}
}

✔ All values are string
✔ Keys must be strings, but number of keys is flexible
✔ Useful for lookup tables

Lookup Example:

locals {
instance_type = lookup(var.instance_sizes, "prod", "t3.micro")
}

OBJECT — Structured Data Type (Strict)

Definition (Simple):

An object is like a record or struct —
You define multiple attributes, each with specific types.

Example:

variable "app_config" {
type = object({
cpu = number
memory = number
region = string
})

default = {
cpu = 4
memory = 2048
region = "us-east-1"
}
}

✔ Each attribute has different types
✔ Structure is strict — user must follow exact keys & types
✔ Useful for complex configurations

Access Example:

locals {
high_memory = var.app_config.memory > 4096
}

🔥 MAP vs OBJECT — Quick Differences Table

Feature MAP OBJECT
Structure Flexible Strict
Keys Unlimited Fixed & predefined
Value types All same type Each attribute has its own type
Use case Lookup tables Complex structured config
Example { env="prod" } { cpu=2, region="us-east-1" }

🎯 2. Difference Between variable and locals in Terraform

Let’s learn like an instructor:


VARIABLES — Input from Outside

Definition (Simple):

variable is used to take input from users, CLI, tfvars file, environment variables, etc.

They make Terraform dynamic and configurable.

Example:

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

Users can override:

terraform apply -var "env=prod"

Use Case:

  • Input values

  • Environment selection

  • Customization from outside


LOCALS — Internal Helper Values

Definition (Simple):

locals are internal computation helpers used only within the module.
They cannot be passed from outside.

They are like temporary variables inside your Terraform code.

Example:

locals {
instance_type = var.env == "prod" ? "t3.large" : "t3.micro"
}

Use Case:

  • Calculated values

  • If–else logic

  • Repeated expressions

  • Clean code formatting


🔥 VARIABLES vs LOCALS — Quick Difference Table

Feature VARIABLES LOCALS
Who sets the value? User / CLI / tfvars Terraform module itself
Can user override? Yes No
Purpose External configuration Internal calculations
Example var.env local.instance_type
Can depend on? Inputs, defaults Variables or other locals
Ideal usage Inputs Derived values

🎉 Final Instructor Summary

map

Good for lookup tables. All values same type. Keys flexible.

object

Good for structured configs. Keys fixed. Values can be diff types.

variable

Input from outside. Overrides allowed.

locals

Internal computed values. No override allowed.


🎉 FINAL OUTPUT: Everything Together

You now know:
✔ all Terraform variable types
✔ definition of each
✔ comparison operators for each
✔ if-else conditions for each

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to Top