Terraform Deployments: Multiple Environments with .tfvars Files

Felipe FaragutiFelipe Faraguti
5 min read

Introduction

When it comes to managing infrastructure as code, Terraform stands out as a robust and versatile tool. One of its key features that significantly enhances its flexibility and reusability is the use of variables. In this post, we'll explore the concept of Terraform variables and show how they enable effortless multi-environment deployments, all thanks to the ingenious utilization of .tfvars files.

Understanding Terraform Variables

What Are Terraform Variables?

In Terraform, variables serve as parameters for your configurations. They act as placeholders for values that can change, allowing you to create dynamic and reusable Terraform modules. Instead of hardcoding values directly into your configuration files, you can use variables to make your code more adaptable and easier to maintain.

Why Use Terraform Variables?

The beauty of Terraform variables lies in their ability to enhance the modularity and portability of your infrastructure code. Here’s why they are incredibly cool to use:

  1. Flexibility: Variables enable you to adjust configurations based on different scenarios without altering the core code. This adaptability is crucial when deploying applications across diverse environments like development, staging, and production.

  2. Reusability: When defining variables, you create a template that can be reused across multiple projects. This reusability not only saves time but also ensures consistency in configurations.

  3. Maintainability: Variables enhance the readability of your code. Anyone reviewing the configuration can instantly identify the purpose of each variable, making collaboration more straightforward and reducing the learning curve for new team members.

  4. Scalability: As your infrastructure grows, variables facilitate easy scaling. You can modify values in a central .tfvars file, and these changes will be reflected across all instances where the variables are used, ensuring uniformity across your infrastructure.

Tailoring Deployments for Different Environments with .tfvars Files

Now that we understand the significance of Terraform variables, let’s explore how .tfvars files elevate the deployment process across various environments. These files contain specific values for variables, allowing you to customize configurations for different use cases without modifying the core Terraform files. In our example, we're going to use Terraform to create on Amazon Web Services (AWS), an EC2 instance and an S3 bucket.

- main.tf

provider "aws" {
 region = var.region
}

data "aws_ami" "latest_amazon_linux" {
  most_recent = true
  owners      = ["amazon"]

  filter {
    name   = "name"
    values = ["amzn2-ami-hvm-*-x86_64-gp2"]
  }
}

resource "aws_instance" "ec2_example" {
  ami           = data.aws_ami.latest_amazon_linux.id
  instance_type = var.instance_type

  tags = {
    Name = "${var.env}-instance"
  }
}

resource "aws_s3_bucket" "bucket_example" {
  bucket = "${var.env}-terraform-bucket"
}

We have a variable called region that tells Terraform which area of the world (like US or Europe) to create our resources. Similarly, we have variables for the type of computer we want (instance_type) and the environment name (env). We can change these variables to create our resources differently for various situations, making our Terraform configurations super flexible.

- variables.tf

variable "region" {}
variable "instance_type" {}
variable "env" {}

This file serves as a definition list, where we specify all the key elements that might change, like regions or instance types. It acts as a structured template, ensuring consistency and providing a clear overview of what can be customized in the Terraform code.

- Staging Environment Configuration (staging.tfvars):

region = "us-east-1"
instance_type = "t2.micro"
env = "staging"

In the staging environment, the region variable is set to "us-east-1," indicating that the resources will be created in the AWS US East (North Virginia) region. The instance_type variable is specified as "t2.micro," meaning a small-sized instance will be created. The env variable is set to "staging," helping identify that these resources belong to the staging environment. This configuration might be suitable for testing or development purposes, where smaller and cost-effective resources are preferred.

- Production Environment Configuration (production.tfvars):

region = "us-east-1"
instance_type = "t2.large"
env = "production"

In the production environment, the region variable is also set to "us-east-1," ensuring that the resources are deployed in the same AWS region as the staging environment. However, the instance_type variable is now specified as "t2.large," indicating a larger and more powerful instance type compared to the staging environment. The env variable is set to "production," distinguishing these resources as part of the production environment. This configuration might be suitable for hosting applications or services in a live, high-demand environment, where more robust and scalable resources are necessary.

Planning the Configuration

  1. Initialization (terraform init):

    We need to first initialize our Terraform configuration. When we run terraform init, Terraform downloads necessary plugins and sets up the environment. It ensures that Terraform understands which provider (in this case, AWS) we're using and prepares the project for further actions.

     terraform init
    
  2. Planning and Deployment:

    Now, when it comes to planning and deployment, Terraform provides a two-step process. Planning is like making a blueprint or a draft of what changes Terraform will make. We use terraform plan to generate this blueprint and show you how it works.

    • For staging environment:

        terraform plan -var-file=staging.tfvars
      

    • For production environment:

        terraform plan -var-file=production.tfvars
      

Important Note: It's crucial to highlight that at this stage, we're only visualizing what Terraform intends to do based on our configurations. We're not making any actual changes to our infrastructure. This approach is beneficial because it allows us to review the plans before applying, ensuring that we're making the intended changes and that everything looks correct.

Conclusion

Terraform variables and .tfvars files empower DevOps teams to navigate the complexities of multi-environment deployments with ease. Knowing this, you not only simplify your configurations but also future-proof your infrastructure, making it adaptable to the evolving needs of your organization. Happy coding!

0
Subscribe to my newsletter

Read articles from Felipe Faraguti directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Felipe Faraguti
Felipe Faraguti

Tech enthusiast and recent graduate with a B.S. in Computer Information Technology. Specialized in AWS and Azure Cloud Computing, Database Management, and DevOps. Eager to contribute to innovative projects. Let's connect and explore tech's endless possibilities!