In today’s blog post, we will learn operators in terraform used to perform calculations, comparisons, or combining conditions to create dynamic configurations. Operators in Terraform allow you to manipulate values, compare them, and build complex logical expressions within your configuration files.
- Dynamic Sizing: Calculating resource capacities based on inputs.
- Conditional Logic: Enabling or disabling resources, or setting attributes based on specific conditions.
- Data Transformation: Adjusting numerical values or combining boolean outcomes.
- Validation: Ensuring inputs meet certain criteria.
Terraform supports a familiar set of arithmetic, equality, comparison, and logical operators, similar to those found in many programming languages, enabling you to add a layer of programmatic control to your terraform code.
Arithmetic Operators
Arithmetic operators perform mathematical calculations on numerical values. They are commonly used to derive resource sizes, counts, or network parameters dynamically.
Operator | Description | Example |
---|---|---|
+ | Addition | 5 + 3 |
- | Subtraction | 10 - 4 |
* | Multiplication | 2 * 6 |
/ | Division | 15 / 3 |
% | Modulo | 10 % 3 (remainder of 10/3) |
# main.tf
variable "base_instances" {
description = "Number of base instances."
type = number
default = 2
}
variable "extra_instances" {
description = "Number of extra instances for peak load."
type = number
default = 1
}
variable "network_prefix_length" {
description = "Base network prefix length."
type = number
default = 24
}
# Addition
output "total_instances" {
description = "Total number of instances."
value = var.base_instances + var.extra_instances
# Outcome: 3
}
# Multiplication
output "max_connections_per_instance" {
description = "Maximum connections per instance."
value = var.base_instances * 100
# Outcome: 200
}
# Subtraction and Division
output "available_network_bits" {
description = "Number of available bits for host addresses."
value = 32 - var.network_prefix_length
# Outcome: 8
}
# Modulo
output "is_odd_instance_count" {
description = "Checks if total instances is an odd number."
value = (var.base_instances + var.extra_instances) % 2 == 1
# Outcome: true (3 % 2 == 1, so 1 == 1 is true)
}
Explanation of the code:
- Arithmetic operators are used to calculate
total_instances
,max_connections_per_instance
, andavailable_network_bits
based on input variables. - The modulo operator (
%
) is demonstrated to check if a number is odd, which can be useful for conditional logic (e.g., distributing resources evenly).
Equality and Comparison Operators
These operators are used to compare two values, resulting in a boolean (true
or false
) outcome. They are core component for conditional logic and validation.
Operator | Description | Example |
---|---|---|
== | Equal to | "dev" == "dev" |
!= | Not equal to | 10 != 5 |
> | Greater than | 7 > 3 |
>= | Greater than or equal to | 5 >= 5 |
< | Less than | 2 < 4 |
<= | Less than or equal to | 8 <= 8 |
# main.tf
variable "environment" {
description = "The deployment environment."
type = string
default = "staging"
}
variable "min_cpu_cores" {
description = "Minimum required CPU cores."
type = number
default = 4
}
variable "actual_cpu_cores" {
description = "Actual CPU cores for the instance."
type = number
default = 8
}
# Equality
output "is_production_env" {
description = "Is the environment 'production'?"
value = var.environment == "production"
# Outcome: false
}
# Not Equal
output "is_not_dev_env" {
description = "Is the environment not 'dev'?"
value = var.environment != "dev"
# Outcome: true
}
# Greater Than
output "cpu_meets_min_requirement" {
description = "Does actual CPU meet minimum requirement?"
value = var.actual_cpu_cores > var.min_cpu_cores
# Outcome: true
}
# Less Than or Equal To
output "is_cost_optimized_instance" {
description = "Is the instance small enough to be cost optimized (e.g., <= 4 cores)?"
value = var.actual_cpu_cores <= 4
# Outcome: false
}
Explanation of the code:
- Equality (
==
,!=
) is used to compare string values (environment
) and numeric values. - Comparison operators (
>
,<=
) are used to check if numerical requirements are met, which often drives conditional resource properties.
Logical Operators
Logical operators combine boolean expressions and return a boolean result. They are essential for building complex conditions that control resource creation, modification, or validation.
Operator | Description | Example |
---|---|---|
&& | AND | true && false |
|| | OR | true || false |
! | NOT | !true |
# main.tf
variable "is_maintenance_window" {
description = "Boolean indicating if currently in maintenance window."
type = bool
default = false
}
variable "is_dr_test" {
description = "Boolean indicating if a disaster recovery test is active."
type = bool
default = false
}
variable "instance_health_status" {
description = "Health status of the instance (e.g., 'healthy', 'unhealthy')."
type = string
default = "unhealthy"
}
# Logical AND (&&)
output "can_deploy_app" {
description = "Can the application be deployed (not maintenance AND not DR test)?"
value = !var.is_maintenance_window && !var.is_dr_test
# Outcome: true (false is not true AND false is not true => true AND true => true)
}
# Logical OR (||)
output "alert_critical_issue" {
description = "Should a critical alert be raised (unhealthy OR DR test active)?"
value = var.instance_health_status == "unhealthy" || var.is_dr_test
# Outcome: true ("unhealthy" == "unhealthy" is true, so true || false is true)
}
# Logical NOT (!)
output "is_not_healthy" {
description = "Is the instance not healthy?"
value = !(var.instance_health_status == "healthy")
# Outcome: true
}
Explanation of the code:
- The
&&
(AND) operator ensures both conditions must be true for the overall expression to be true, used forcan_deploy_app
. - The
||
(OR) operator means if at least one condition is true, the overall expression is true, used foralert_critical_issue
. - The
!
(NOT) operator inverts a boolean value, useful foris_not_healthy
.
Conditional Operator (? :
)
The conditional operator (also known as the ternary operator) allows you to define a value based on a boolean condition. They are similar to if-then-else
logic available in other programming languages.
# main.tf
variable "environment_type" {
description = "Type of environment (e.g., 'prod', 'dev')."
type = string
default = "dev"
}
output "instance_size_by_env" {
description = "Instance size based on environment type."
value = var.environment_type == "prod" ? "t3.large" : "t2.micro"
# Outcome: "t2.micro"
}
# Complex condition with conditional operator
output "security_group_ingress_port" {
description = "Port to open in security group."
value = var.environment_type == "prod" ? (var.is_maintenance_window ? 8080 : 443) : 80
# Outcome: 80 (since environment_type is "dev", the else branch is taken)
}
Explanation of the code:
- The
? :
operator evaluates the condition before?
. Iftrue
, it returns the value after?
. Iffalse
, it returns the value after:
. - It is a powerful tool for dynamically setting resource attributes like
instance_size_by_env
orsecurity_group_ingress_port
based on varying conditions.
Operator Precedence
Like in mathematics, operators in Terraform have a defined precedence, which determines the order in which operations are evaluated. When in doubt, or to improve readability, use parentheses ()
to explicitly group expressions and control the evaluation order.
The general order of precedence (from highest to lowest) is:
- Dot and Bracket Access:
.
,[]
- Arithmetic:
*
,/
,%
(multiplicative) then+
,-
(additive) - Comparisons:
==
,!=
,<
,<=
,>
,>=
- Logical NOT:
!
- Logical AND:
&&
- Logical OR:
||
- Conditional:
? :
Example: a && b || c
is evaluated as (a && b) || c
due to &&
having higher precedence than ||
. Example: 5 + 3 * 2
is evaluated as 5 + (3 * 2)
which is 11
.
Best Practices for Using Operators
- Readability: For complex expressions, use parentheses
()
to explicitly group operations. This improves clarity, even if it matches default precedence. - Booleans for Conditions: Ensure the expressions used with logical and conditional operators resolve to boolean (
true
orfalse
) values. - Type Consistency: Be mindful of the types of values you are operating on. Terraform often handles type conversions implicitly, but explicit understanding helps prevent unexpected behavior (e.g., comparing strings to numbers).
- Validation Rules: Operators are excellent for creating
validation
rules for input variables, ensuring that values passed to your modules meet specific criteria (e.g.,min_cpu_cores > 0
). - Local Values: For highly complex calculations or conditions, define intermediate results using
locals
blocks. This breaks down complexity and improves maintainability.
Conclusion
Operators are the building blocks in Terraform, allowing you to move beyond static configurations and introduce dynamic, conditional, and calculated logic into your terraform Code. By mastering arithmetic, equality, comparison, and logical operators, along with the conditional operator, you gain the ability to create more dynamic and reusable configurations. Thoughtful application of these operators ensures your Terraform configurations reflect the desired state of your cloud resources under various conditions.
Author

Experienced Cloud & DevOps Engineer with hands-on experience in AWS, GCP, Terraform, Ansible, ELK, Docker, Git, GitLab, Python, PowerShell, Shell, and theoretical knowledge on Azure, Kubernetes & Jenkins.
In my free time, I write blogs on ckdbtech.com