Welcome back to the 63rd day of our 90 days of DevOps journey! Today, we'll delve into Terraform variables, a fundamental concept that allows us to parameterize our infrastructure code. Let's dive in!
What are Terraform Variables?
Terraform variables serve as placeholders for values in Terraform configurations. They enable us to reuse and customize configurations without hardcoding values directly into our code. Variables in Terraform can be defined at multiple levels, including at the root module, child modules, and even within expressions.
Variables can be of different types such as strings, numbers, lists, sets, maps, and more. They offer flexibility and maintainability to our infrastructure codebase.
Now, let's tackle a couple of tasks to better understand Terraform variables.
Task-01: Create a Local File Using Terraform
In this task, we'll use Terraform to create a local file. We'll leverage Terraform variables to define the filename and content dynamically.
resource "local_file" "devops" {
filename = var.filename
content = var.content
}
In the above code snippet:
We've defined a
local_file
resource named "devops".The
filename
attribute is set using thevar.filename
variable.Similarly, the
content
attribute is set using thevar.content
variable.
This demonstrates how Terraform variables can be used to parameterize resource configurations.
Task-02: Demonstrate Usage of List, Set, and Object Datatypes
Now, let's explore the usage of different data types - List, Set, and Object - within Terraform.
variable "example_list" {
type = list
default = ["item1", "item2", "item3"]
}
variable "example_set" {
type = set
default = ["a", "b", "c"]
}
variable "example_object" {
type = map(object({
key1 = string
key2 = number
}))
default = {
example1 = {
key1 = "value1"
key2 = 123
}
example2 = {
key1 = "value2"
key2 = 456
}
}
}
In this snippet:
We've defined variables of different types.
example_list
is a list type variable.example_set
is a set type variable.example_object
is a map of objects type variable.
These demonstrate how we can leverage different data types to model our infrastructure configurations more effectively.
Additionally, we'll use terraform refresh
to update the state file with the current real-world infrastructure. This command reconciles the Terraform state with the physical resources.
For more information related to terraform variables and their types checkout this blog (https://spacelift.io/blog/how-to-use-terraform-variables)
By completing these tasks, we've gained a better understanding of Terraform variables and their usage in infrastructure provisioning.
That's it for today! Stay tuned for more DevOps adventures on our 90-day journey. Happy automating! ๐