Terraform Tutorial

(4.9)
14920 Viewers

This Terraform tutorial covers Terraform basics and advanced concepts in detail. You will learn how to install Terraform in different ways. The article explores the Terraform CLI, HCP Terraform, HCL concepts, various versions, and more. By the end of the article, you will gain a comprehensive understanding of Terraform, including Terraform use cases, policies, and more.

Terraform Tutorial
  • Blog Author:
    Mohammed Zaid
  • Last Updated:
    24 Oct 2026
  • Views:
    14920
  • Read Time:
    43:45 Minutes
  • Share:

Building and changing IT infrastructure isn't easy. That’s why organisations keep looking for a powerful tool to build, version, and change infrastructure smoothly.

Terraform is an Infrastructure-as-Code (IaC) tool. It provides human-readable configuration files that you can easily use and share with other applications. It effectively supports managing infrastructure changes, whether for storage or compute.

This guide explores the Terraform tutorial.

Table of Contents

 

Infrastructure-as-Code (IaC) - An Overview

IaC is an approach to managing your complete IT infrastructure using code or configuration files. You can automate the entire data centre using programming scripts. It includes infrastructure management, automated testing, version control, configuration management, and deployment automation.

As a result, Terraform is one of the most popular IaC tools used by many organisations. Primarily, you can use IaC to automate cloud resource management.

Terraform - An Introduction

Terraform is a source-available infrastructure provisioning tool. With consistent workflows, Terraform lets you manage infrastructure effectively throughout its lifecycle. It also manages all types of resources, from compute, storage, and networking resources to DNS entries and SaaS capabilities.

As of October & November 2026, the latest version of Terraform is 1.16.6.

Why Terraform?

Let’s look at the reasons below:

  • Tracking: Terraform keeps a ‘state file’, which helps identify the changes it makes.
  • Standardising Configurations: Terraform uses reusable modules for configuration. Modules save time and encourage best practices.
  • Automation: Terraform creates resource graphs, including resource dependencies, to improve provisioning efficiency.
  • Collaboration: Because Terraform configurations are stored as code, you can manage them with version control systems. HCP Terraform supports running Terraform in a reliable, consistent environment.

Terraform CLI (Command-Line Interface) Basics

Terraform CLI is a free, source-available Terraform edition under the BUSL that provides a command-line interface (CLI). With Terraform CLI, you can manage thousands of resources and services across multiple cloud providers. It also manages configuration, plugins, infrastructure, and state.

Features of Terraform CLI

Let’s look at the key features of Terraform CLI.

  • Initialising Working Directories

Working directories provide configuration content. They let you store modules, settings, cached plugins, and state data. Terraform uses and automatically manages the hidden .terraform directory.

The terraform init command initialises a working directory. You cannot run terraform plan or terraform apply without first initialising the working directory.

  • Writing and Modifying Code

The Terraform language is the primary interface for defining infrastructure configurations. Terraform workflows therefore depend on this language.

  • Provisioning Infrastructure

Terraform's primary task is to create, modify, and destroy infrastructure resources to match the desired Terraform configuration. Provisioning is Terraform's core function, and it depends on three commands: plan, apply, and destroy.

First, the Terraform plan command evaluates the desired state of all resources. Next, Terraform creates a plan based on the difference between the desired state and the current state.

When you run Terraform apply, Terraform applies the plan to provision infrastructure according to the desired state. Lastly, the Terraform destroy command deletes resources in the existing configuration as required.

  • Authenticating

Terraform integrates with HCP Terraform, which can be integrated as either a front-end or a back-end. Know that integrations need authentication. 

Terraform uses login and logout commands to manage authentication and API tokens for Terraform accounts.

  • Automating Terraform

You can automate Terraform workflows using Amazon S3. In this method, you will use the hashicorp/terraform:light Docker image to run Terraform in a Docker container.

You can also use GitHub Actions to automate HCP Terraform workflows. Use the hashicorp/setup-terraform action to install a pinned version, run fmt, validate and plan on pull requests, and run apply after merge. With this approach, you can deploy a publicly accessible web server from a workspace.

  • Managing Plugins

Terraform uses plugins or providers to manage resources. It downloads plugins from the source registry based on the configuration's requirements. It also supports caching downloaded plugins.

Terraform also supports specifying a local or HTTPS mirror from which to install plugins.

OpenTofu

OpenTofu is an open-source Infrastructure as Code (IaC) tool that is compatible with Terraform. It was created as a fork of Terraform after HashiCorp changed Terraform's license from the open-source MPL 2.0 to the Business Source License (BSL).

The table below shows the differences between the Terraform CLI and OpenTofu.

FeaturesTerraform CLIOpenTofu
LicenseBSL 1.1MPL 2.0
Managed byHashiCorp (an IBM company)Linux Foundation
CLI commandsterraform plan, terraform applytofu plan, tofu apply
Client-side state and plan encryptionIt doesn't provide a CLI command for client-side state encryption. So you rely on an encrypted backend (S3 with KMS) and access controls.It supports client-side state and plan encryption.

Terraform Installation

Terraform works with many platforms and services, such as AWS, Google Cloud, Microsoft Azure, and more. This tutorial covers installing Terraform on Windows for use with AWS.

1. Installing Terraform Manually

You can install Terraform CLI by installing a pre-compiled executable. The other option is to compile Terraform from source.

Let’s start with the first option: ‘a pre-compiled executable’.

  • First, download the appropriate Terraform software for your operating system using the link below:

Download Terraform

  • Ensure that the directory containing the Terraform binary is included in your system’s PATH.
  • For Windows, get the semicolon-separated list of locations in your PATH.

Path

  • Then move the Terraform executable to one of those locations.

move Downloads\terraform …

  • If you are using Linux or macOS, you can use the command below to get the colon-separated list of locations in your PATH.

echo $PATH

  • Then, move the Terraform executable to any listed location using the command below:

mv ~/Downloads/terraform /usr/local/bin/

(Documentation Source)

Let’s look at the procedure for the second option: ‘compile from source’.

  • Clone the HashiCorp Terraform repository using the command below:

git clone

  • Then navigate to the new directory using the command below:

cd terraform

  • Use the command below to compile and store the binary.

go install

  • Then, ensure that the Terraform binary is available in your system’s PATH, as you did in the earlier section based on your operating system.

2. Installing Terraform Using a Package Manager

Chocolatey is an open-source package management system for Windows. Let’s see how to use Chocolatey to install Terraform.

  • You can use this package manager to install Terraform using the command below:

choco install terraform

  • Then verify the installation as described in the manual installation section.

3. Verifying the Installation

  • To verify the installation on Windows, open a new terminal session.
  • Use the command below to list Terraform's available commands:

terraform -help

  • You can add the –help flag to learn more about available options.
  • For example, you can use the command below to learn more about Terraform plans.

terraform plan -help

4. Enabling Tab Completion

  • To enable tab completion, run the following Bash command to ensure the configuration file exists in the selected shell.

touch ~/.bashrc

  • Then, use the command below to install the autocomplete package.

terraform -install-autocomplete

  • Restart your shell after you finish installing autocomplete.

Subscribe MindMajix YouTube Channel

How Does Terraform Work?

Terraform connects to external applications through APIs. Terraform providers enable Terraform to interact with external APIs and services.

The core Terraform Workflow has three stages: write, plan, and apply. Let’s see how they work:

  1. Write: In the first stage, you decide which resources and services your application needs.
  2. Plan: In this stage, Terraform prepares a plan that describes the needed infrastructure based on the existing infrastructure and configuration.
  3. Apply: Terraform applies the changes in the order defined by the plan, while respecting resource dependencies.

Terraform HashiCorp Configuration Language (HCL) - A Deep Dive

HCL is HashiCorp's configuration language, used to define IT infrastructure in a human-readable, structured format.

  • Resources

A resource is an infrastructure object that you can create with Terraform. It can be a compute instance, virtual network, or DNS record.

You can add or remove resources from your configuration when you need to change the infrastructure. You can also refactor collections of resources into reusable modules.

  • Data Sources

Terraform can fetch data from sources such as external Terraform workspaces, APIs, and function outputs. To access data from a data source, configure the data block and specify its arguments.

  • Variables

You can add variable blocks to define an input interface for modules in your configuration. A variable block allows module consumers to customise module behaviour without changing the module’s source code.

You can use var.<NAME> syntax if you want to reference a variable in other parts of the configuration.

Example:

A web server configuration can replace hardcoded values with variables.

resource "aws_instance" "web" {
  ami           = data.aws_ami.ubuntu.id
  instance_type = "t2.micro"
  subnet_id     = "subnet-12345"

  tags = {
    Environment = "dev"
    Name        = "dev-web-server"
  }
}

You can use the sensitive argument when you want to define a variable for sensitive data. It prevents Terraform from displaying the value in CLI output. The sensitive data can be an API key or password.

Example:

variable "database_password" {
  type        = string
  description = "Password for the RDS database instance"
  sensitive   = true
}
  • Locals and Outputs

You can use locals in Terraform to assign names to expressions. This lets you reuse the name instead of repeating the expression.

You can use an output block to allow child modules to expose resource attributes to parent modules.

Example

If you want to expose the ID and IP address of your configuration’s web server, you can add two output blocks.

output "instance_id" {
  description = "ID of the EC2 instance"
  value       = aws_instance.web.id
}

output "instance_ip" {
  description = "Private IP address of the EC2 instance"
  value       = aws_instance.web.private_ip
}

resource "aws_instance" "web" {
  # …
}
  • Dynamic blocks

You can use dynamic blocks to produce nested blocks rather than a complex typed value. In particular, it generates a nested block for each element of the complex value.

Example:

resource "aws_elastic_beanstalk_environment" "tfenvtest" {
  name                = "tf-test-name"
  application         = aws_elastic_beanstalk_application.tftest.name
  solution_stack_name = "64bit Amazon Linux 2018.03 v2.11.4 running Go 1.12.6"

  dynamic "setting" {
    for_each = var.settings
    content {
      namespace = setting.value["namespace"]
      name = setting.value["name"]
      value = setting.value["value"]
    }
  }
}
  • State Management

State management includes state storage and S3 native state locking.

    • State storage and locking

Backends determine where state is stored. The local backend stores state in a JSON file on disk. When you use a non-local backend, Terraform does not persist state to disk.

Terraform can lock your state for all operations that can write state. This prevents other operations from acquiring the lock and modifying the state at the same time.

    • S3 native state locking

The S3 backend stores state in an S3 bucket. It supports state locking. All you need to do is set the use_lockfile argument to true. This eliminates the need for a DynamoDB state-locking table.

Example:

The bucket name is mybucket, where Terraform writes state to the key path/to/my/key.

terraform {
  backend "s3" {
    bucket = "mybucket"
    key    = "path/to/my/key"
    region = "us-east-1"
  }
}
  • Terraform Workspaces

Terraform allows you to use multiple workspaces using the backends, including azureRM, Consul,kubernetes, Postgres, and Remote.

If you run terraform plan in a new workspace, Terraform cannot access resources of other workspaces. To manage resources, switch workspaces.

  • Terraform State Commands

The following are some of the Terraform state commands:

    • terraform state show <address> - It displays the details of a resource.
    • terraform state list - It lists resources tracked in state.
    • terraform state rm - It removes a resource from state without destroying the real resource.
    • terraform state mv - It moves a resource to a different state address.
    • terraform state pull - It downloads the current state.
    • terraform state push - It uploads a local state to the configured backend.
  • Terraform Modules

Terraform modules are reusable collections of Terraform configuration files. You can use modules to define and manage infrastructure. They help reduce duplication, organise code, and standardise infrastructure deployments across environments.

    • Writing a Terraform module: A Terraform module contains main.tf, variables.tf, and outputs.tf. The root module calls child modules to create reusable infrastructure components.
    • Module versioning: It helps you control which module release your Terraform configuration uses. By pinning a version, you can prevent unexpected configuration changes when a module is updated.
    • Using modules from the Terraform Registry: You can find reusable modules published by HashiCorp in the Terraform Registry.
  • Safe Refactoring

It is the process of restructuring Terraform code without recreating, deleting, or modifying existing IT infrastructure. You can use this approach to improve code orchestration without disturbing resource identity in Terraform state.

It includes the following techniques:

    • Using removed blocks: A removed block removes a resource from Terraform state without changing the real infrastructure.
    • Using moved blocks: You can rename resources or move them into modules without treating them as new resources.
    • Using import blocks: An import block brings an existing infrastructure resource under Terraform management without creating a new instance.
  • Secret Handling

Terraform supports secure management of sensitive information such as passwords, API tokens, database credentials, and cloud access keys. These features help prevent accidental exposure in configuration files, version control,  logs, and Terraform state.

Terraform's ephemeral variables and resources can help prevent certain sensitive values from being persisted in state.

  • Lifecycle Rules and Validation

Terraform lifecycle rules control how Terraform creates, replaces, updates, and secures resources. You can define them inside a resource's lifecycle block. Some lifecycle arguments include:

    • create_before_destroy – It creates a replacement resource before destroying the existing one, where the provider and infrastructure allow it.
    • ignore_changes – It ignores changes to specified attributes during update planning.
    • prevent_destroy – It rejects plans that would destroy the resource while this lifecycle rule remains in configuration.

Preconditions and postconditions: You can use preconditions and postconditions inside a resource's lifecycle block. They help verify assumptions before an operation and check results after it.

Check blocks: They let you define broader assertions, including infrastructure health checks. Failed assertions produce warnings rather than blocking an operation.

  • Terraform Testing

Terraform testing helps you verify that infrastructure configurations behave as expected before deployment. It validates modules, identifies configuration errors, and reduces deployment risk.

The following are the key Terraform testing commands:

    • terraform validate – Use this command to check configuration syntax and internal consistency.
    • terraform fmt -check – It checks whether files follow Terraform formatting conventions.
    • terraform test – Runs Terraform tests defined in .tftest.hcl files.

 

  • Terraform CI/CD Workflow

Terraform CI/CD workflow automates infrastructure changes while ensuring that proposed changes are reviewed before deployment.

The typical CI/CD workflow is as follows:

    • Committing Terraform changes to Git
    • Formatting, validating, testing, scanning, authenticating with OIDC, and generating a plan
    • Reviewing additions, updates, replacements, and deletions
    • Approving the pull request
    • Obtaining OIDC credentials for the deployment job
    • Verifying the approved plan
    • Applying the reviewed changes
    • Checking the deployment results.

HashiCorp Cloud Platform (HCP) Terraform

HCP Terraform is a SaaS application with an intuitive user interface. It offers a stable environment with a private registry for sharing modules. It integrates with the Terraform CLI, Bitbucket, GitHub, and GitLab. 

Moreover, it publishes configuration modules in the HCP Terraform Private Registry, which includes approved infrastructure patterns.

Features of HCP Terraform

HCP Terraform lets Terraform run in a consistent, reliable environment. It also enables you to collaborate on Terraform workflows. HCP Terraform also provides shared data, policy enforcement, sensitive data management, access controls, a private registry, and more.

Terraform Workflow

HCP Terraform generally runs the Terraform CLI to provision infrastructure. The Terraform workflow includes the CLI, remote Terraform execution, a workspace-based organisation model, version control integration, remote state management, and a private Terraform module registry.

The workflow includes workspaces, drift detection, variable sets, and run tasks.

Terraform Workflow
  • Drift Detection: HCP Terraform identifies differences between the actual infrastructure and the configuration or state Terraform expects.
  • Projects: They help organise related workspaces and infrastructure resources into logical groups. This lets you manage IT infrastructure across applications and environments easily.
  • Variable Sets: They reuse common configuration values and credentials across multiple workspaces.
  • Agents: They execute Terraform runs in infrastructure environments. HCP Terraform hosted workers cannot directly access these environments.

Integrations

In general, you can access all HCP Terraform features via APIs. So, other services can create workspaces, configure workspaces, upload configurations, and start Terraform runs. HCP Terraform also lets you send notifications to other systems.

In addition, Terraform has the ’run tasks’ feature that allows HCP Terraform to execute tasks in external systems. This happens at specific points in the HCP Terraform run cycle.

Access Control

HCP Terraform’s access controls and policies can simplify permission management in large enterprises.

Using Sentinel as a policy-as-code framework, HCP Terraform helps restrict compute VM sizes, streamline major updates to defined maintenance windows, and more. HCP Terraform also enables granular policies for organisation-level provisioning.

Terraform Enterprise

This Terraform offering allows you to self-host HCP Terraform. In other words, it provides a private HCP Terraform instance. You can customise resource limits and enable security and compliance options with Terraform Enterprise. It also supports private networking and job scaling.

Terraform administration has two domains: infrastructure administration and application administration. Infrastructure administration covers upgrades, monitoring, and backups. Application administration covers tasks and configurations within applications.

Terraform MCP Server and Terragrunt

The Terraform MCP server is a lightweight server that lets AI models connect securely to external systems, applications, and data sources. It helps AI assistants examine Terraform configurations, interact with infrastructure workflows, and access providers and more.

This server helps retrieve information about Terraform providers and modules. It also helps you inspect Terraform plans and state-related information. It has permissions and execution controls that govern AI assistant actions.

Safety Note: Use read-only or least-privilege tokens. Keep production credentials out of reach, and review every plan yourself. Don't let an assistant run terraform apply unreviewed.

It offers the following benefits to users:

  • Access provider documentation in real time, eliminating reliance on outdated data. 
  • Integrate directly with public Terraform Registry APIs
  • Create, update, and delete workspaces
  • Enable Terraform configuration with high-level accuracy.

Terragrunt

Terragrunt is an open-source IaC orchestrator. It works with Terraform to simplify infrastructure management. It orchestrates Terraform and OpenTofu configurations using HCL.

You can use Terragrunt to reduce code duplication by reusing shared configuration. Terragrunt helps define dependencies between infrastructure components. It simplifies configuring remote state backends. It also helps manage development, testing, staging, and production environments. 

Code Quality, Security and Cost Tools

Terraform projects use code-quality, security, and cost-estimation tools to identify issues before deployment.

  • TFLint: A Terraform linter that checks deprecated syntax, identifies potential errors, and provider-specific issues. It can enforce naming and best-practice rules.
  • Infracost: Estimates the cost impact of Terraform changes before deployment. It shows cost differences in pull requests and supports FinOps policies.
  • Checkov: It scans Terraform configurations and plans for security and compliance misconfigurations.
  • terraform-docs: It generates documentation for Terraform modules, including inputs and outputs.

Terraform Policy and Use Cases

Terraform policy (public beta) is a HCL-based policy-as-code framework that integrates directly with Terraform providers. It requires Terraform 1.16 or later and runs with full enforcement inside HCP Terraform. You can write policies using HCL.

The following is the policy workflow:

  • Writing policies for resources, providers, and modules
  • Testing policies locally using the tfpolicy command
  • Commit policies to a version control system repository and connect to HCP Terraform
  • Creating policy sets and evaluating policies
  • Starting a workspace run for policy evaluations
  • Reporting the results in HCP Terraform.

Let’s discover more about Terraform policy.

Sentinel is HashiCorp's policy-as-code tool that controls the use of HashiCorp products. You can use Sentinel to enforce policies during Terraform runs. Open Policy Agent (OPA) is a policy engine that you can use to evaluate policies. This lets you validate infrastructure configurations and plans effectively.

You can use Terraform policy to ensure organisational standards and control non-compliant resources.

Terraform Use Cases

Terraform offers numerous features, each serving a different purpose. Let's look at some common use cases:

  • Infrastructure as Code

Terraform simplifies automation through Infrastructure as Code (IaC). This makes it easy to automate the provisioning of infrastructure such as firewalls, servers, and databases. It also enables teams to codify, share, manage, and apply infrastructure configurations and policies through a consistent workflow.

  • Multi-Cloud Deployment

Terraform simplifies large-scale infrastructure with multi-cloud deployment. This approach lets Terraform manage multiple cloud providers and cross-cloud dependencies effectively. It also manages Microsoft Azure directory resources and Google Cloud load balancers.

For example, one project can create an AWS VPC, Microsoft Entra ID (formerly Azure AD) groups through the azuread provider, and a Google Cloud load balancer, all in the same workflow.

  • Self-Service Clusters

Self-service capabilities let you provision and manage infrastructure on demand. You can create Terraform modules to codify standards for deploying and managing services. Terraform can integrate with ServiceNow to automatically generate new infrastructure requests.

  • Managing Kubernetes

Kubernetes is an open-source container orchestration platform. Terraform supports AKS, EKS, and GKE for deploying and managing Kubernetes clusters.

  • Deployment, Scaling, and Monitoring Tools

Terraform can efficiently support the deployment, scaling, and monitoring of infrastructure for multi-tier applications. It connects web servers, databases, caching servers, API servers, and routing meshes.

It also manages dependencies between resources effectively. Because the web server depends on the database, Terraform creates the database first.

  • Policy Compliance and Management

Terraform uses an HCL-based policy framework for compliance. This framework uses HashiCorp Configuration Language (HCL) to define rules and control Terraform infrastructure configurations. Sentinel and OPA frameworks also support policy compliance.

CI/CD workflows can also automate infrastructure deployments. Terraform also automates key networking tasks such as updating load balancer member pools and applying firewall policies.

Terraform Certifications and Pricing

HashiCorp recently updated its certification lineup; its lab-based exam is now called the Advanced credential. Check HashiCorp's certification page for the current exam names before you book. The following are the various Terraform certifications:

MindMajix's Terraform training covers the essential topics that are required for these exams.

HCP Terraform Subscription Plans

The table below shows the HCP Terraform product plans as of October 2026.

HCP Terraform PlanPricing per month per resource
Essentials$0.10
Standard$0.47
Premium$0.99
EnterpriseCustom pricing

Frequently Asked Questions

1. Is learning Terraform easy for beginners?

Yes, beginners can learn Terraform if they gain basic knowledge of cloud and IT infrastructure concepts. Basic proficiency in Linux, networking, and various cloud platforms helps.

2. How long will it take to learn Terraform?

You can become familiar with Terraform basic concepts within 2-4 weeks. It will take 2-3 months to become comfortable with Terraform projects. You can become proficient with the Terraform platform in 3-6 months.

3. What is the difference between Ansible and Terraform?

Terraform is mainly used to provision infrastructure declaratively, such as networks, virtual machines, databases and DNS records. Ansible is mainly used for configuration management and application deployment, such as installing packages and configuring services on servers.

4. Can I use Terraform with AWS, Azure, and Google Cloud?

Yes, you can use Terraform with these cloud platforms through their providers. You can provision and manage virtual machines, networks, storage, and databases across these platforms using Terraform.

5. Can learning Terraform help with DevOps careers?

Yes, Terraform is a key skill for devops, cloud, platform engineering, and infrastructure automation roles.

Conclusion

In summary, you have learned about Terraform features, different Terraform editions, installation methods, and common use cases. This article should have helped you understand Terraform certifications, pricing, and more.

For guided, hands-on practice, explore the Terraform course from MindMajix. By the end of the training, you will have a practical understanding of the platform and gain a competitive advantage in the IT field.

logoOn-Job Support Service

Online Work Support for your on-job roles.

jobservice
@Learner@SME

Our work-support plans provide precise options as per your project tasks. Whether you are a newbie or an experienced professional seeking assistance in completing project tasks, we are here with the following plans to meet your custom needs:

  • Pay Per Hour
  • Pay Per Week
  • Monthly
Learn MoreContact us
Course Schedule
NameDates
Terraform TrainingOct 31 to Nov 15View Details
Terraform TrainingNov 03 to Nov 18View Details
Terraform TrainingNov 07 to Nov 22View Details
Terraform TrainingNov 10 to Nov 25View Details
Last updated: 24 Oct 2026
About Author

Mohammed Zaid is a technical content creator and digital marketer with good experience in translating complex technologies into accessible insights. He specializes in writing expert articles on Agentic AI, Generative AI, LLMs, data strategy, and cloud computing for a global audience.
 

read less