DEV Community

Nandan K
Nandan K

Posted on

Terraform type constraints or variable types

Day 7 of #30daysofawsterraform challenge

Today I come across different types of variables in Terraform.

$ What is variables in Terraform?
Variables in Terraform are like placeholders that store values, this makes your code reusable across environments (dev, staging, prod) and teams.

$ Types:

Basic Types:

  1. String - Text values Eg: variable "environment" { default = "dev" type = string

Access using:
Environment = var.environment

  1. Number - Numeric values (integers and floats) Eg: variable "instance_count" { description = "Number of instances to create" type = number }

Access using:
count = var.instance_count

  1. Bool - Boolean values (true/false)
    Eg:
    variable "monitoring_enabled" {
    description = "Enabled detailed monitoring for EC2 instance"
    type = bool
    default = true
    }

    Access using:
    monitoring = var.monitoring_enabled

Collection Types:

  1. List(type) - Ordered collection of values Eg: variable "cidr_block" { description = "CIDR block for VPC" type = list(string) default = ["10.0.0.0/8", "192.168.0.0/16", "172.16.0.0/12"] }

Access using:
cidr_ipv4 = var.cidr_block[2]

  1. Set(type) -
    Unordered collection of unique values
    Do not allow the duplicates
    It cannot access by their index - first convert it into list and then access the data.

    Eg:
    variable "allowed_region" {
    description = "AWS list of allowed regions"
    type = set(string)
    default = ["us-east-1", "us-west-1", "us-west-2"]
    }

Access using:
region = tolist(var.allowed_region)[0]

  1. Map(type) - Key-value pairs with string keys Eg: variable "tags" { type = map(string) default = { Environment = "dev" Name = "dev-EC2-instance" } }

Access using:
tags = var.tags

  1. Tuple([type1, type2, ...]) - Ordered collection with specific types for each element. Eg: variable "ingress_values" { type = tuple([number, string, number]) default = [443, "tcp", 443] }

Access using:
from_port = var.ingress_values[0]
ip_protocol = var.ingress_values[1]
to_port = var.ingress_values[2]

  1. Object({key1=type1, key2=type2, ...}) - Structured data with named attributes.
    Eg:
    variable "config" {
    type = object({
    region = string,
    monitoring = bool,
    instance_count = number
    })

    default = {
    region = "us-east-1",
    monitoring = true,
    instance_count = 1
    }
    }

Access using:
region = var.config.region
monitoring = var.config.monitoring

Devops #Terraform #AWS

Thanks to Piyush sachdeva The CloudOps Community

Top comments (0)