Terraform Session 3: Let's Learn about Terraform State, Variables and Functions

Are you ready to dive into the world of Infrastructure as Code (IaC) with Terraform? Welcome to our new blog series on Infrastructure as Code with Terraform! In this post, we'll cover essential concepts to help beginners get started with Terraform. Let's dive in! Desired vs Current State Terraform manages infrastructure by comparing the desired state (defined in your configuration files) with the current state of your resources. When you run terraform apply, Terraform calculates the differences and makes the necessary changes to achieve the desired state[1][5]. Variables and TFVARS Variables in Terraform allow you to parameterize your configurations. You can define them in a variables.tf file: variable "instance_type" { type = string default = "t2.micro" } To set values for these variables, you can use a terraform.tfvars file: instance_type = "t2.small" Environment Variables Terraform can also read values from environment variables. By convention, these variables are prefixed with TF_VAR_. For example: Linux: export TF_VAR_instance_type="t2.medium" Windows: set TF_VAR_instance_type="t2.medium" Locals Local values in Terraform allow you to assign a name to an expression, which you can then use multiple times within a module: locals { common_tags = { Project = "MyApp" Owner = "DevOps Team" } } resource "aws_instance" "server" { # ... other configuration ... tags = merge(local.common_tags, { Name = "WebServer" }) } Data Types Terraform supports several data types, including string, number, bool, list, map, and set. Here's an example using different data types: variable "server_port" { type = number default = 8080 } variable "tags" { type = map(string) default = { Environment = "Dev" Project = "MyApp" } } Conditional Expressions Conditional expressions in Terraform allow you to make decisions based on certain conditions: resource "aws_instance" "server" { instance_type = var.environment == "prod" ? "t2.medium" : "t2.micro" } Functions Terraform provides various built-in functions for string manipulation, numeric operations, and more. Popular Terraform Functions join Function The join function concatenates elements of a list into a single string using a specified delimiter. This is particularly useful when combining multiple values into a formatted string: variable "tags" { default = ["web", "app", "db"] } output "tag_string" { value = join("-", var.tags) } This would output: "web-app-db". split Function The split function does the opposite of join, breaking a string into a list of substrings based on a delimiter: variable "comma_separated" { default = "apple,orange,banana" } output "fruits_list" { value = split(",", var.comma_separated) } This would output: ["apple", "orange", "banana"]. format Function The format function creates a formatted string using printf-style syntax. It's useful for creating complex strings with variables: variable "name" { default = "John" } variable "age" { default = 30 } output "greeting" { value = format("Hello, my name is %s and I'm %d years old", var.name, var.age) } coalesce Function The coalesce function returns the first non-null value from a list of arguments. It's particularly useful for providing default values: variable "port" { default = null } resource "aws_security_group" "example" { name = "example" ingress { from_port = coalesce(var.port, 80) to_port = coalesce(var.port, 80) protocol = "tcp" } } merge Function The merge function combines multiple maps into a single map. This is especially useful when working with tags or combining different sets of variables: variable "common_tags" { default = { Environment = "Production" Project = "MyApp" } } variable "resource_tags" { default = { Name = "WebServer" } } resource "aws_instance" "example" { # ... other configuration ... tags = merge(var.common_tags, var.resource_tags) } This concludes our beginner-friendly overview of key Terraform concepts. In our next post, we'll dive deeper into practical examples and best practices. Happy terraforming! Citations: [1] https://spacelift.io/blog/terraform-infrastructure-as-code [2] https://blog.facets.cloud/guide-iac-with-terraform/ [3] https://www.xenonstack.com/insights/terraform [4] https://www.youtube.com/watch?v=YcJ9IeukJL8 [5] https://developer.hashicorp.com/terraform/tutorials/aws-get-started/infrastructure-as-code [6] https://blog.gruntwork.io/an-introduction-to-terraform-f17df9c6d180?gi=8a2d1a228195 [7] https://k21academy.com/terraform-iac/terraform-beginners-guide/ [8] https://www.reddit.com/r/Terraform/comments/1cc9fnf/free_blog_series_on_getting_started_quickly_with/ [9] https://codefresh.io/learn/infrastructure-as-code/iac-with-terr

Jan 19, 2025 - 17:10
Terraform Session 3: Let's Learn about Terraform State, Variables and Functions

Are you ready to dive into the world of Infrastructure as Code (IaC) with Terraform?

Welcome to our new blog series on Infrastructure as Code with Terraform! In this post, we'll cover essential concepts to help beginners get started with Terraform. Let's dive in!

Desired vs Current State

Terraform manages infrastructure by comparing the desired state (defined in your configuration files) with the current state of your resources. When you run terraform apply, Terraform calculates the differences and makes the necessary changes to achieve the desired state[1][5].

Variables and TFVARS

Variables in Terraform allow you to parameterize your configurations. You can define them in a variables.tf file:

variable "instance_type" {
  type    = string
  default = "t2.micro"
}

To set values for these variables, you can use a terraform.tfvars file:

instance_type = "t2.small"

Environment Variables

Terraform can also read values from environment variables. By convention, these variables are prefixed with TF_VAR_. For example:

Linux:

export TF_VAR_instance_type="t2.medium"

Windows:

set TF_VAR_instance_type="t2.medium"

Locals

Local values in Terraform allow you to assign a name to an expression, which you can then use multiple times within a module:

locals {
  common_tags = {
    Project = "MyApp"
    Owner   = "DevOps Team"
  }
}

resource "aws_instance" "server" {
  # ... other configuration ...
  tags = merge(local.common_tags, {
    Name = "WebServer"
  })
}

Data Types

Terraform supports several data types, including string, number, bool, list, map, and set. Here's an example using different data types:

variable "server_port" {
  type    = number
  default = 8080
}

variable "tags" {
  type = map(string)
  default = {
    Environment = "Dev"
    Project     = "MyApp"
  }
}

Conditional Expressions

Conditional expressions in Terraform allow you to make decisions based on certain conditions:

resource "aws_instance" "server" {
  instance_type = var.environment == "prod" ? "t2.medium" : "t2.micro"
}

Functions

Terraform provides various built-in functions for string manipulation, numeric operations, and more.

Popular Terraform Functions

  1. join Function

The join function concatenates elements of a list into a single string using a specified delimiter. This is particularly useful when combining multiple values into a formatted string:

variable "tags" {
  default = ["web", "app", "db"]
}

output "tag_string" {
  value = join("-", var.tags)
}

This would output: "web-app-db".

  1. split Function

The split function does the opposite of join, breaking a string into a list of substrings based on a delimiter:

variable "comma_separated" {
  default = "apple,orange,banana"
}

output "fruits_list" {
  value = split(",", var.comma_separated)
}

This would output: ["apple", "orange", "banana"].

  1. format Function

The format function creates a formatted string using printf-style syntax. It's useful for creating complex strings with variables:

variable "name" { default = "John" }
variable "age" { default = 30 }

output "greeting" {
  value = format("Hello, my name is %s and I'm %d years old", var.name, var.age)
}
  1. coalesce Function

The coalesce function returns the first non-null value from a list of arguments. It's particularly useful for providing default values:

variable "port" { default = null }

resource "aws_security_group" "example" {
  name = "example"
  ingress {
    from_port = coalesce(var.port, 80)
    to_port   = coalesce(var.port, 80)
    protocol  = "tcp"
  }
}
  1. merge Function

The merge function combines multiple maps into a single map. This is especially useful when working with tags or combining different sets of variables:

variable "common_tags" {
  default = {
    Environment = "Production"
    Project     = "MyApp"
  }
}

variable "resource_tags" {
  default = {
    Name = "WebServer"
  }
}

resource "aws_instance" "example" {
  # ... other configuration ...
  tags = merge(var.common_tags, var.resource_tags)
}

This concludes our beginner-friendly overview of key Terraform concepts. In our next post, we'll dive deeper into practical examples and best practices. Happy terraforming!

Citations:
[1] https://spacelift.io/blog/terraform-infrastructure-as-code
[2] https://blog.facets.cloud/guide-iac-with-terraform/
[3] https://www.xenonstack.com/insights/terraform
[4] https://www.youtube.com/watch?v=YcJ9IeukJL8
[5] https://developer.hashicorp.com/terraform/tutorials/aws-get-started/infrastructure-as-code
[6] https://blog.gruntwork.io/an-introduction-to-terraform-f17df9c6d180?gi=8a2d1a228195
[7] https://k21academy.com/terraform-iac/terraform-beginners-guide/
[8] https://www.reddit.com/r/Terraform/comments/1cc9fnf/free_blog_series_on_getting_started_quickly_with/
[9] https://codefresh.io/learn/infrastructure-as-code/iac-with-terraform-a-practical-guide/