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" } Now in main.tf, we access these variables using the var object:
resource "local_file" "devops" { filename = var.filename content = var.content } 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" } } We can reference it like:
output "map_output" { value = var.file_contents["statement1"] } Task-02: Demonstrating List, Set, and Object
List
variable "names" { type = list(string) default = ["Deborah", "George", "DevOps"] } output "list_example" { value = var.names[1] } Output - George
- Set
variable "unique_names" { type = set(string) default = ["apple", "banana", "apple", "orange"] } output "set_example" { value = var.unique_names } 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}" } ⚡ Using terraform refresh
The command:
terraform refresh 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)