Terraform Variables

Terraform Variables

What are Terraform Variables?

In any scripting or programming language, variables are essential to store data values. Similarly, in Terraform, variables provide a way to externalize configuration settings, so you don't hard-code every value. This is especially useful when working in different environments like development, staging, and production.

Create variables.tf file which will hold all the variables.

Types of Terraform Variables:

1) Input Variables:

As the name suggests, these are the variables which you can provide values for. They allow for customization and can be defined using the variable block.

variable "region" {
  description = "The AWS region"
  default     = "us-west-1"
}

2) Output Variables:

These are used to extract information from the Terraform state. It's particularly useful when you want to output endpoints, IDs, or any other critical info after the infrastructure is provisioned.

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

3) Local Values:

These are intermediary variables you can use within your configuration to simplify complexity and avoid repetition. They are defined using the locals block.

locals {
  common_tags = {
    Owner = "DevOps Team"
  }
}

How to Use Terraform Variables:

  1. Directly in Configuration: You can set default values for your variables directly in your Terraform configuration.

  2. From a File: Using a terraform.tfvars or any *.auto.tfvars file, you can define values for your variables. This makes it easier to manage and version your variable values.

  3. From Command Line: You can also set variables using the -var flag with terraform apply or terraform plan commands.

     terraform apply -var "region=us-east-1"
    
  4. From Environment Variables: Terraform will recognize any environment variables that are prefixed with TF_VAR_.

     export TF_VAR_region=us-east-1
    

Best Practices:

  1. Sensitive Data: Never hard code sensitive data. Instead, use variables and store the values securely, possibly encrypted, and feed them into Terraform when needed.

  2. Structure: Group related variables in the same block or file. This enhances readability and maintainability.

  3. Documentation: Always document your variables, especially when working in teams. Terraform allows adding descriptions to variables, which can be quite helpful.

  4. Don't Overuse Defaults: While default values can be useful, don't rely on them for critical infrastructure decisions. Explicitly setting a value provides clarity.

  5. Versioning: If you're storing variable values in *.tfvars files, consider version controlling these (excluding sensitive data, of course) for tracking changes over time.

Task-1

Create a simple txt file with Terraform using variable.tf

Login to your EC2 Instance and create a directory mkdir /home/ubuntu/terraform

Create main.tf file has resource as local_file and will be mentioning filename and content - main.tf

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

vaiable.tf

Here we are adding the filename and its content.

variable "filename" {
default = "/home/ubuntu/terraform/myfile.txt"
}

variable "content" {
default = "Hello, Kshitija Here! This is coming from a variable which was updated"
}

Now, let's create it using Terraform. First, initialize terraform

terraform init

How does the file will get create; see it using following command

terraform plan

Create file with terraform apply as follows

terraform apply

Validate

if you list the files, you will see new file has got created named my myfile.txt, see its content, it is as per the configuration.

Yes Well Done GIF - Yes Well Done Success - Discover & Share GIFs


Map

In Terraform, a map is a data structure that allows you to store and manage a collection of key-value pairs. Maps are often used to define input variables, output values, and resource configurations.

Task-2

variable.tf Create a variable of type map and pass two statements that will act as content for two text files.

variable "filename1" {
default = "/home/ubuntu/terraform/myfile-1.txt"
}

variable "filename2" {
default = "/home/ubuntu/terraform/myfile-2.txt"
}

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

main.tf Create two files that will pick the content of the map variable.

resource "local_file" "devops1" {
filename = var.filename1
content = var.content_map["statement1"]
}

resource "local_file" "devops2" {
filename = var.filename2
content = var.content_map["statement2"]
}

We can check the syntax of our HCL code using terraform validate command. Then let's check the plan of the terraform.

terraform validate

Finally, apply the terraform for the code.

terraform apply

Now we can check that two files have been created with the contents that we had passed in the Map variable.


List

In Terraform, a list is a data structure that allows you to store and manage a collection of values. Lists are often used to define input variables, output values, and resource configurations.

Task-3

variable.tf Create a variable of type list to pass the list of files.

variable "file_list"{
    type = list
    default = ["/home/ubuntu/terraform/file1.txt","/home/ubuntu/terraform/file2.txt"]
}
variable "content_map" {
 type = map
 default = {
 "statement1" = "this is cool"
 "statement2" = "this is cooler"
 }
 }

Replace the file name in the main.tf code to the list of file variables. This will assign the filename and location through the variable.

resource "local_file" "devops1" {
    filename = var.file_list[0]
    content = var.content_map["statement1"]
}

resource "local_file" "devops2" {
    filename = var.file_list[1]
    content = var.content_map["statement2"]
}

You can follow terraform validate and terraform apply, below is the output.

Conclusion

Terraform variables play a pivotal role in ensuring that our infrastructure configurations are flexible, maintainable, and reusable. By understanding and using variables effectively, you can ensure that your IaC practices are robust and resilient. Whether you're just starting with Terraform or an experienced practitioner, always remember to make ample use of variables to externalize and manage your configuration settings.

ย