When it comes to managing your infrastructure as code, Terraform stands as a powerful ally. One of its key features that contributes to its flexibility and reusability is variables. In this guide, we’ll explore the ins and outs of variables in Terraform using a real-world example.

What are variables in Terraform?

Variables in Terraform allow you to parameterize your configurations, making them dynamic and reusable. They help you keep your code clean, flexible, and adaptable to different environments.

There are two types of variables in Terraform:

  • Input variables are used to pass values to Terraform from the outside world. For example, you might have an input variable for the name of your web app, or the region where you want to deploy it.
  • Output variables are used to return the values of resources that have been created by Terraform. They can be used in other Terraform configuration files, or they can be used by scripts or applications.

How to define Input variables?

Input variables are typically defined in a separate file with a .tfvars extension or within the Terraform configuration file itself.

How to use input variables?

You can use input variables in your resource declarations or other parts of your configuration like this:

Variable values can be set using command-line flags, a terraform.tfvars file, or by passing them directly when running “terraform apply“.

How to define Output Variables?

Output variables are defined within the same configuration file or in a separate .tf file.

How to use Output Variable?

You can use output variables to display information or for passing information to external systems.

Interpolating Output Variables:

You can interpolate output variables in other Terraform configurations. For example, you can pass the instance IPs to a shell script:

Real-World Example:

Let’s consider a scenario where you’re provisioning virtual machines in AWS using Terraform. You want to parameterize the instance type and the number of instances.

Assuming you have the following files in your Terraform project directory:

variables.tf


main.tf


outputs.tf

terraform.tfvars

Now, if you run “terraform apply” in the directory containing these files, you’ll see output similar to the following:


In this output, Terraform first creates the specified number of instances with the specified instance type in the AWS region.

Once the resources are created, it displays the public IPs of the instances using the output variable. In this case, three instances were created, and their public IPs are shown in the “instance_ips” output.

Thanks for Reading!
I hope you find this post helpful.

You can connect with me for more free content related to DevOps: Learn DevOps & Cloud For Free

Leave a Reply

Your email address will not be published. Required fields are marked *

DevOps Lifecycle Simplified Cybersecurity Lifecycle Top 10 Technical Roles for 2023 7 Tips to become Data Scientist