Skip to main content

Terraform Numeric Functions

Introduction

Terraform provides a set of built-in functions that help you manipulate and transform values within your infrastructure code. Numeric functions are a specific category that allows you to perform mathematical operations, conversions, and calculations when defining your infrastructure. These functions can be particularly useful when you need to calculate values dynamically, implement scaling logic, or handle numeric transformations.

In this guide, we'll explore Terraform's numeric functions, understand their syntax, and see practical examples of how they can be used in real-world infrastructure configurations.

Basic Numeric Functions

abs - Absolute Value

The abs function returns the absolute (positive) value of a given number.

Syntax:

hcl
abs(number)

Example:

hcl
locals {
negative_value = -42
positive_result = abs(local.negative_value)
}

output "absolute_value_example" {
value = "The absolute value of ${local.negative_value} is ${local.positive_result}"
}

Output:

The absolute value of -42 is 42

ceil - Ceiling Value

The ceil function rounds a decimal number up to the nearest integer.

Syntax:

hcl
ceil(number)

Example:

hcl
locals {
instance_count = 2.1
actual_instances = ceil(local.instance_count)
}

output "ceil_example" {
value = "We need ${local.actual_instances} instances to handle the load"
}

Output:

We need 3 instances to handle the load

floor - Floor Value

The floor function rounds a decimal number down to the nearest integer.

Syntax:

hcl
floor(number)

Example:

hcl
locals {
available_budget = 3.8
server_count = floor(local.available_budget)
}

output "floor_example" {
value = "With the current budget, we can provision ${local.server_count} servers"
}

Output:

With the current budget, we can provision 3 servers

Advanced Numeric Functions

max - Maximum Value

The max function returns the highest value from a list of numbers.

Syntax:

hcl
max(number1, number2, ...)

Example:

hcl
locals {
cpu_usage = [42, 18, 67, 29]
peak_usage = max(local.cpu_usage...)
}

output "max_example" {
value = "Peak CPU usage was ${local.peak_usage}%"
}

Output:

Peak CPU usage was 67%

min - Minimum Value

The min function returns the lowest value from a list of numbers.

Syntax:

hcl
min(number1, number2, ...)

Example:

hcl
locals {
response_times = [120, 85, 210, 95]
fastest_response = min(local.response_times...)
}

output "min_example" {
value = "The fastest response time was ${local.fastest_response}ms"
}

Output:

The fastest response time was 85ms

pow - Power Function

The pow function calculates the result of raising a base number to an exponent.

Syntax:

hcl
pow(base, exponent)

Example:

hcl
locals {
base = 2
exponent = 10
result = pow(local.base, local.exponent)
}

output "pow_example" {
value = "${local.base} raised to the power of ${local.exponent} equals ${local.result}"
}

Output:

2 raised to the power of 10 equals 1024

signum - Sign Function

The signum function determines the sign of a number, returning -1 for negative numbers, 0 for zero, and 1 for positive numbers.

Syntax:

hcl
signum(number)

Example:

hcl
locals {
values = [-10, 0, 15]
signs = [for v in local.values : signum(v)]
}

output "signum_example" {
value = "Signs of ${jsonencode(local.values)} are ${jsonencode(local.signs)}"
}

Output:

Signs of [-10, 0, 15] are [-1, 0, 1]

Conversion Functions

log - Natural Logarithm

The log function calculates the natural logarithm (base e) of a number.

Syntax:

hcl
log(number, base)

Example:

hcl
locals {
value = 100
log_base_10 = log(local.value, 10)
}

output "log_example" {
value = "Log base 10 of ${local.value} is ${local.log_base_10}"
}

Output:

Log base 10 of 100 is 2

parseint - Parse Integer

The parseint function converts a string representation of a number into an actual integer value, with a specified base.

Syntax:

hcl
parseint(string, base)

Example:

hcl
locals {
hex_value = "1a"
decimal_result = parseint(local.hex_value, 16)
}

output "parseint_example" {
value = "Hexadecimal ${local.hex_value} equals decimal ${local.decimal_result}"
}

Output:

Hexadecimal 1a equals decimal 26

Real-World Applications

Example 1: Calculating Auto-Scaling Group Sizes

hcl
variable "expected_users" {
description = "Expected number of users"
type = number
default = 1200
}

locals {
users_per_instance = 150
required_instances = ceil(var.expected_users / local.users_per_instance)
min_instances = max(2, floor(local.required_instances * 0.5))
max_instances = max(local.min_instances, ceil(local.required_instances * 2))
}

resource "aws_autoscaling_group" "web_servers" {
name = "web-servers"
min_size = local.min_instances
max_size = local.max_instances
desired_capacity = local.required_instances

# Other configuration options...
}

output "scaling_settings" {
value = {
min_instances = local.min_instances
max_instances = local.max_instances
desired_instances = local.required_instances
}
}

This example shows how numeric functions can be used to:

  1. Calculate the required number of instances based on expected user load
  2. Set a minimum instance count that's at least 50% of the required number but no less than 2
  3. Set a maximum instance count that can handle up to twice the expected load

Example 2: Resource Sizing Based on Environment

hcl
variable "environment" {
description = "Deployment environment (dev, staging, prod)"
type = string
default = "dev"
}

locals {
# Define environment multipliers
env_multipliers = {
dev = 1
staging = 2
prod = 4
}

# Get the appropriate multiplier or default to 1
size_multiplier = lookup(local.env_multipliers, var.environment, 1)

# Calculate resource sizes
base_memory = 512
memory = local.base_memory * local.size_multiplier
base_cpu = 256
cpu = local.base_cpu * local.size_multiplier
base_disk_size = 20
disk_size = local.base_disk_size * pow(2, floor(log(local.size_multiplier, 2)))
}

resource "aws_ecs_task_definition" "app" {
family = "app-service"
container_definitions = jsonencode([
{
name = "app"
image = "app:latest"
cpu = local.cpu
memory = local.memory
essential = true
# Other container settings...
}
])

# Other task definition settings...
}

output "resource_allocation" {
value = {
environment = var.environment
cpu = local.cpu
memory = local.memory
disk_size = local.disk_size
}
}

This example demonstrates using numeric functions to:

  1. Define environment-specific sizing multipliers
  2. Calculate memory and CPU allocations based on environment
  3. Scale disk size exponentially using logarithmic and power functions

Combining Numeric Functions With Conditional Logic

Terraform's numeric functions become even more powerful when combined with conditional expressions and other function types.

hcl
variable "instances" {
description = "Number of instances to deploy"
type = number
default = 5
}

locals {
instance_count = var.instances

# Calculate cost with volume discount
base_cost_per_instance = 0.10
discount_tiers = {
10 = 0.09, # 10% discount at 10+ instances
20 = 0.08, # 20% discount at 20+ instances
50 = 0.06 # 40% discount at 50+ instances
}

effective_cost = local.instance_count >= 50 ? local.discount_tiers[50] :
local.instance_count >= 20 ? local.discount_tiers[20] :
local.instance_count >= 10 ? local.discount_tiers[10] :
local.base_cost_per_instance

total_hourly_cost = local.instance_count * local.effective_cost
estimated_monthly_cost = ceil(local.total_hourly_cost * 24 * 30)
}

output "cost_estimate" {
value = "Estimated monthly cost for ${local.instance_count} instances: $${local.estimated_monthly_cost}"
}

This example shows:

  1. Calculating costs with tiered pricing
  2. Combining conditional logic with numeric functions
  3. Producing an estimated monthly cost with appropriate rounding

Summary

Terraform's numeric functions provide powerful capabilities for performing calculations and manipulations within your infrastructure code. They enable dynamic sizing, intelligent scaling, and cost optimization directly in your configurations.

Key points to remember:

  • Basic functions like abs, ceil, and floor provide fundamental numeric operations
  • Comparative functions like min and max help with selecting appropriate values
  • Advanced functions like pow and log enable more complex calculations
  • Numeric functions can be combined with conditionals and other Terraform features for dynamic infrastructure sizing

By mastering these functions, you can create more flexible, responsive, and efficient infrastructure code that adapts to changing requirements without manual intervention.

Additional Resources

To further your knowledge of Terraform numeric functions and expressions:

  1. Practice creating auto-scaling configurations that adapt to different workloads
  2. Experiment with cost optimization formulas for different cloud resources
  3. Try implementing dynamic resource allocation based on input variables

Exercises

  1. Create a Terraform configuration that calculates the optimal number of database read replicas based on expected query volume.
  2. Implement a scaling formula that increases resources exponentially as load increases, but with appropriate maximum caps.
  3. Build a module that can automatically right-size cloud resources based on historical usage patterns (represented as input variables).


If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)