Skip to main content

Command Palette

Search for a command to run...

Day 47: Terraform Variables

Published
2 min read
Day 47: Terraform Variables
P

Hi, I am an AWS-certified cloud engineer and I write about my progress and learnings of DevOps.

Hello everyone!

Variables in Terraform are quite important, as you need to hold values of names of instances, configs, etc.

We can create a variable.tf file which will hold all the variables.

variable "filename" {
default = "/home/ubuntu/terrform-tutorials/terraform-variables/demo-var.txt"
}
variable "content" {
default = "This is coming from a variable which was updated"
}

These variables can be accessed by var object in main.tf

Tasks:

Task 1) Create a local file using Terraform

Create a variable.tf file

variable "filename" {
default = "/home/terraform/var-demo.txt"
}
variable "content" {
default = "This is demo terraform variable file"
}

Create a main.tf file

resource "local_file" "devops" {
filename = var.filename
content = var.content
}

Initializes a new or existing working directory for Terraform

terraform init

terraform plan
terraform apply

Our file has been created.

Data Types in Terraform

Map

A map is a collection of values where each value is identified by a string label

variable.tf

variable "file_contents" {
type = map
default = {
"statement1" = "this is cool"
"statement2" = "this is cooler"
}
}

A map variable named content_map is defined in the example, with a default value of two key-value pairs. Strings serve as both the keys and the values.


Thanks for reading ;)