← All posts

Infrastructure as Code: Terraform

terraformopentofuiacdevopsawscloudflareinfrastructure

What do you do when you need to set up a server, a database or a storage bucket? Most of the time the answer is clicking your way through a web console. That works the first time. But when you need to build the same infrastructure a second time, or you're trying to figure out "why is production different from staging?", things get messy. This is where Infrastructure as Code (IaC) comes in. In this post we'll cover what IaC is, the most widely used IaC tool Terraform (and its open source alternative OpenTofu), the core concepts, and your first configuration with practical examples.

What Is Infrastructure as Code (IaC)?

IaC is the approach of defining your infrastructure (servers, networks, DNS records, storage, databases) with code files that can live in version control, instead of manual steps. Your infrastructure is no longer described by clicks in a console but by readable text files. The idea isn't tied to any tool. You can apply it with AWS CloudFormation, Pulumi or Ansible as well.

Advantages:

  • Repeatability: You can build the exact same environment from the same configuration as many times as you want.
  • Versioning: Infrastructure changes are tracked in Git just like your code, they get reviewed and can be rolled back.
  • Documentation: The code itself is living documentation of the current state of your infrastructure.
  • Automation: It plugs easily into CI/CD pipelines.

What Is Terraform?

Terraform is a cloud-agnostic IaC tool built by HashiCorp. It lets you manage platforms like AWS, Google Cloud, Azure and Cloudflare with a single language and a single workflow.

Core Features:

  1. Declarative: Instead of saying "do this, then that", you define the end state you want. Terraform works out the difference between the current state and the desired state on its own and applies the necessary steps.
  2. HCL (HashiCorp Configuration Language): It uses a configuration language that is easy to read, similar to JSON but human friendly.
  3. Provider Architecture: It works with hundreds of platforms through the same tool, and each platform comes with a "provider" plugin. AWS, GCP, Azure, Cloudflare, Kubernetes, GitHub, Datadog... the list is almost endless. So Terraform isn't just for one cloud. It's used to manage almost anything that has an API, from cloud infrastructure to DNS records, from GitHub repo/organization settings to SaaS configuration.
  4. State Management: It keeps the current state of the resources it manages in a state file, which keeps the real world and your code in sync.

Note (OpenTofu): In August 2023, HashiCorp moved Terraform's license from the open source MPL 2.0 to a more restrictive license (BUSL). In response, the community forked Terraform and OpenTofu was born. It lives under the Linux Foundation, is MPL 2.0 licensed, and is a drop-in replacement fully compatible with Terraform. The commands are the same, you just type tofu instead of terraform. Everything in this post applies to both.


Installation

Terraform is a single binary. You can install it quickly with your package manager:

bash
# macOS (Homebrew)
brew tap hashicorp/tap
brew install hashicorp/tap/terraform

# Windows (winget)
winget install HashiCorp.Terraform

# Verify the installation
terraform version

Core Concepts

Before writing any configuration, it's worth getting four core concepts down.

  • Provider: The plugin that lets Terraform talk to a specific platform (AWS, Cloudflare, etc.).
  • Resource: A concrete piece of infrastructure you want to manage, like a virtual machine, a DNS record, a storage bucket... It's the basic building block of Terraform.
  • State: The file where the current state of created resources is stored (terraform.tfstate). It's the bridge between your code and the real infrastructure.
  • Plan / Apply cycle: First you see what will be done (plan), you approve it, then you apply it (apply).

First Configuration: An S3 Bucket on AWS

Let's start with a classic example and create an S3 bucket on AWS. First you need to set up your AWS credentials. The easiest way is with the AWS CLI:

bash
aws configure   # Enter your Access Key, Secret Key and region

Then create a main.tf file in an empty folder:

main.tfhcl
terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}

provider "aws" {
  region = "eu-central-1"
}

resource "aws_s3_bucket" "example" {
  bucket = "acme-app-assets"

  tags = {
    Project     = "acme-web"
    Environment = "dev"
  }
}

Code Explanation:

  • terraform { required_providers { ... } }: Specifies which provider (hashicorp/aws) and version we'll use. terraform init downloads the provider based on this.
  • provider "aws" { region = ... }: Configures the AWS provider and tells it which region to create resources in.
  • resource "aws_s3_bucket" "example" { ... }: Defines the resource to create. "aws_s3_bucket" is the resource type, and "example" is its local name inside Terraform (referenced in code as aws_s3_bucket.example).
  • bucket: The globally unique name of the bucket (S3 bucket names must be unique across the whole world, so change the name in the example).
  • tags: Labels attached to the resource, used for organization and cost tracking.

Three basic commands are enough to bring the configuration to life:

bash
terraform init      # Downloads providers, prepares the directory
terraform plan      # Shows what will be done (changes nothing)
terraform apply     # Applies the changes after confirmation

In the plan output, a + sign means a resource will be created:

bash
Terraform will perform the following actions:

  # aws_s3_bucket.example will be created
  + resource "aws_s3_bucket" "example" {
      + bucket = "acme-app-assets"
      + arn    = (known after apply)
      + id     = (known after apply)
    }

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

When apply finishes, the bucket exists in your AWS account and a terraform.tfstate file shows up in your folder. To clean up everything you created, use terraform destroy. This is especially useful so you don't leave test resources running and end up paying for them.


Variables and Outputs

Pulling values out into variables instead of hardcoding them makes the configuration reusable. Outputs, on the other hand, expose information about the created resources:

variables.tfhcl
variable "bucket_name" {
  type        = string
  description = "Globally unique name of the S3 bucket to create"
}

variable "region" {
  type    = string
  default = "eu-central-1"
}

provider "aws" {
  region = var.region
}

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

output "bucket_arn" {
  value = aws_s3_bucket.example.arn
}

Code Explanation:

  • variable "bucket_name" { ... }: Defines an input that can take a value from outside. Inside the configuration it's used as var.bucket_name.
  • default: The default used when no value is given (in the example it's set for region, and bucket_name is left required).
  • output "bucket_arn" { ... }: Exposes a value after apply (here, the bucket's ARN). It shows up in the CLI output and can be passed to other modules.

Now you can run the same code with different values using terraform apply -var="bucket_name=acme-staging-assets".


Same Tool, Different Cloud: Cloudflare R2

Terraform's real strength is managing multiple platforms with a single language. We just created an AWS S3 bucket. Now, with the exact same init → plan → apply cycle, let's create an R2 bucket on Cloudflare. The only things that change are the provider and the resource definition:

main.tfhcl
terraform {
  required_providers {
    cloudflare = {
      source  = "cloudflare/cloudflare"
      version = "~> 4"
    }
  }
}

variable "cloudflare_api_token" {
  type      = string
  sensitive = true
}

variable "cloudflare_account_id" {
  type = string
}

provider "cloudflare" {
  api_token = var.cloudflare_api_token
}

resource "cloudflare_r2_bucket" "assets" {
  account_id = var.cloudflare_account_id
  name       = "website-assets"
  location   = "WEUR"
}

The concepts are exactly the same: provider, resource, variables, plan/apply. Once you know AWS, learning Cloudflare (or GCP, Azure, DigitalOcean...) comes down to learning the new provider's resources. Also note that sensitive = true keeps sensitive values like API tokens from being shown in plain text in Terraform's output.


Terraform Workflow (Mermaid Diagram)

The diagram below shows Terraform's basic work cycle and the role state plays in it:

graph TD
    A[main.tf - Configuration] --> B[terraform init]
    B --> C[terraform plan]
    C --> D{Approve changes?}
    D -->|yes| E[terraform apply]
    E --> F[Real Infrastructure: AWS / Cloudflare]
    E --> G[terraform.tfstate]
    F --> G
    G --> C

State is read at every plan step to compare "the state the code wants" with "the state that actually exists", and it's updated after every apply. This file sits at the heart of the cycle.


State Management: Things to Watch Out For

The terraform.tfstate file is critical and needs care.

  • Never commit it to Git. The state file can contain sensitive information about your resources (sometimes even secrets). Add it to your .gitignore:
.gitignorebash
# .gitignore
.terraform/
*.tfstate
*.tfstate.*
  • Use a remote backend when working in a team. If more than one person manages the same infrastructure, keep the state in a shared backend like AWS S3, Cloudflare R2 or Terraform/OpenTofu Cloud, not on a local disk.

Note: A remote backend doesn't just centralize state. Thanks to state locking, it also stops two people from running apply at the same time and breaking the infrastructure.

I covered why the backend matters so much and how to configure it in depth in a separate post: Terraform Backend: Why Remote State Is a Must


Conclusion

Infrastructure as Code removes the uncertainty that comes with managing infrastructure through clicks and turns it into a readable, versionable and repeatable codebase. In this post we looked at the idea behind IaC, the core concepts of Terraform/OpenTofu and the init → plan → apply cycle, and with the same workflow we created real resources on both AWS and Cloudflare.

For next steps, I'd suggest looking into modules (reusable infrastructure blocks), remote backend configuration and workspaces (multiple environments from the same code). But remember: everything is built on top of the simple plan and apply cycle you saw in this post.

Resources: