DEV Community

Udoh Deborah
Udoh Deborah

Posted on

Day 63 : Terraform Variables

Terraform Variables

Variables in Terraform are very powerful — they help you write flexible and reusable code instead of hardcoding values everywhere. They can hold filenames, configurations, credentials, or instance names and can be grouped by different data types.

  • Task-01: Create a local file using variables

We first define variables in a variables.tf file:

variable "filename" {
  default = "/home/ubuntu/terraform-tutorials/terraform-variables/demo-var.txt"
}

variable "content" {
  default = "This is coming from a variable which was updated"
}
Enter fullscreen mode Exit fullscreen mode

Now in main.tf, we access these variables using the var object:

resource "local_file" "devops" {
  filename = var.filename
  content  = var.content
}
Enter fullscreen mode Exit fullscreen mode
  • Running terraform apply will create a file at the path defined by filename containing the content.

  • Data Types in Terraform

Terraform supports various data types. Let’s look at some common ones:

  • Map
variable "file_contents" {
  type = map(string)
  default = {
    "statement1" = "this is cool"
    "statement2" = "this is cooler"
  }
}
Enter fullscreen mode Exit fullscreen mode

We can reference it like:

output "map_output" {
  value = var.file_contents["statement1"]
}
Enter fullscreen mode Exit fullscreen mode
  • Task-02: Demonstrating List, Set, and Object

  • List

variable "names" {
  type    = list(string)
  default = ["Deborah", "George", "DevOps"]
}

output "list_example" {
  value = var.names[1]
}
Enter fullscreen mode Exit fullscreen mode

Output - George

  • Set
variable "unique_names" {
  type    = set(string)
  default = ["apple", "banana", "apple", "orange"]
}

output "set_example" {
  value = var.unique_names
}

Enter fullscreen mode Exit fullscreen mode
  • A set removes duplicates → ["apple", "banana", "orange"]

  • Object

variable "person" {
  type = object({
    name = string
    age  = number
    role = string
  })

  default = {
    name = "Deborah"
    age  = 27
    role = "DevOps Engineer"
  }
}

output "object_example" {
  value = "${var.person.name} is ${var.person.age} years old and works as a ${var.person.role}"
}
Enter fullscreen mode Exit fullscreen mode

⚡ Using terraform refresh

The command:

terraform refresh
Enter fullscreen mode Exit fullscreen mode
  • Reloads the state and re-syncs variables from your configuration files, ensuring Terraform has the latest values.

  • By using variables + data types, you can write clean, dynamic, and reusable Terraform scripts instead of static hardcoded ones.

Top comments (0)