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.

By OmniAI Editorial · Nov 22, 2026 · 13 min read

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:

  1. Write: describe the resources you want in configuration files.
  2. 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.
  3. Apply: after review, the tool calls cloud APIs to make the changes.
  4. Record state: the tool stores a record of what it manages, so the next run knows what already exists.
  5. 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.

Three light boxes joined by ink arrows: ink code lines, a diff with one orange line, and a grey server, with a curved ink arrow running from the server back to the first box.
Write, plan, apply, then check for drift on the next run.

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 confirmation

Change 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

DeclarativeImperative
You describeThe end state: "two servers with these settings"The steps: "create server, then attach disk, then..."
Who works out the stepsThe toolYou
Running it twiceUsually changes nothing the second timeCan create duplicates unless scripts check first
ExamplesTerraform, OpenTofu, CloudFormation, Bicep, Kubernetes manifestsShell scripts, many SDK scripts; Ansible is procedural but most modules are idempotent
Best forProvisioning cloud resourcesOrdered 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

ToolStyleLanguageCloudsStateLicense and stewardBest for
TerraformDeclarative provisioningHCLAny, through thousands of providersState file, local or remoteBusiness Source License since August 2023; HashiCorp, part of IBM since February 2025Multi-cloud provisioning with the largest ecosystem
OpenTofuDeclarative provisioningHCL (Terraform-compatible)AnyState file, with built-in state encryptionOpen source (MPL 2.0); Linux FoundationTeams wanting an open-source Terraform alternative
PulumiDeclarative engine, general-purpose languagesTypeScript, Python, Go, C#, Java, YAMLAnyPulumi Cloud or self-managed backendOpen-source engine; commercial cloud serviceDevelopers who prefer real programming languages
AWS CloudFormationDeclarativeYAML or JSONAWSManaged by AWSAWS serviceAWS-only teams wanting native integration
AWS CDKCode that generates CloudFormationTypeScript, Python, Java, C#, GoAWSThrough CloudFormationOpen sourceAWS teams who want code over templates
Azure BicepDeclarativeBicep (compiles to ARM templates)AzureManaged by AzureOpen source, MicrosoftAzure-only teams
Google Infrastructure ManagerRuns Terraform on Google CloudHCLGoogle CloudManagedGoogle serviceGoogle Cloud teams; replaces Deployment Manager
CrossplaneKubernetes-based control planeKubernetes YAMLAnyKubernetes APICNCF graduated project (November 2025)Platform teams building self-service infrastructure on Kubernetes
AnsibleProcedural configuration and orchestrationYAML playbooksServers, network gear, cloudsNo state file; checks current state per runOpen source; Red HatConfiguring servers and network devices
Chef and PuppetConfiguration managementRuby DSL, Puppet DSLServersAgent-basedCommercial vendors with open-source coresLarge 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 jobProvisioning cloud infrastructureConfiguring servers and running tasks
ApproachDeclarative, with a plan stepProcedural playbooks of tasks, mostly idempotent
StateKeeps a state file of managed resourcesNo state file; inspects targets each run
AgentNone; calls cloud APIsNone; connects over SSH or WinRM
StrengthDependency graphs, previews, lifecycle of cloud resourcesInstalling software, editing configs, orchestrating steps across hosts
WeaknessNot designed for configuring inside serversWeaker 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

  1. Store everything in Git: modules, environments and CI configuration.
  2. Use remote state with locking, such as a cloud storage bucket plus a lock, so two people can't apply at once.
  3. Open a pull request for every change. CI runs formatting, validation and a security scan, then posts the plan for review.
  4. Review the plan, not just the code. A one-line change can destroy a database.
  5. Apply from CI after approval, not from laptops, so credentials and history stay controlled.
  6. Separate environments with different state files and accounts or projects.
  7. Run drift detection on a schedule and investigate any manual change.
A row of boxes joined by ink arrows: a light card with ink lines, a grey box with check marks, a light box with a large orange check mark, and a grey cloud at the end.
Every change goes through a pull request, a reviewed plan and an apply from CI.

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:

  1. Inventory what exists. List accounts, regions and resources, and tag anything you can't identify an owner for.
  2. Pick a small, low-risk slice first, such as DNS records, storage buckets or a staging network, rather than the production database.
  3. Write the configuration to match reality, then use your tool's import feature (Terraform and OpenTofu both support import blocks) so it adopts existing resources instead of creating duplicates.
  4. 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.
  5. Lock down manual changes for imported resources with permissions, so the code becomes the source of truth.
  6. 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

BenefitsChallenges
Consistent, repeatable environmentsLearning curve for the tool and the cloud provider's resource model
Faster provisioning and disaster recoveryState files are critical and must be secured and backed up
Peer review and audit history for every changeDrift from manual changes still happens without discipline
Fewer manual errors and configuration driftA bad change can be applied at scale just as quickly
Easier cost control through tagging and cleanupRefactoring large codebases without destroying resources takes care
Works naturally with CI/CDSecrets and sensitive values need careful handling

Which Infrastructure as Code Tool Should You Choose?

SituationGood choice
Multi-cloud or many SaaS providersTerraform or OpenTofu
Strong preference for open-source licensingOpenTofu
Developers want TypeScript or Python instead of a DSLPulumi, or AWS CDK on AWS only
AWS only, want native integrationCloudFormation or CDK
Azure onlyBicep
Google Cloud onlyTerraform with Infrastructure Manager
Platform team building self-service on KubernetesCrossplane
Configuring servers and network devicesAnsible

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.

All articles

Read next

Language

EnglishEnglish · en TürkçeTurkish · tr DeutschGerman · de العربيةArabic · ar

Account

Enter your email. We’ll send you a sign-in link and a 6-digit code. No password needed.

Sign in

Theme

Language

Show our email address

To keep spam out of our inbox, please confirm your own email first. We will send you a 6-digit code.

We send codes only to these providers: gmail.com, googlemail.com, outlook.com, hotmail.com, live.com, msn.com, proton.me, protonmail.com, pm.me, icloud.com, me.com, mac.com, yahoo.com, aol.com, gmx.de, gmx.net, web.de, t-online.de, yandex.com, omniai.blog