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?
    • The problem Terraform solves
    • What Infrastructure as Code means
  • How Terraform works
    • Providers and resources
    • Terraform and cloud platforms
    • Understanding HCL
  • Your first Terraform configuration
    • AWS authentication and access keys
  • The Terraform command workflow
    • terraform init
    • terraform fmt and validate
    • terraform plan
    • terraform apply
    • terraform destroy
  • Understanding Terraform state
    • Why Terraform needs a state file
    • Local state vs remote state
  • Input variables
  • Output values
  • Terraform modules
    • Create a reusable module
    • Using a module
  • Terraform taint and untaint
    • The modern replacement for taint
  • Which one should I use?
  • Common mistakes
  • Quick recap
  • Try it yourself

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" } 

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 

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 

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 

With IaC:

Developer | v Write Configuration Files | v Terraform | v Cloud Provider API | v Infrastructure Created 

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 

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 

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" } 

Let's understand the syntax.

resource "aws_s3_bucket" "my_bucket" { | | | | v v Resource Type Resource Name } 
  • 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 

Example output:

Terraform v1.17.2 on windows_amd64 

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

Now create a project directory:

mkdir terraform-demo cd terraform-demo 

Create a file named:

main.tf 

Terraform configuration files use the .tf extension.

Our project will initially look like this:

terraform-demo/ | +-- main.tf 

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" } 

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" } } } 

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" } 

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" } 

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 

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

aws configure 

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 

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" 

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" 

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 

Let's understand each command.

terraform init

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

terraform init 

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 

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! 

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 

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 

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 

2. terraform validate

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

Run:

terraform validate 

Example output:

Success! The configuration is valid. 

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 

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" } 

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. 

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 

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 

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 

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. 

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 

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: 

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. 

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 

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 

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" } 

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 

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

Now suppose we execute:

terraform plan 

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. 

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 

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 

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 

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" } 

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

For example:

Development -> dev-bucket Testing -> test-bucket Production -> prod-bucket 

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 

Add:

variable "bucket_name" { description = "Name of the S3 bucket" type = string default = "my-unique-terraform-demo-bucket-12345" } 

Now update main.tf:

resource "aws_s3_bucket" "my_bucket" { bucket = var.bucket_name } 

Notice:

var.bucket_name 

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" 

Or create a file named:

terraform.tfvars 

Add:

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

Terraform automatically loads the default terraform.tfvars file.

Now execute:

terraform plan 

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 

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) } 

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 

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 } 

Let's understand this:

aws_s3_bucket.my_bucket.bucket 

This references the bucket attribute of the S3 resource.

Similarly:

aws_s3_bucket.my_bucket.arn 

References the ARN attribute.

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

Now execute:

terraform apply 

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" 

You can also retrieve outputs later using:

terraform output 

Or retrieve a specific output:

terraform output bucket_name 

Behind the scenes

 AWS RESOURCE | v Resource Attributes | v outputs.tf | v Output Values | v terraform output 

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 

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 

Inside modules/s3-bucket/main.tf:

resource "aws_s3_bucket" "bucket" { bucket = var.bucket_name } 

Inside modules/s3-bucket/variables.tf:

variable "bucket_name" { description = "Name of the S3 bucket" type = string } 

Inside modules/s3-bucket/outputs.tf:

output "bucket_arn" { value = aws_s3_bucket.bucket.arn } output "bucket_name" { value = aws_s3_bucket.bucket.bucket } 

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" } 

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 = moduleSource:https://dev.to/mayur_bodhare/terraform-explained-infrastructure-as-code-for-beginners-9b6

Related posts