Solving the DevOps Infrastructure Dilemma: Enabling developer velocity with control 💡

Register for the webinar here →


What is Terraform? What is it Used For, How it Works

what is terraform overview

If you have heard of Terraform but are not exactly sure what it is or when to use it, you have landed at the right place. This post will cover it all starting off with defining Terraform.

What is Terraform?

Terraform is a powerful Infrastructure as Code (IaC) software tool offered by HashiCorp. It facilitates provisioning and managing your infrastructure on-prem and in the cloud. It can be easily extended with the help of its plugin-based architecture.

What is Terraform Used For?

Terraform can be connected with different infrastructure hosts and achieve complex management scenarios and compliance across multiple clouds. Its configuration can be easily packaged, shared, and reused in the form of Terraform modules.

In this post we will go over some basic elements and features of Terraform that can help you get started. Before we move forward, however, let’s discuss Infrastructure as Code (IaC) a bit more to develop a good understanding of Terraform.

Infrastructure as Code (IaC)

Traditionally, the process of preparing a Windows or Linux server for your lab or data center consisted of several steps involving mouse clicks, running scripts, and manually configuring different aspects such as storage and networking. Doing this at scale for hundreds or thousands of servers becomes increasingly complex and error-prone.

IaC makes this process much easier by allowing you to define and provision your infrastructure with the help of a declarative language. With this approach, you can gain consistency, repeatability, and enhanced reliability

In addition to day one infrastructure setup, this approach also helps with the management of any changes that happen to your infrastructure along the way, commonly referred to as drift management. (If you’re interested in how to manage Terraform workflows at scale, see: How to Manage Terraform at Scale)

Other common IaC tools include Cloud Formation Templates (CFT) for AWS, Azure Resource Manager (ARM) templates for Microsoft Azure, and Deployment Manager for Google cloud.

How Does Terraform Work?

At a high level, Terraform can be thought of as consisting of two main parts: Terraform Core and Plugins. Core is responsible for life cycle management of infrastructure. It is the open-source binary that you download and use from the command line. 

Terraform Core takes into consideration the current state and evaluates it against your desired configuration. It then proposes a plan to add or remove infrastructure components as needed. Next, it takes care of provisioning or decommissioning any resources if you choose to apply the plan.

Terraform Plugins provide a mechanism for Terraform Core to communicate with your infrastructure host or SaaS providers. Terraform Providers and Provisioners are examples of plugins as mentioned above. Terraform Core communicates with the plugins via Remote Procedure Call (RPC).

terraform definition

Terraform Workflow

A typical Terraform workflow will consist of the following steps:

Step 1. Write 

Declare your infrastructure resources as code in Hashicorp Configuration Language (HCL). 

Step 2. Review the Plan

Terraform will display a plan to add or remove resources based on the comparison of your declared infrastructure and the current state of any existing resources.

Step 3. Apply

Accept the planned changes to add or remove any infrastructure resources. This workflow works well for a single author as Terraform State is stored locally. As more contributors join the team, it becomes important to ensure everyone has a correct view of the current infrastructure state and changes are applied sequentially without overlaps. 

Terraform offers Enterprise and Cloud versions for teams to work together. These store the state remotely so everyone can have a consistent view. Terraform Cloud is available as a hosted service, whereas Terraform Enterprise enables you to deploy and self-host the Terraform Cloud in your private instance. Authors contribute their code to a central version control system (e.g. Github) and Terraform Cloud uses the latest code versions from the central repository. (See: Top 8 Terraform Cloud Alteratives)

Core Elements of Terraform

Terraform CLI

Terraform is an open-source tool that compiles to a single binary file that can be downloaded on your system and used interactively from the command prompt. The latest version of Terraform can be downloaded here. A list of available Terraform commands can be retrieved from the command line

~  terraform --help                                                                  
Usage: terraform [global options] <subcommand> [args]

The available commands for execution are listed below.
The primary workflow commands are given first, followed by
less common or more advanced commands.

Main commands:
  init          Prepare your working directory for other commands
  validate      Check whether the configuration is valid
  plan          Show changes required by the current configuration
  apply         Create or update infrastructure
  destroy       Destroy previously-created infrastructure

All other commands:
  console       Try Terraform expressions at an interactive command prompt
  fmt           Reformat your configuration in the standard style
  force-unlock  Release a stuck lock on the current workspace
  get           Install or upgrade remote Terraform modules
  graph         Generate a Graphviz graph of the steps in an operation
  import        Associate existing infrastructure with a Terraform resource
  login         Obtain and save credentials for a remote host
  logout        Remove locally-stored credentials for a remote host
  output        Show output values from your root module
  providers     Show the providers required for this configuration
  refresh       Update the state to match remote systems
  show          Show the current state or a saved plan
  state         Advanced state management
  taint         Mark a resource instance as not fully functional
  test          Experimental support for module integration testing
  untaint       Remove the 'tainted' state from a resource instance
  version       Show the current Terraform version
  workspace     Workspace management

Global options (use these before the subcommand, if any):
  -chdir=DIR    Switch to a different working directory before executing the
                given subcommand.
  -help         Show this help output, or the help for a specified subcommand.
  -version      An alias for the "version" subcommand.

Terraform Language

Infrastructure is defined in the Hashicorp Configuration Language (HCL) when working with Terraform. HCL is a declarative language targeted towards DevOps tools and servers. It provides a nice balance between machine-readable formats such as JSON and configuration formats included in high-level languages such as Ruby. 

Infrastructure components managed by Terraform are called Resources. Examples of resources include virtual machines, database tables, AWS S3 buckets, VPCs, and more. Each resource block in HCL helps define the resource and configure its properties. An example VPC resource looks like this:

resource "aws_vpc" "default_vpc" { 
    cidr_block = "" 
    tags = { 
        Name = "example_vpc" 
} }

Terraform Providers

Terraform needs to connect to your infrastructure host to effectively manage your infrastructure. Infrastructure hosts generally have a published API that facilitates operations to create, update and delete infrastructure elements. Terraform Providers supply an abstraction to these APIs

Terraform configuration must include providers for it to connect with required cloud or SaaS services. Providers are published by infrastructure hosts and made available to Terraform as plugins. The plugin-based architecture allows publishers to independently publish and maintain their providers. The Terraform registry is the main directory of publicly available providers (you can also find the Spacelift Terraform Provider in this registry).

Here is an example of configuring AWS Terraform Provider in HCL:

provider "aws" { 
   version = "~> 3.0" 
   region = "us-east-1" 

Terraform Provisioners

Provisioners are another type of plugin available to use with Terraform as a means of configuring the infrastructure and making it ready for service. For example, you might need to copy certain files to your virtual machine necessary for your application to function, or you might need to run configuration management software (e.g. Chef or Puppet, etc.) that you normally use to configure your environment. 

Provisioners add complexity to overall usage of Terraform. Their behavior cannot be easily modeled with Terraform for planning as they can take a wide range of actions and might access your critical infrastructure services with high privileges. Hashicorp recommends using Provisioners as a last resort for your needs, only after searching for options available with other Terraform constructs.

Terraform Modules

Modules provide a way to package resources that provide relevant functionality together as a group. Each Terraform configuration has at least one module called the root module and can call other modules referred to as child modules. 

It is easy to write modules and share them with your team or others. The Terraform registry hosts a large collection of Terraform modules for commonly used configuration scenarios. Terraform can automatically download these modules if you include them in your configuration.

Terraform State

Terraform stores a representation of your infrastructure objects, their interdependencies and bindings in a configuration file named terraform.tfstate. Storing the state information helps Terraform immensely in making planning and execution decisions. State can be stored locally as well as remotely in a team environment.

Read more about the elements of Terraform architecture.

Terraform Example Use Cases

Let’s take a look at some common scenarios where Terraform can be used:

Example 1. Rapidly Build and Dispose Environments

It is common practice to have multiple environments in a typical IT organization such as Development, Testing, Staging, and Production. Terraform allows us to save all the infrastructure resources and their interdependencies specific to an environment as code in Hashicorp Configuration Language (HCL). We can use this code to quickly create a new environment as needed. 

For example, when we need to test a new feature and want to make sure our Testing environment is an exact copy of Production, we can quickly create a Test environment with the help of code that is used to create the Production, ensuring our changes will run smoothly when moved to Production after testing. 

Similarly, when developing a new feature we might need to create a new development environment for a short period of time. We can easily create and tear down one with the help of Terraform automation. The same concept applies to building recovery environments in case a disaster strikes and makes the Production unavailable.

Example 2. Use Multiple Clouds

Using more than one public cloud provider can be very beneficial if we want to have some fault tolerance for our application. In case cloud services for a particular region fail for a cloud provider, the application can continue to work if it is configured to use multiple cloud providers. It is also common to keep some resources on-prem and use a hybrid environment, combining private and public cloud resources. 

Terraform is cloud-agnostic. It can deploy applications across multiple clouds quickly and consistently. With Terraform, we don’t have to worry about using deployment tools specific to cloud providers. Instead, we can have a uniform experience working with different clouds.

Example 3. Deploy N-Tier Applications

N-Tier applications provide separation of concerns by having different tiers targeted to specific purposes. For example, a typical web application will have a tier dedicated to databases, and another tier for web servers. The web servers will depend on databases to function properly and will be behind a load balancer that will distribute requests among these web servers. 

Terraform can help ensure dependencies in this environment are implemented correctly, as databases will have to be deployed and be available before web servers. It is also easy to scale multi-tiered applications by adding more resources to a specific tier. 

For example, if you feel your application can be more robust with the help of an additional database server, it can be a matter of a simple configuration change and deployment with Terraform to add another server to the database tier.

Example 4. Work with Popular PaaS tools

Infrastructure provisioning is an important part of application deployment. However, it is not the only one required for successful deployment of applications. Modern applications use several tools to accomplish critical functions such as scheduling of resources, caching and routing, etc. Kubernetes is a popular orchestration platform used to productively deploy containers across multiple hardware resources. 

Terraform Providers not only work as abstractions for infrastructure hosts, but they can essentially interact with any API based platform such as Kubernetes. This allows us to use Terraform as a single tool to deploy infrastructure and then configure any required platforms like Kubernetes.


Terraform vs Other Infrastructure Tools

Terraform solves several important infrastructure problems and naturally has some overlapping features with other infrastructure tools. Let’s take a look at some frequently asked questions about other tools in relation to Terraform

  • What is OpenTofu, and should I use it instead of Terraform?

    OpenTofu is an open-source version of Terraform that will expand on Terraform’s existing concepts and offerings. It is a viable alternative to Terraform, being forked from Terraform version 1.5.6, created as a community-driven initiative supported by many of the most recognized companies and projects in the Terraform ecosystem in response to Hashicorp’s BSL license change.

    OpenTofu is the future of the Terraform ecosystem and having a truly open-source project to support all your IaC needs is the main priority.

    Key advantages of using OpenTofu instead of Terraform:

    • Open-source nature: There are no restrictions on how you can use OpenTofu, either for commercial or personal use. The open-source nature of OpenTofu embodies the principles of openness and collaboration that characterize the tech community.
    • Dynamic community: Developer contributions will make the project more robust and adaptable to different use cases. Bugs and issues will be identified and resolved quickly to ensure reliability and stability.
    • Fast, reliable support: The growing community behind OpenTofu not only gives everyone the opportunity to influence the development of new features, but it also supplies the resources to ensure these features and bug fixes will be introduced rapidly.
    • Minimal risk: OpenTofu is published under MPL and is a part of the Linux Foundation (with the goal of joining CNCF), which provides the guarantee the tool remains truly open-source, forever.
  • Should I use Terraform or other popular configuration management tools like Chef or Puppet?

    There is a basic difference between Terraform and configuration management tools. Terraform focuses on making it easy to provision and manage your infrastructure, whereas configuration management software is used to prepare the VMs and Servers to fit your application and environment needs after provisioning. Furthermore, Terraform can be used in conjunction with configuration management tools as they address separate concerns.

  • What about cloud specific tools like Cloud Formation and ARM Templates?

    While cloud specific tools can be excellent at managing resources for a particular cloud provider, Terraform strives to be cloud agnostic. It allows you to use the same language to define your resources across different clouds and makes it easy to work with multi-cloud and hybrid cloud scenarios.

  • What about common orchestration tools such as Kubernetes?

Similarly to configuration management tools, container orchestration platforms focus on a separate concern and can be easily used in collaboration with Terraform. They usually have a robust API that helps develop Terraform Providers that in turn can be used effectively with Terraform Core, for example. Kubernetes Terraform Provider can be found in the Terraform Provider registry.

  • Why use Terraform instead of our home grown scripts?

    There are several reasons for moving away from custom ad-hoc scripts. A common issue encountered is their limitation to scale and adapt to new infrastructure needs. A custom script typically addresses a specific environment and needs updating and refactoring as new applications and infrastructure are added to the IT organization. This creates an overhead in terms of time, effort, and budget to achieving business-critical goals.


In this post, we have briefly discussed the main features and use cases of Terraform that will help you get started. We encourage you also to explore how Spacelift makes it easy to work with Terraform. Have questions? Drop us a line in the comments below.

Terraform Management Made Easy

Spacelift effectively manages Terraform state, more complex workflows, supports policy as code, programmatic configuration, context sharing, drift detection, resource visualization and includes many more features.

Start free trial
Terraform Essential Components Cheatsheet

Whenever you're embarking on a new journey or seeking to refine your foundational knowledge.

Share your data and download the cheatsheet