DEV Community

Mayur Bodhare
Mayur Bodhare

Posted on

Terraform Explained: Infrastructure as Code for Beginners

Imagine you are working on a project that needs the following infrastructure:

  • One virtual machine to run your application.
  • One storage bucket to store files.
  • One database to store application data.
  • A network to connect everything.

You open your cloud provider's dashboard and start creating these resources manually.

Everything works fine.

Now imagine your company wants to create the same infrastructure for development, testing, and production environments.

You have to repeat the entire process.

What happens if someone forgets to configure a security rule? What if you need to recreate the same infrastructure in another region? What if you accidentally delete a resource?

Managing infrastructure manually becomes difficult as your application grows.

Wouldn't it be better if you could describe your infrastructure using code and let a tool create it automatically?

This is exactly the problem Terraform solves.

Terraform is an Infrastructure as Code (IaC) tool that allows us to define, provision, update, and destroy infrastructure using configuration files.

Instead of manually creating cloud resources, we describe what we need in code, and Terraform communicates with the cloud provider to make it happen.

In this article, we'll understand Terraform from scratch, explore its architecture, write our first Terraform configuration, provision an AWS resource, understand state files, variables, outputs, modules, and important Terraform commands.

Versions used in this article:

  • Terraform CLI: 1.17.2.
  • AWS Provider: HashiCorp AWS provider. Check the latest compatible version in the Terraform Registry.
  • Configuration language: HCL2.

Table of contents

What is Terraform?

Terraform is an open-source Infrastructure as Code (IaC) tool developed by HashiCorp.

It allows us to define infrastructure using configuration files and automatically provision that infrastructure through cloud provider APIs.

In simple words, instead of creating infrastructure manually through a cloud dashboard, we write code describing what infrastructure we need.

Terraform reads that code and creates the required resources.

For example, suppose Ravi wants to create an AWS S3 bucket.

Instead of opening the AWS console and creating the bucket manually, Ravi writes a Terraform configuration:

resource "aws_s3_bucket" "my_bucket" {

  bucket = "ravi-terraform-demo-bucket"
}
Enter fullscreen mode Exit fullscreen mode

Now Terraform can create the bucket using the AWS provider.

The important idea is that we describe the desired infrastructure, and Terraform figures out what operations are required to achieve that state.

Terraform is commonly used for:

  • Creating virtual machines.
  • Creating storage buckets.
  • Creating virtual networks.
  • Provisioning databases.
  • Configuring security groups.
  • Managing cloud infrastructure.
  • Recreating infrastructure across environments.

The problem Terraform solves

Let's understand the problem with a practical example.

Suppose Meera is working on an application hosted on AWS.

She needs the following resources:

                 AWS CLOUD
                     |
          +----------+----------+
          |          |          |
          v          v          v
       EC2 VM      S3 Bucket   Database
          |
          v
      Application
Enter fullscreen mode Exit fullscreen mode

Without Infrastructure as Code, Meera might create each resource manually using the AWS console.

Now imagine her team needs the same infrastructure in three environments:

  • Development.
  • Testing.
  • Production.

The team has to repeat the configuration process.

This creates several problems:

  1. Manual work: Creating resources repeatedly takes time.
  2. Human errors: Someone might forget an important configuration.
  3. Inconsistency: Development and production environments may have different configurations.
  4. Difficult maintenance: Updating infrastructure requires repeating manual operations.
  5. Poor reproducibility: Recreating the exact infrastructure becomes difficult.

Now introduce Terraform.

Instead of manually creating resources, we write their configuration once.

              TERRAFORM CODE
                    |
                    |
          +---------+---------+
          |         |         |
          v         v         v
       DEV ENV    TEST ENV   PROD ENV
          |         |         |
          v         v         v
        AWS       AWS        AWS
      Resources Resources  Resources
Enter fullscreen mode Exit fullscreen mode

We can reuse the same configuration with different input values to provision different environments.

This makes infrastructure easier to manage, reproduce, and maintain.

What Infrastructure as Code means

Infrastructure as Code (IaC) is the practice of managing infrastructure through machine-readable configuration files instead of manually configuring everything.

Let's understand the difference.

Without IaC:

Developer
    |
    v
Open Cloud Console
    |
    v
Create Virtual Machine
    |
    v
Configure Network
    |
    v
Create Storage
    |
    v
Configure Security
Enter fullscreen mode Exit fullscreen mode

With IaC:

Developer
    |
    v
Write Configuration Files
    |
    v
Terraform
    |
    v
Cloud Provider API
    |
    v
Infrastructure Created
Enter fullscreen mode Exit fullscreen mode

The infrastructure configuration becomes code.

We can also store this code in GitHub, just like application source code.

This gives us several benefits:

  • Version control: Track infrastructure changes.
  • Reusability: Reuse existing configurations.
  • Consistency: Create similar environments using the same configuration.
  • Automation: Reduce repetitive manual operations.
  • Collaboration: Multiple developers can work on infrastructure code.
  • Reproducibility: Recreate infrastructure from configuration.

For example, if your application needs a new storage bucket, you can update the Terraform configuration and review the proposed infrastructure changes before applying them.

That's the main idea behind Infrastructure as Code.

How Terraform works

Now let's understand how Terraform communicates with cloud platforms.

Terraform does not directly know how to create every cloud resource.

For example, creating an AWS EC2 instance requires AWS-specific API calls.

Creating an Azure virtual machine requires Azure-specific API calls.

So how does Terraform handle different cloud platforms?

It uses something called Providers.

Providers and resources

A provider is a plugin that allows Terraform to communicate with a particular infrastructure platform or service.

Examples:

  • AWS Provider.
  • AzureRM Provider.
  • Google Cloud Provider.
  • Kubernetes Provider.
  • Docker Provider.

Each provider exposes different resource types and data sources.

Resource

A resource represents an infrastructure object that Terraform manages.

For example:

  • aws_instance: AWS EC2 instance.
  • aws_s3_bucket: AWS S3 bucket.
  • azurerm_virtual_machine: Azure virtual machine.
  • google_storage_bucket: Google Cloud Storage bucket.

Let's understand the relationship.

                 TERRAFORM
                     |
                     v
                  PROVIDER
                     |
          +----------+----------+
          |          |          |
          v          v          v
         AWS       AZURE       GCP
          |          |          |
          v          v          v
       Resources  Resources  Resources
          |          |          |
          v          v          v
       EC2, S3     VM, VNet   VM, GCS
Enter fullscreen mode Exit fullscreen mode

Terraform uses the provider plugin to communicate with the external platform.

The provider translates Terraform's requested operations into API requests that the platform understands.

For example:

Terraform Configuration
          |
          v
    AWS Provider
          |
          v
      AWS APIs
          |
          v
     Create S3 Bucket
Enter fullscreen mode Exit fullscreen mode

Without a provider, Terraform cannot manage resources specific to that platform.

Terraform and cloud platforms

Terraform supports many infrastructure platforms through its provider ecosystem.

Some popular integrations include:

  • Amazon Web Services (AWS).
  • Microsoft Azure.
  • Google Cloud Platform (GCP).
  • Kubernetes.
  • Docker.
  • VMware.
  • Cloudflare.

It is important to understand that Terraform does not automatically support every service offered by every cloud provider.

The available resources and capabilities depend on the providers and their implementations.

You can discover providers through the Terraform Registry:

https://registry.terraform.io/

For example, if you want to work with AWS, you need the AWS provider.

If you want to work with Azure, you need the Azure provider.

The same Terraform workflow can be used across different platforms, but their provider configurations and resource definitions are different.

Understanding HCL

Terraform uses a configuration language called HCL.

HCL stands for HashiCorp Configuration Language.

It is a human-readable language designed for defining configuration.

Instead of writing complex programming logic, we describe the infrastructure we want.

For example:

resource "aws_s3_bucket" "my_bucket" {

  bucket = "my-terraform-demo-bucket"
}
Enter fullscreen mode Exit fullscreen mode

Let's understand the syntax.

resource "aws_s3_bucket" "my_bucket" {
           |               |
           |               |
           v               v
       Resource Type   Resource Name
}
Enter fullscreen mode Exit fullscreen mode
  • resource: Declares an infrastructure resource.
  • aws_s3_bucket: Specifies the type of resource.
  • my_bucket: A name used to identify this resource inside Terraform.
  • bucket: An argument provided to the AWS resource.

Notice that my_bucket is not the actual bucket name.

The actual bucket name is the value assigned to the bucket argument.

HCL supports different block types, including:

  • terraform: Terraform configuration.
  • provider: Provider configuration.
  • resource: Infrastructure resource.
  • variable: Input variable.
  • output: Output value.
  • module: Module declaration.
  • data: Data source.

We'll use these blocks throughout this article.

Your first Terraform configuration

Let's create our first practical Terraform project.

We'll create an AWS S3 bucket using Terraform.

An S3 bucket is a storage container in AWS that can store files and objects.

First, install Terraform and configure the AWS CLI on your machine.

Check the installation:

terraform version
Enter fullscreen mode Exit fullscreen mode

Example output:

Terraform v1.17.2
on windows_amd64
Enter fullscreen mode Exit fullscreen mode

Your operating system and architecture will determine the platform information shown.

Now create a project directory:

mkdir terraform-demo
cd terraform-demo
Enter fullscreen mode Exit fullscreen mode

Create a file named:

main.tf
Enter fullscreen mode Exit fullscreen mode

Terraform configuration files use the .tf extension.

Our project will initially look like this:

terraform-demo/
    |
    +-- main.tf
Enter fullscreen mode Exit fullscreen mode

Add the following configuration to main.tf:

terraform {

  required_providers {

    aws = {
      source = "hashicorp/aws"
      version = ">= 5.0.0"
    }
  }
}

provider "aws" {

  region = "ap-south-1"
}

resource "aws_s3_bucket" "my_bucket" {

  bucket = "my-unique-terraform-demo-bucket-12345"
}
Enter fullscreen mode Exit fullscreen mode

Replace the bucket name with a globally unique name.

Let's understand the configuration.

1. Terraform block

terraform {

  required_providers {

    aws = {
      source = "hashicorp/aws"
      version = ">= 5.0.0"
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

This block tells Terraform which provider plugin is required.

Here:

  • aws is the local provider name.
  • hashicorp/aws identifies the provider source.
  • version specifies the acceptable provider version range.

The provider version is separate from the Terraform CLI version.

2. Provider block

provider "aws" {

  region = "ap-south-1"
}
Enter fullscreen mode Exit fullscreen mode

This configures the AWS provider.

Here, ap-south-1 represents the Mumbai AWS region.

3. Resource block

resource "aws_s3_bucket" "my_bucket" {

  bucket = "my-unique-terraform-demo-bucket-12345"
}
Enter fullscreen mode Exit fullscreen mode

This declares an S3 bucket that Terraform should manage.

Now we have described the infrastructure we want.

But how will Terraform access our AWS account?

That's where authentication comes into the picture.

AWS authentication and access keys

To create AWS resources, Terraform needs permission to communicate with AWS APIs.

For example, if Terraform needs to create an S3 bucket, AWS must verify that the request comes from an authorized identity.

For local development, one common authentication method is AWS access keys.

An AWS access key consists of:

  1. Access Key ID.
  2. Secret Access Key.

Think of them as credentials that allow an application or tool to authenticate with AWS.

             TERRAFORM
                 |
                 | AWS API Request
                 |
                 v
            AWS PROVIDER
                 |
                 | Credentials
                 |
          +------+------+
          |             |
          v             v
     Access Key ID   Secret Access Key
          |             |
          +------+------+
                 |
                 v
             AWS CLOUD
                 |
                 v
          Authentication
                 |
                 v
           API Operations
Enter fullscreen mode Exit fullscreen mode

For example, you can configure AWS credentials using the AWS CLI:

aws configure
Enter fullscreen mode Exit fullscreen mode

It will ask for:

AWS Access Key ID: YOUR_ACCESS_KEY_ID

AWS Secret Access Key: YOUR_SECRET_ACCESS_KEY

Default region name: ap-south-1

Default output format: json
Enter fullscreen mode Exit fullscreen mode

Alternatively, you can configure environment variables.

For Linux or macOS:

export AWS_ACCESS_KEY_ID="YOUR_ACCESS_KEY_ID"

export AWS_SECRET_ACCESS_KEY="YOUR_SECRET_ACCESS_KEY"

export AWS_REGION="ap-south-1"
Enter fullscreen mode Exit fullscreen mode

For PowerShell:

$env:AWS_ACCESS_KEY_ID="YOUR_ACCESS_KEY_ID"

$env:AWS_SECRET_ACCESS_KEY="YOUR_SECRET_ACCESS_KEY"

$env:AWS_REGION="ap-south-1"
Enter fullscreen mode Exit fullscreen mode

Now the AWS provider can use these credentials without storing them directly in the Terraform configuration.

Important security note:

Never hardcode access keys inside .tf files or commit them to GitHub.

Also, access keys are not the only authentication method.

For production environments, prefer temporary credentials and IAM roles or other workload identity mechanisms where supported.

AWS authentication is specific to AWS. Azure and Google Cloud use their own authentication mechanisms.

The Terraform command workflow

Now that we have written our Terraform configuration, let's understand how to execute it.

Terraform provides several commands to manage infrastructure.

The most important commands are:

Write .tf Configuration
          |
          v
    terraform init
          |
          v
    terraform fmt
          |
          v
   terraform validate
          |
          v
    terraform plan
          |
          v
    terraform apply
          |
          v
    Infrastructure Created
          |
          v
   terraform destroy
          |
          v
    Infrastructure Deleted
Enter fullscreen mode Exit fullscreen mode

Let's understand each command.

terraform init

The first command we execute in a new Terraform project is:

terraform init
Enter fullscreen mode Exit fullscreen mode

The init command initializes the Terraform working directory.

But why do we need it?

Remember that Terraform uses providers to communicate with cloud platforms.

Our configuration uses the AWS provider.

Terraform needs to download and install that provider before it can manage AWS resources.

terraform init performs initialization tasks such as:

  • Downloading required providers.
  • Installing required modules.
  • Initializing the configured backend.
  • Preparing the working directory.

Run:

terraform init
Enter fullscreen mode Exit fullscreen mode

Simplified example output:

Initializing the backend...

Initializing provider plugins...

- Finding hashicorp/aws versions matching ">= 5.0.0"...

- Installing hashicorp/aws...

- Installed hashicorp/aws successfully

Terraform has been successfully initialized!
Enter fullscreen mode Exit fullscreen mode

The exact version and output will depend on the provider release selected by Terraform.

Behind the scenes

Terraform reads the provider requirements from the configuration.

It downloads the required provider plugin and stores the installation information in the .terraform directory.

It also creates or updates the dependency lock file:

.terraform.lock.hcl
Enter fullscreen mode Exit fullscreen mode

This file records the selected provider versions and checksums.

You should commit .terraform.lock.hcl to version control so your team can use consistent provider selections.

terraform fmt and validate

After initialization, we should format and validate our configuration.

These commands solve two different problems.

1. terraform fmt

The fmt command automatically formats Terraform configuration files.

For example:

terraform fmt
Enter fullscreen mode Exit fullscreen mode

It fixes formatting issues such as indentation and spacing.

You don't have to manually align every block.

To check formatting without changing files:

terraform fmt -check
Enter fullscreen mode Exit fullscreen mode

2. terraform validate

The validate command checks whether the configuration is syntactically valid and internally consistent.

Run:

terraform validate
Enter fullscreen mode Exit fullscreen mode

Example output:

Success! The configuration is valid.
Enter fullscreen mode Exit fullscreen mode

But what exactly does validation check?

It checks things such as:

  • Valid Terraform syntax.
  • Correct block structure.
  • Valid references.
  • Required arguments.
  • Configuration consistency.

One important distinction:

terraform validate does not verify that your AWS credentials work or that AWS will successfully create the resource.

That is why we have the next command.

terraform plan

This is one of the most important Terraform commands.

terraform plan
Enter fullscreen mode Exit fullscreen mode

The plan command creates an execution plan.

It compares your desired infrastructure configuration with the current infrastructure and Terraform state.

It then displays what Terraform intends to do.

For example, suppose you have declared an S3 bucket:

resource "aws_s3_bucket" "my_bucket" {

  bucket = "my-unique-terraform-demo-bucket-12345"
}
Enter fullscreen mode Exit fullscreen mode

But the bucket does not exist yet.

Terraform will show a plan to create it.

Simplified output:

Terraform will perform the following actions:

  # aws_s3_bucket.my_bucket will be created

  + resource "aws_s3_bucket" "my_bucket" {

      + bucket = "my-unique-terraform-demo-bucket-12345"

      + id = (known after apply)

      + arn = (known after apply)
    }

Plan: 1 to add, 0 to change, 0 to destroy.
Enter fullscreen mode Exit fullscreen mode

Let's understand the symbols:

+   Create a new resource

~   Update an existing resource

-   Destroy an existing resource

-/+ Destroy and recreate a resource

+/- Create a replacement before destroying the old resource
Enter fullscreen mode Exit fullscreen mode

The exact ordering of replacement symbols depends on the lifecycle operation.

The important point is that Terraform shows the proposed changes before making them.

Why is terraform plan important?

Imagine you accidentally change a configuration that causes an existing database to be destroyed.

If you directly execute an apply without reviewing the plan, you might make a destructive change.

With terraform plan, you can inspect the proposed changes first.

Think of it as a preview of infrastructure changes.

terraform apply

Once we are satisfied with the execution plan, we can apply it.

terraform apply
Enter fullscreen mode Exit fullscreen mode

Terraform displays the proposed changes and asks for confirmation.

Example:

Plan: 1 to add, 0 to change, 0 to destroy.

Do you want to perform these actions?

  Enter a value:

yes
Enter fullscreen mode Exit fullscreen mode

After entering yes, Terraform communicates with AWS and creates the S3 bucket.

Simplified output:

aws_s3_bucket.my_bucket: Creating...

aws_s3_bucket.my_bucket: Creation complete

Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
Enter fullscreen mode Exit fullscreen mode

Now the S3 bucket exists in AWS.

Behind the scenes

  1. Terraform reads the configuration.
  2. Terraform determines the required changes.
  3. The AWS provider receives the resource creation request.
  4. The provider communicates with AWS APIs.
  5. AWS creates the bucket.
  6. Terraform records the resource information in its state.

Notice that Terraform does not directly create the bucket itself.

The AWS provider communicates with AWS and performs the actual API operations.

terraform destroy

What happens when we no longer need the infrastructure?

For example, suppose Meera created an S3 bucket for testing and now wants to remove it.

We can use:

terraform destroy
Enter fullscreen mode Exit fullscreen mode

Terraform calculates which managed resources should be deleted.

Example output:

Terraform will perform the following actions:

  # aws_s3_bucket.my_bucket will be destroyed

Plan: 0 to add, 0 to change, 1 to destroy.

Do you really want to destroy all resources?

  Enter a value:
Enter fullscreen mode Exit fullscreen mode

After confirmation, Terraform asks the AWS provider to delete the bucket.

Simplified output:

aws_s3_bucket.my_bucket: Destroying...

aws_s3_bucket.my_bucket: Destruction complete

Destroy complete! Resources: 1 destroyed.
Enter fullscreen mode Exit fullscreen mode

Important: AWS S3 buckets must be empty before they can normally be deleted. If the bucket contains objects, the destroy operation may fail until those objects are removed.

Also, terraform destroy deletes resources managed by the current Terraform configuration and workspace. Never execute it in a production environment without reviewing its plan carefully.

Understanding Terraform state

So far, we have learned how Terraform creates and destroys infrastructure.

But here's an interesting question.

Suppose Terraform created an S3 bucket yesterday.

Today, you execute:

terraform plan
Enter fullscreen mode Exit fullscreen mode

How does Terraform know that the bucket already exists?

Does it recreate the bucket every time?

No.

Terraform maintains information about the infrastructure it manages using something called a State File.

The default local state file is:

terraform.tfstate
Enter fullscreen mode Exit fullscreen mode

Why Terraform needs a state file

A state file is used by Terraform to maintain the relationship between resources declared in configuration and the actual infrastructure objects.

It contains information such as:

  • Resource addresses.
  • Resource IDs.
  • Resource attributes.
  • Provider information.
  • Dependency-related information.
  • Metadata needed to manage infrastructure.

Let's understand with an example.

Our Terraform configuration declares:

resource "aws_s3_bucket" "my_bucket" {

  bucket = "my-unique-terraform-demo-bucket-12345"
}
Enter fullscreen mode Exit fullscreen mode

After successfully creating the bucket, Terraform records information about that resource in its state.

Conceptually:

           main.tf
              |
              |
              v
         TERRAFORM
              |
              | Create Resource
              v
          AWS CLOUD
              |
              v
           S3 Bucket
              |
              |
              v
        terraform.tfstate
              |
              v
       Resource Information
Enter fullscreen mode Exit fullscreen mode

The state file helps Terraform identify which real-world resource corresponds to aws_s3_bucket.my_bucket.

Now suppose we execute:

terraform plan
Enter fullscreen mode Exit fullscreen mode

Terraform uses the configuration, state, and refreshed information from the provider to determine whether any changes are required.

If the infrastructure already matches the desired configuration, Terraform generally reports:

No changes. Your infrastructure matches the configuration.
Enter fullscreen mode Exit fullscreen mode

This is why the state file is so important.

Behind the scenes

Terraform uses three important pieces of information:

  1. Configuration: What infrastructure do we want?
  2. State: What infrastructure does Terraform currently manage?
  3. Real infrastructure: What actually exists in the cloud?
       CONFIGURATION
        (Desired State)
              |
              |
              v
          TERRAFORM
              ^
              |
       STATE FILE
       (Known State)
              |
              |
              v
         CLOUD API
              |
              v
       REAL INFRASTRUCTURE
Enter fullscreen mode Exit fullscreen mode

Terraform compares these sources to determine what operations are required.

The state file is not simply a backup of your .tf files. It is an important record used to manage real infrastructure.

Local state vs remote state

By default, Terraform stores state locally in a file named:

terraform.tfstate
Enter fullscreen mode Exit fullscreen mode

This is called local state.

It works well when you are learning Terraform or experimenting with a small project.

But imagine a team of five developers working on the same infrastructure.

If each developer has a separate local state file, their state information can become inconsistent.

For example:

  • Developer A creates a virtual machine.
  • Developer B does not know that it exists.
  • Developer B applies another configuration using outdated state information.

This can create serious infrastructure management problems.

For team environments, we generally use remote state.

Remote state means storing Terraform state in a shared remote backend.

Examples include:

  • Amazon S3 with appropriate locking configuration.
  • HCP Terraform.
  • Other supported remote backends.
           DEVELOPER A
                |
                |
           DEVELOPER B
                |
                |
           DEVELOPER C
                |
                v
          REMOTE STATE
                |
                v
          SHARED STATE
Enter fullscreen mode Exit fullscreen mode

Remote backends can also provide state locking, which helps prevent conflicting operations when multiple users try to modify the same state simultaneously.

Important security point:

Terraform state can contain sensitive information, including credentials or passwords returned by providers.

Never commit terraform.tfstate to a public GitHub repository.

For production environments, use a properly secured remote backend, access controls, encryption, and state locking where supported.

Input variables

So far, we have hardcoded the S3 bucket name directly inside our configuration.

resource "aws_s3_bucket" "my_bucket" {

  bucket = "my-unique-terraform-demo-bucket-12345"
}
Enter fullscreen mode Exit fullscreen mode

But what if we want to create different buckets for different environments?

For example:

Development -> dev-bucket

Testing     -> test-bucket

Production  -> prod-bucket
Enter fullscreen mode Exit fullscreen mode

Do we need to modify the configuration every time?

No.

Terraform provides Input Variables.

Input variables allow us to pass values into our Terraform configuration instead of hardcoding them.

Let's create a file called:

variables.tf
Enter fullscreen mode Exit fullscreen mode

Add:

variable "bucket_name" {

  description = "Name of the S3 bucket"

  type = string

  default = "my-unique-terraform-demo-bucket-12345"
}
Enter fullscreen mode Exit fullscreen mode

Now update main.tf:

resource "aws_s3_bucket" "my_bucket" {

  bucket = var.bucket_name
}
Enter fullscreen mode Exit fullscreen mode

Notice:

var.bucket_name
Enter fullscreen mode Exit fullscreen mode

The var keyword is used to reference an input variable.

Now we can pass a different value without modifying the resource configuration.

For example:

terraform plan -var="bucket_name=my-dev-terraform-bucket-12345"
Enter fullscreen mode Exit fullscreen mode

Or create a file named:

terraform.tfvars
Enter fullscreen mode Exit fullscreen mode

Add:

bucket_name = "my-dev-terraform-bucket-12345"
Enter fullscreen mode Exit fullscreen mode

Terraform automatically loads the default terraform.tfvars file.

Now execute:

terraform plan
Enter fullscreen mode Exit fullscreen mode

Terraform uses the value from the variable file.

Behind the scenes

      variables.tf
           |
           v
      bucket_name
           |
           |
           v
      terraform.tfvars
           |
           v
      "my-dev-bucket"
           |
           v
       main.tf
           |
           v
      aws_s3_bucket
Enter fullscreen mode Exit fullscreen mode

Input variables make Terraform configurations reusable and configurable.

You can also declare variables with different types:

variable "environment" {

  type = string
}

variable "instance_count" {

  type = number
}

variable "enable_backup" {

  type = bool
}

variable "availability_zones" {

  type = list(string)
}
Enter fullscreen mode Exit fullscreen mode

This helps Terraform validate the values passed into your configuration.

Output values

We have learned how to pass values into Terraform using input variables.

But what if Terraform creates a resource and we want to display some information about it?

For example:

  • S3 bucket name.
  • EC2 instance ID.
  • Public IP address.
  • Resource ARN.

Terraform provides Output Values for this purpose.

Output values allow us to expose information from resources and modules.

Let's create a file called:

outputs.tf
Enter fullscreen mode Exit fullscreen mode

Add:

output "bucket_name" {

  description = "Name of the created S3 bucket"

  value = aws_s3_bucket.my_bucket.bucket
}

output "bucket_arn" {

  description = "ARN of the created S3 bucket"

  value = aws_s3_bucket.my_bucket.arn
}
Enter fullscreen mode Exit fullscreen mode

Let's understand this:

aws_s3_bucket.my_bucket.bucket
Enter fullscreen mode Exit fullscreen mode

This references the bucket attribute of the S3 resource.

Similarly:

aws_s3_bucket.my_bucket.arn
Enter fullscreen mode Exit fullscreen mode

References the ARN attribute.

ARN stands for Amazon Resource Name. It is a unique identifier used to identify AWS resources.

Now execute:

terraform apply
Enter fullscreen mode Exit fullscreen mode

After successful creation, Terraform displays the configured outputs.

Example:

Outputs:

bucket_name = "my-dev-terraform-bucket-12345"

bucket_arn = "arn:aws:s3:::my-dev-terraform-bucket-12345"
Enter fullscreen mode Exit fullscreen mode

You can also retrieve outputs later using:

terraform output
Enter fullscreen mode Exit fullscreen mode

Or retrieve a specific output:

terraform output bucket_name
Enter fullscreen mode Exit fullscreen mode

Behind the scenes

       AWS RESOURCE
             |
             v
       Resource Attributes
             |
             v
       outputs.tf
             |
             v
       Output Values
             |
             v
       terraform output
Enter fullscreen mode Exit fullscreen mode

One important point:

Output values are not automatically secret.

If an output contains sensitive information, use sensitive = true and follow proper secret-handling practices.

Terraform modules

Now let's discuss one of the most useful concepts in Terraform.

Imagine your company has ten applications.

Every application needs:

  • An S3 bucket.
  • A security group.
  • A virtual machine.
  • A network configuration.

You could write the same Terraform resource definitions separately for every application.

But that creates duplicated code.

What if you need to change the configuration?

You would have to update it in multiple places.

Terraform solves this problem using Modules.

A module is a collection of Terraform configuration files grouped together to manage related infrastructure.

In simple words, a module is a reusable collection of Terraform code.

Think of it like a reusable component in React or a reusable class in Java.

Instead of writing the same logic repeatedly, you create it once and use it wherever required.

Terraform modules help us:

  • Reuse infrastructure configurations.
  • Avoid code duplication.
  • Organize large Terraform projects.
  • Standardize infrastructure.
  • Separate infrastructure responsibilities.

Terraform has two important module concepts:

  1. Root Module.
  2. Child Module.

The root module is the main Terraform configuration directory where you execute Terraform commands.

A child module is another module called by the root module.

              ROOT MODULE
                   |
          +--------+--------+
          |        |        |
          v        v        v
       NETWORK   STORAGE  COMPUTE
       MODULE    MODULE   MODULE
          |        |        |
          v        v        v
       VPC       S3       EC2
Enter fullscreen mode Exit fullscreen mode

Let's create a reusable module.

Create a reusable module

Suppose we want to create a reusable S3 bucket module.

Our project structure will look like this:

terraform-project/
    |
    +-- main.tf
    |
    +-- variables.tf
    |
    +-- outputs.tf
    |
    +-- modules/
          |
          +-- s3-bucket/
                |
                +-- main.tf
                |
                +-- variables.tf
                |
                +-- outputs.tf
Enter fullscreen mode Exit fullscreen mode

Inside modules/s3-bucket/main.tf:

resource "aws_s3_bucket" "bucket" {

  bucket = var.bucket_name
}
Enter fullscreen mode Exit fullscreen mode

Inside modules/s3-bucket/variables.tf:

variable "bucket_name" {

  description = "Name of the S3 bucket"

  type = string
}
Enter fullscreen mode Exit fullscreen mode

Inside modules/s3-bucket/outputs.tf:

output "bucket_arn" {

  value = aws_s3_bucket.bucket.arn
}

output "bucket_name" {

  value = aws_s3_bucket.bucket.bucket
}
Enter fullscreen mode Exit fullscreen mode

We have now created a reusable module.

Notice that the module accepts a bucket name through an input variable and exposes the bucket information through output values.

This allows other Terraform configurations to reuse it.

Using a module

Now let's use our module from the root configuration.

Inside the root main.tf:

module "dev_bucket" {

  source = "./modules/s3-bucket"

  bucket_name = "my-dev-terraform-bucket-12345"
}

module "test_bucket" {

  source = "./modules/s3-bucket"

  bucket_name = "my-test-terraform-bucket-12345"
}
Enter fullscreen mode Exit fullscreen mode

Here:

  • module declares a module.
  • dev_bucket is the module name.
  • source specifies where the module is located.
  • bucket_name passes an input variable to the module.

We are using the same module twice with different input values.

Now expose the module outputs from the root module.

Inside the root outputs.tf:

output "dev_bucket_arn" {

  value = module.dev_bucket.bucket_arn
}

output "test_bucket_arn" {

  value = module.test_bucket.bucket_arn
}
Enter fullscreen mode Exit fullscreen mode

Notice the syntax:

module.dev_bucket.bucket_arn
Enter fullscreen mode Exit fullscreen mode

This accesses an output value from the child module.

Now execute:

terraform init

terraform fmt

terraform validate

terraform plan

terraform apply
Enter fullscreen mode Exit fullscreen mode

Terraform downloads or loads the module and provisions both S3 buckets.

Behind the scenes

               ROOT MODULE
                    |
             +------+------+
             |             |
             v             v
        dev_bucket     test_bucket
             |             |
             v             v
         S3 MODULE     S3 MODULE
             |             |
             v             v
         DEV BUCKET    TEST BUCKET
Enter fullscreen mode Exit fullscreen mode

The same infrastructure logic is reused with different input values.

Modules can also be downloaded from the Terraform Registry, Git repositories, and other supported sources.

One important point: after changing a module's source or registry version, run terraform init again to update the module installation.

Terraform taint and untaint

Now let's understand two commands that are useful when managing resource health and replacement.

  • terraform taint
  • terraform untaint

Imagine Terraform created an EC2 instance.

After some time, the instance becomes damaged or enters an unexpected state.

You want Terraform to recreate that instance.

Terraform has a concept called a tainted resource.

A tainted resource is a resource marked in Terraform state as needing replacement.

The modern replacement for taint

Historically, we could use:

terraform taint aws_instance.my_instance
Enter fullscreen mode Exit fullscreen mode

This marks the specified resource as tainted.

During the next plan or apply, Terraform proposes replacing that resource.

However, terraform taint is now deprecated.

HashiCorp recommends using the -replace option instead.

For example:

terraform plan -replace="aws_instance.my_instance"
Enter fullscreen mode Exit fullscreen mode

This previews the replacement operation.

If the plan looks correct, execute:

terraform apply -replace="aws_instance.my_instance"
Enter fullscreen mode Exit fullscreen mode

Terraform will replace the specified instance.

This is safer because the replacement appears in the execution plan before you approve it.

What about terraform untaint?

The terraform untaint command removes the tainted marker from a resource in Terraform state.

For example:

terraform untaint aws_instance.my_instance
Enter fullscreen mode Exit fullscreen mode

Why would we use it?

Imagine Terraform marked an instance as tainted, but after checking it, you discover that the instance is actually working correctly.

You can remove the tainted status using terraform untaint.

This does not repair or modify the actual cloud resource. It only changes the state information.

Remember:

  • terraform taint: Legacy command to mark a resource for replacement. Deprecated.
  • terraform untaint: Removes the tainted marker from a resource.
  • terraform apply -replace: Recommended modern way to request resource replacement.

Which one should I use?

Let's quickly compare the important Terraform concepts.

1. Configuration vs State

  • Configuration (.tf): Describes the desired infrastructure.
  • State (terraform.tfstate): Records Terraform's knowledge of managed infrastructure.

You need both to manage infrastructure reliably.

2. Input Variables vs Output Values

  • Input variables: Pass values into a configuration.
  • Output values: Expose values from resources or modules.

Use input variables to make configurations reusable and output values to expose useful resource information.

3. Root Module vs Child Module

  • Root module: Main Terraform working directory.
  • Child module: Reusable Terraform configuration called by another module.

Start with a root module for small projects. Introduce child modules when you have infrastructure that needs to be reused or logically separated.

4. Local State vs Remote State

  • Local state: Stored on your local machine.
  • Remote state: Stored in a shared backend.

For learning, local state is fine. For team and production environments, use a secure remote backend with suitable locking support.

5. terraform taint vs -replace

  • terraform taint: Deprecated.
  • terraform apply -replace: Recommended approach.

Prefer -replace because you can review the proposed replacement before applying it.

My recommended learning order:

1. Understand IaC
        |
        v
2. Learn HCL
        |
        v
3. Understand Providers and Resources
        |
        v
4. Learn Terraform Commands
        |
        v
5. Understand State Files
        |
        v
6. Learn Variables and Outputs
        |
        v
7. Learn Modules
        |
        v
8. Learn Remote State and Team Workflows
Enter fullscreen mode Exit fullscreen mode

Don't jump directly into complex modules or production infrastructure.

First understand how Terraform creates one resource, tracks it using state, and updates it when the configuration changes.

Common mistakes

Here are six mistakes beginners commonly make while learning Terraform.

  1. Thinking Terraform supports every cloud service automatically: Terraform uses providers, and each provider supports specific resource types and capabilities. Check the Terraform Registry before assuming a service is supported.

  2. Hardcoding AWS credentials in .tf files: Never store access keys or secret keys directly in configuration files. Use environment variables, AWS profiles, IAM roles, or other secure authentication methods.

  3. Thinking terraform plan creates infrastructure: Plan only previews the proposed changes. terraform apply performs the actual operations after confirmation.

  4. Deleting the state file manually: Terraform depends on state to identify the resources it manages. Deleting it without a recovery plan can cause Terraform to lose track of existing infrastructure. Back up state and use Terraform state commands for state management.

  5. Committing terraform.tfstate to GitHub: State files may contain sensitive information. Keep them out of public repositories and use a secured remote backend for shared infrastructure.

  6. Using terraform taint in new workflows: The command is deprecated. Use terraform plan -replace to preview a resource replacement and terraform apply -replace to execute it.

Quick recap

Let's quickly revise everything we learned.

Terraform

  • Open-source Infrastructure as Code tool.
  • Used to provision, update, and destroy infrastructure.
  • Supports cloud platforms through providers.
  • Uses HCL (HashiCorp Configuration Language).

Providers and resources

  • Providers are plugins that communicate with infrastructure platforms.
  • Resources represent infrastructure objects managed by Terraform.

Important commands

  • terraform init: Initialize the working directory.
  • terraform fmt: Format configuration files.
  • terraform validate: Validate configuration.
  • terraform plan: Preview infrastructure changes.
  • terraform apply: Apply infrastructure changes.
  • terraform destroy: Destroy managed infrastructure.

State

  • terraform.tfstate stores information about managed resources.
  • Local state is stored on your machine.
  • Remote state is stored in a shared backend.
  • State files can contain sensitive information.

Variables and outputs

  • Input variables accept values.
  • Output values expose information from resources and modules.

Modules

  • Modules are reusable Terraform configurations.
  • Root module is the main working directory.
  • Child modules are called by other modules.

Resource replacement

  • terraform taint is deprecated.
  • terraform untaint removes a tainted marker.
  • terraform apply -replace is the recommended replacement workflow.

Remember this complete Terraform workflow:

          WRITE TERRAFORM CODE
                  |
                  v
             terraform init
                  |
                  v
             terraform fmt
                  |
                  v
            terraform validate
                  |
                  v
             terraform plan
                  |
                  v
             terraform apply
                  |
                  v
          INFRASTRUCTURE CREATED
                  |
                  v
           terraform destroy
                  |
                  v
          INFRASTRUCTURE DELETED
Enter fullscreen mode Exit fullscreen mode

Terraform makes infrastructure management programmable, repeatable, and easier to maintain.

Try it yourself

Practice idea:

Create an AWS S3 bucket using Terraform.

Follow these steps:

  1. Install Terraform.
  2. Configure AWS authentication.
  3. Create a main.tf file.
  4. Declare the AWS provider.
  5. Create an S3 bucket resource.
  6. Run terraform init.
  7. Run terraform fmt and terraform validate.
  8. Run terraform plan.
  9. Run terraform apply.
  10. Verify that the bucket exists in your AWS console.
  11. Run terraform destroy when you no longer need the resource.

Bonus experiment:

Create a reusable S3 bucket module.

Pass the bucket name using an input variable and expose the bucket ARN using an output value.

Then call the same module twice to create two different buckets.

Try changing the bucket configuration and observe how terraform plan identifies the required infrastructure changes.

One final suggestion: experiment with Terraform using a dedicated AWS account or a restricted IAM identity. Always review your plan before applying changes, and clean up resources after testing to avoid unexpected cloud charges.

If this helped, or if you spotted something I should fix, tell me in the comments. I'm still learning too.

Top comments (0)