Dev tools
Infrastructure as Code: What It Is and Which Tool to Use
Infrastructure as code explained: how IaC works, declarative vs imperative, Terraform, OpenTofu, Pulumi and other tools, an example and best practices.
Infrastructure as code (IaC) means defining servers, networks, databases and other cloud resources in text files that a tool reads to create and update them automatically, instead of clicking through a console or running commands by hand. The files live in version control like application code, so every change is reviewed, repeatable and reversible. Terraform and its open-source fork OpenTofu are the most widely used provisioning tools; Pulumi, AWS CloudFormation and CDK, Azure Bicep, Crossplane and Ansible cover other styles and platforms.
This guide answers what is infrastructure as code in practical terms, shows an infrastructure as code example, explains declarative vs imperative and provisioning vs configuration management, compares the main infrastructure as code tools (including Terraform vs Ansible), walks through a team workflow and best practices, and helps you choose.
What Is Infrastructure as Code?
Infrastructure as code is the practice of managing infrastructure with machine-readable definition files. A file might say: one virtual network, two subnets, a database with these settings, a storage bucket with encryption on. An IaC tool compares that description with what actually exists in your cloud account and makes the changes needed to match.
IBM describes IaC as treating infrastructure like software, so teams can version, test and deploy it with the same practices they use for application code. That shift brings three big improvements:
- Repeatability: the same files create identical environments for development, staging and production, in any region.
- Visibility: every change goes through a pull request, so you know who changed what, when and why.
- Speed and recovery: rebuilding an environment after a mistake or disaster is a command, not a weekend of clicking.
How Infrastructure as Code Works
Most provisioning tools follow the same loop:
- Write: describe the resources you want in configuration files.
- Plan: the tool reads the files, checks the current state of your infrastructure, and shows a preview of what it will create, change or delete.
- Apply: after review, the tool calls cloud APIs to make the changes.
- Record state: the tool stores a record of what it manages, so the next run knows what already exists.
- Detect drift: if someone changes a resource by hand, the next plan shows the difference.
GitHub's guide to IaC makes an important point here: IaC tools can detect drift between the code and live infrastructure, but they can't stop someone from making manual changes. Teams prevent drift with permissions and habits, not just tools.
Infrastructure as Code Example
Here's a small infrastructure as code example in Terraform's HCL language, creating a storage bucket on AWS:
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
}
}
}
provider "aws" {
region = "us-east-1"
}
resource "aws_s3_bucket" "logs" {
bucket = "example-app-logs-2f9c"
tags = {
environment = "staging"
owner = "platform-team"
}
}And the workflow:
terraform init # download the AWS provider
terraform plan # preview: 1 to add, 0 to change, 0 to destroy
terraform apply # create the bucket after confirmationChange the tag in the file, run plan again, and the tool shows exactly one change. Delete the resource block and plan shows the bucket will be destroyed, which is why plans are reviewed before applying. With OpenTofu, the same files work with the tofu command instead of terraform.
Declarative vs Imperative
| Declarative | Imperative | |
|---|---|---|
| You describe | The end state: "two servers with these settings" | The steps: "create server, then attach disk, then..." |
| Who works out the steps | The tool | You |
| Running it twice | Usually changes nothing the second time | Can create duplicates unless scripts check first |
| Examples | Terraform, OpenTofu, CloudFormation, Bicep, Kubernetes manifests | Shell scripts, many SDK scripts; Ansible is procedural but most modules are idempotent |
| Best for | Provisioning cloud resources | Ordered tasks, one-off operations, configuration steps |
Pulumi and AWS CDK blur the line: you write general-purpose code (TypeScript, Python, Go and others) that builds a declarative model, which the engine then applies.
Provisioning vs Configuration Management
Two jobs often get lumped together under IaC:
- Provisioning creates the infrastructure itself: networks, virtual machines, managed databases, load balancers, DNS, permissions. Terraform, OpenTofu, CloudFormation, Bicep, Pulumi and Crossplane focus here.
- Configuration management sets up what runs inside servers: installing packages, editing config files, managing users and services. Ansible, Chef and Puppet focus here.
With containers and managed services, configuration management matters less than it used to: instead of patching long-lived servers, teams build images and replace servers entirely, an approach called immutable infrastructure.
Infrastructure as Code Tools Compared
| Tool | Style | Language | Clouds | State | License and steward | Best for |
|---|---|---|---|---|---|---|
| Terraform | Declarative provisioning | HCL | Any, through thousands of providers | State file, local or remote | Business Source License since August 2023; HashiCorp, part of IBM since February 2025 | Multi-cloud provisioning with the largest ecosystem |
| OpenTofu | Declarative provisioning | HCL (Terraform-compatible) | Any | State file, with built-in state encryption | Open source (MPL 2.0); Linux Foundation | Teams wanting an open-source Terraform alternative |
| Pulumi | Declarative engine, general-purpose languages | TypeScript, Python, Go, C#, Java, YAML | Any | Pulumi Cloud or self-managed backend | Open-source engine; commercial cloud service | Developers who prefer real programming languages |
| AWS CloudFormation | Declarative | YAML or JSON | AWS | Managed by AWS | AWS service | AWS-only teams wanting native integration |
| AWS CDK | Code that generates CloudFormation | TypeScript, Python, Java, C#, Go | AWS | Through CloudFormation | Open source | AWS teams who want code over templates |
| Azure Bicep | Declarative | Bicep (compiles to ARM templates) | Azure | Managed by Azure | Open source, Microsoft | Azure-only teams |
| Google Infrastructure Manager | Runs Terraform on Google Cloud | HCL | Google Cloud | Managed | Google service | Google Cloud teams; replaces Deployment Manager |
| Crossplane | Kubernetes-based control plane | Kubernetes YAML | Any | Kubernetes API | CNCF graduated project (November 2025) | Platform teams building self-service infrastructure on Kubernetes |
| Ansible | Procedural configuration and orchestration | YAML playbooks | Servers, network gear, clouds | No state file; checks current state per run | Open source; Red Hat | Configuring servers and network devices |
| Chef and Puppet | Configuration management | Ruby DSL, Puppet DSL | Servers | Agent-based | Commercial vendors with open-source cores | Large fleets of long-lived servers |
Sources: HashiCorp and IBM announcements, OpenTofu and Linux Foundation pages, CNCF announcement of Crossplane's graduation, Google Cloud Deployment Manager deprecation notice, vendor documentation.
Google ended support for its older Deployment Manager in 2026 and recommends Infrastructure Manager, which uses Terraform, a sign of how far Terraform-style HCL has become a common language.
Terraform vs Ansible
Terraform vs Ansible is one of the most common questions, and the honest answer is that they mostly do different jobs.
| Terraform (or OpenTofu) | Ansible | |
|---|---|---|
| Main job | Provisioning cloud infrastructure | Configuring servers and running tasks |
| Approach | Declarative, with a plan step | Procedural playbooks of tasks, mostly idempotent |
| State | Keeps a state file of managed resources | No state file; inspects targets each run |
| Agent | None; calls cloud APIs | None; connects over SSH or WinRM |
| Strength | Dependency graphs, previews, lifecycle of cloud resources | Installing software, editing configs, orchestrating steps across hosts |
| Weakness | Not designed for configuring inside servers | Weaker for full lifecycle and deletion of cloud resources |
Many teams use both: Terraform creates the network and servers, then Ansible configures what runs on them. In container-based setups, Terraform plus container images and Kubernetes often replaces the Ansible step. Our guide to Docker vs Kubernetes explains that layer.
Terraform vs OpenTofu
In August 2023, HashiCorp moved Terraform from the open-source Mozilla Public License to the Business Source License, which restricts some commercial uses such as offering competing hosted services. The community forked the last open-source version as OpenTofu, now under the Linux Foundation. The two remain largely compatible for most configurations, though features have started to diverge, such as OpenTofu's built-in state encryption. For most companies using Terraform internally, the license change has little practical effect; teams that care about open-source licensing, or vendors building products on top, often choose OpenTofu.
A Team Workflow for Infrastructure as Code
- Store everything in Git: modules, environments and CI configuration.
- Use remote state with locking, such as a cloud storage bucket plus a lock, so two people can't apply at once.
- Open a pull request for every change. CI runs formatting, validation and a security scan, then posts the plan for review.
- Review the plan, not just the code. A one-line change can destroy a database.
- Apply from CI after approval, not from laptops, so credentials and history stay controlled.
- Separate environments with different state files and accounts or projects.
- Run drift detection on a schedule and investigate any manual change.
This is the same discipline site reliability teams apply to production; our guide to site reliability engineering covers the operational side.
Best Practices
- Keep modules small and reusable, with clear inputs and outputs; don't build one giant file.
- Pin provider and module versions so upgrades are deliberate.
- Never commit secrets. Pull them from a secrets manager at runtime and mark sensitive outputs.
- Use policy as code with tools such as Open Policy Agent, HashiCorp Sentinel or Checkov to block risky changes, like public storage buckets or unencrypted databases.
- Tag every resource with owner and environment to control costs.
- Protect critical resources with lifecycle rules that prevent accidental deletion.
- Import existing resources instead of recreating them when adopting IaC on an existing account.
- Test changes in a staging environment built from the same code.
How to Adopt Infrastructure as Code in an Existing Account
Most teams don't start from an empty cloud account. A practical path for bringing existing infrastructure under code:
- Inventory what exists. List accounts, regions and resources, and tag anything you can't identify an owner for.
- Pick a small, low-risk slice first, such as DNS records, storage buckets or a staging network, rather than the production database.
- Write the configuration to match reality, then use your tool's import feature (Terraform and OpenTofu both support
importblocks) so it adopts existing resources instead of creating duplicates. - Run a plan and aim for "no changes." Any differences show where your code doesn't match reality yet; fix the code, not the resource.
- Lock down manual changes for imported resources with permissions, so the code becomes the source of truth.
- Expand slice by slice, saving production data stores for when the team is confident in the workflow.
Several tools can generate starter configuration from existing resources, which saves typing, though the output usually needs cleanup into readable modules.
Infrastructure as Code for AI and GPU Workloads
AI infrastructure benefits from IaC even more than ordinary web apps, because GPU capacity is expensive and environments are easy to get wrong by hand:
- Reproducible GPU environments: define instance types, drivers, container images and storage once, so training runs and inference servers are identical every time.
- Cost control: create GPU clusters for a job and destroy them afterwards with the same code, instead of leaving idle machines running.
- Quota and region planning: GPU availability differs by region; parameterized modules let you switch regions or providers without rewriting everything.
- Managed AI services: model endpoints, vector databases, API keys stored in secrets managers and network rules for private access can all be declared alongside the rest of the stack.
- Auditability: for regulated AI systems, version-controlled infrastructure shows exactly which configuration served which model and when.
Benefits and Challenges
| Benefits | Challenges |
|---|---|
| Consistent, repeatable environments | Learning curve for the tool and the cloud provider's resource model |
| Faster provisioning and disaster recovery | State files are critical and must be secured and backed up |
| Peer review and audit history for every change | Drift from manual changes still happens without discipline |
| Fewer manual errors and configuration drift | A bad change can be applied at scale just as quickly |
| Easier cost control through tagging and cleanup | Refactoring large codebases without destroying resources takes care |
| Works naturally with CI/CD | Secrets and sensitive values need careful handling |
Which Infrastructure as Code Tool Should You Choose?
| Situation | Good choice |
|---|---|
| Multi-cloud or many SaaS providers | Terraform or OpenTofu |
| Strong preference for open-source licensing | OpenTofu |
| Developers want TypeScript or Python instead of a DSL | Pulumi, or AWS CDK on AWS only |
| AWS only, want native integration | CloudFormation or CDK |
| Azure only | Bicep |
| Google Cloud only | Terraform with Infrastructure Manager |
| Platform team building self-service on Kubernetes | Crossplane |
| Configuring servers and network devices | Ansible |
For a small team starting out, Terraform or OpenTofu with a remote state backend and a CI pipeline is a reliable default. Even a single cheap server benefits: our guide to choosing a cheap VPS is easier to act on when the server can be rebuilt from code.
Common Mistakes
- Mixing manual changes with IaC. Every console edit becomes drift that the next apply may undo.
- Local state files. Lost laptops mean lost state; use a remote backend with locking.
- Applying without reading the plan. Renames and replacements can destroy data.
- Huge, monolithic configurations. Slow plans and risky changes; split by component and environment.
- Hard-coded secrets and credentials. They end up in Git history forever.
- Copy-pasting between environments instead of using modules and variables.
FAQ
What is infrastructure as code in simple terms?
It's writing down your servers, networks and other cloud resources in files, then letting a tool build and update them automatically, so your infrastructure is managed like software with version control and reviews.
Is Terraform the same as infrastructure as code?
No. Infrastructure as code is the practice; Terraform is one of the most popular tools for it. Others include OpenTofu, Pulumi, CloudFormation, Bicep, Crossplane and Ansible.
What is the difference between Terraform and Ansible?
Terraform mainly provisions cloud infrastructure declaratively and tracks it in a state file. Ansible mainly configures servers and runs ordered tasks over SSH without a state file. Many teams use both.
Is infrastructure as code only for the cloud?
No. It's most common in the cloud, but tools can manage on-premise virtualization, network devices, DNS, SaaS settings, Kubernetes clusters and even monitoring dashboards.
Is IaC part of DevOps?
Yes. It's a core DevOps practice because it lets infrastructure changes go through the same version control, review and automated delivery as application code.