Day 63: Understanding Terraform Variables

Day 63: Understanding Terraform Variables

Day#63 Of 90 Days Of DevOps Challenge

👋Introduction

Terraform is a powerful infrastructure-as-code tool that enables you to define, manage, and provision your infrastructure.

Variables in Terraform play a crucial role in defining inputs for your configurations, allowing for greater flexibility and reusability in your infrastructure provisioning process.

This blog will explore the concept of Terraform variables and provide practical examples.

❄Introduction to Terraform Variables

In Terraform, variables serve as placeholders for values that can be supplied to your configurations. They are essential for parameterizing your code, enabling dynamic values to be incorporated into your infrastructure. These variables can be used to pass data between different parts of your Terraform code, as well as to provide users with the ability to customize the behavior of their infrastructure.

🖋Creating a Variables File

To get started with Terraform variables, you typically create a variables.tf file to define and declare the variables that will be used in your Terraform code.

These variables can be of various types, such as strings, numbers, booleans, lists, maps, and even complex objects.

Example of Terraform Provider:

To illustrate how Terraform variables work, consider the following examples. In the case of a provider configuration for AWS, you can specify the region using a variable as shown below:

provider "aws" {
  region = "us-east-1"
}

Example of Terraform Resource:

Similarly, when defining a resource like an AWS EC2 instance, variables can be employed to specify attributes like the Amazon Machine Image (AMI) and instance type:

resource "aws_instance" "example" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"
}

Creating a Variable:

Here is how you declare a Terraform variable:

variable "filename" {
  default = ""
}

Example of Terraform Output:

Finally, Terraform outputs allow you to expose certain values to users. Here's an example that outputs the public IP address of the AWS instance created earlier:

output "instance_ip_addr" {
  value = aws_instance.example.public_ip
}

📃Task 1: Creating a Local File Using Terraform Variables

To put these concepts into practice, let's create a local file using Terraform. The following steps outline how to do this:

  1. Create a main.tf file and add the code to create a local file using Terraform.
resource "local_file" "devops" {
  filename = var.filename
  content  = var.content
}
  1. Create a variables.tf file and declare the variables required for the task.
variable "filename" {
  default = "/home/ubuntu/Documents/terraform/day2/demo.txt"
}
variable "content" {
  default = "This is a sample file."
}
  1. Initialize Terraform in the working directory:
terraform init
  1. Review the planned changes:
terraform plan
  1. Apply the changes to create the local file:
terraform apply

Upon completion, you'll have a file with the content specified in the variable file.

📜Task 2: Exploring Data Types in Terraform

Terraform supports various data types, each serving a unique purpose. These data types include:

  • String: For holding text or characters.

  • Number: For storing numeric values (integers or floats).

  • Bool: To represent boolean values (true or false).

  • List: An ordered collection of values.

  • Map: For organizing key-value pairs.

  • Object (Complex Type): Suitable for structured data.

Example of Terraform Map:

In Terraform, a map is used to store key-value pairs efficiently. Here's an example of a map in Terraform:

variable "example_map" {
  type    = map(string)
  default = {
    key1 = "value1"
    key2 = "value2"
    key3 = "value3"
  }
}

📚Task 3: Creating a Map in Terraform

To demonstrate the use of maps in Terraform, follow these steps:

  1. Create a main.tf file and define a map.
provider "aws" {
  region = "ap-south-1"
}

resource "local_file" "example_3" {
  filename = "/home/user/Documents/terraform/day62/devops.txt"
  content  = var.file_contents["statement1"]
}

resource "local_file" "example_4" {
  filename = "/home/user/Documents/terraform/day62/devops_cloud.txt"
  content  = var.file_contents["statement2"]
}
  1. In the variables.tf file, declare the required variables, including a map:
variable "filename" {
  default = "/home/ubuntu/Documents/terraform/demo/demo.txt"
}

variable "content" {
  default = "Hello World ..."
}

variable "file_contents" {
  type    = map
  default = {
    "statement1" = "This is a sample file."
    "statement2" = "This is a sample file for Devops and Cloud."
  }
}
  1. Initialize Terraform:
terraform init
  1. Apply the configuration to create the map in Terraform:
terraform apply

You can verify the map using the cat command.

📑Task 4: Lists and Objects in Terraform

What is a List in Terraform?

A list in Terraform is a data type representing an ordered collection of values. Lists maintain the order of elements and can contain values of the same or different data types.

They are declared using square brackets and accessed by index.

Example of a List in Terraform:

variable "example_list" {
  type    = list
  default = ["item1", "item2", "item3"]
}

Creating a List in Terraform

To create a list in Terraform, perform the following steps:

  1. In your variables.tf file, declare a list variable, as shown in the example above.

  2. Initialize Terraform:

terraform init
  1. Apply the configuration to create the list.

What is an Object in Terraform?

In Terraform, an object is a complex data structure used to organize related data using key-value pairs.

It allows for the representation of structured data with various attributes or properties, each with its data type.

Example of an Object in Terraform:

Here's an example of defining an object in Terraform:

variable "aws_ec2_object" {
  type = object({
    name     = string
    instance = number
    keys     = list(string)
    ami      = string
  })
  default = {
    name     = "MyEC2"
    instance = 1
    keys     = ["aws_key.pem"]
    ami      = "ami-0f5ee92e2d63afc18"
  }
}

📖What is a Set in Terraform?

In Terraform, a "set" typically refers to creating a distinct collection of resources or modules based on conditions or input data.

This is achieved using the count or for_each arguments to dynamically manage instances within Terraform configurations.

While Terraform doesn't have a specific "set" data type, it allows you to achieve similar functionality by selectively creating or managing resources.

📜Task 5: Creating a Set in Terraform

To create a set in Terraform, follow these steps:

  1. Create a main.tf file and add the code for creating a set.
provider "aws" {
  region = "ap-south-1"
}

output "security_groups" {
  value = var.security_groups
}
  1. Initialize Terraform:
terraform init
  1. To create the set in Terraform.
terraform plan
  1. To refresh the state by your configuration file and reload the variables.
terraform apply

These tasks demonstrate the flexibility and versatility of Terraform in managing infrastructure using various data types, including lists, objects, and sets.

💥Conclusion

Terraform variables are the building blocks of flexibility and reusability in your infrastructure as code projects.

They allow you to parameterize your configurations, making it easy to adapt and scale your infrastructure as needed.

In this blog, we've explored the steps to define variables, use various data types, and the importance of terraform refresh in your Terraform workflow.

Stay tuned for the next blog in our Terraform journey as we continue to uncover the powerful features and capabilities of this amazing infrastructure as a code tool. Happy coding!

Happy learning & may your DevOps journey be filled with exciting discoveries🎊

Thank you for joining us on this exciting Day 63 of the 90 Days of DevOps challenge. I hope you found the information helpful and insightful.💥

So please keep yourself updated with my latest insights and articles on DevOps 🚀 by following me on :

Hashnode: vishaltoyou.hashnode.dev

LinkedIn: linkedin.com/in/vishalphadnis