Terraform in the DevOps Workflow: Plan to Apply

How Terraform fits the DevOps loop: fmt, validate, plan on pull requests, apply on merge, remote state with locking, drift checks and a pipeline checklist.

Jul 17, 2025 - 17:30
Nov 5, 2026 - 08:14
 0  56
Terraform in the DevOps Workflow: Plan to Apply

Terraform fits into the DevOps workflow as the infrastructure as code step between a merged change and a running environment. Engineers describe servers, networks and services in configuration files, review a plan in a pull request, and let a pipeline apply it. The same code then gives you history, repeatability and an audit trail for every infrastructure change.

This guide follows one change through the DevOps loop (plan, code, build, test, release, deploy, operate) and shows where Terraform commands, state and policy checks belong at each step. It is about workflow placement. For tool comparisons see our ranking of 12 infrastructure as code tools, and for production hardening see 12 Terraform best practices for production.

Key takeaways

  • Terraform's core loop is write, plan, apply. A DevOps pipeline turns that loop into a pull request (plan) and a merge (apply).
  • State is the record of what Terraform manages. Keep it in a remote backend with locking, never in Git.
  • Run terraform fmt -check, terraform validate and terraform plan on every pull request, and apply only from the main branch.
  • Terraform does not replace configuration management or deployment tools. It creates the infrastructure; Ansible, Kubernetes or your release tool puts software on it.
  • Drift, shared state, secrets and long-lived credentials are the usual sources of trouble, so plan for them before the first apply.
  • As of 12 November 2026 the latest stable Terraform release on GitHub is v1.17.2, published on 11 November 2026.

What Terraform does in a DevOps team

Terraform is an infrastructure as code tool from HashiCorp. You describe the resources you want in configuration files, and Terraform works out the order of operations and makes the API calls. HashiCorp's introduction describes the loop as three steps: write the configuration, plan to preview the changes, and apply to carry them out in dependency order.

Three ideas explain most of how it behaves in a team:

  • Declarative configuration. You state the end result (three subnets, one load balancer) and Terraform computes the difference from what exists.
  • Providers. A provider is a plugin that talks to one platform API. AWS, Azure, Google Cloud, Kubernetes, Helm and GitHub are among the providers published on the Terraform Registry.
  • State. Terraform records the real objects it manages in a state file and compares it with your configuration to decide what must change.

Because the files are text, they go through the same pull request, review and history as application code. That is the connection to DevOps: infrastructure changes become small, reviewable and repeatable instead of console clicks that nobody can replay.

Where Terraform sits in the DevOps loop

DevOps stageWhat happens with TerraformTypical command or artifact
PlanDecide the target architecture and split it into modules and environmentsRepository layout, module design
CodeWrite or change .tf files on a branchGit branch, terraform fmt
BuildInitialize providers and modules, check syntaxterraform init, terraform validate
TestPreview the change and run tests or policy checksterraform plan, terraform test
ReleaseReview the plan in the pull request, approve and mergePlan output as a PR comment
DeployApply the approved change to the target environmentterraform apply
OperateDetect drift, manage state, plan upgrades and destroy short-lived environmentsterraform plan -refresh-only, terraform destroy

Step 1: Code. Write configuration on a branch

Every change starts as a branch. A small configuration looks like this:

terraform {
  required_version = ">= 1.9"
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}

provider "aws" {
  region = var.region
}

resource "aws_s3_bucket" "artifacts" {
  bucket = "${var.project}-artifacts-${var.environment}"
}

Two habits pay off early. First, pin the Terraform and provider versions so a pipeline run next month behaves like a run today. Second, commit the dependency lock file (.terraform.lock.hcl) so every machine installs the same provider builds.

Keep code readable with terraform fmt. The -check option exits with status 0 only if the files are already formatted, which makes it usable as a pipeline gate, and -recursive extends it to subdirectories.

Step 2: Build. Initialize and validate

The pipeline's first job installs providers and modules and checks the configuration:

terraform fmt -check -recursive
terraform init -backend=false
terraform validate

According to the Terraform CLI documentation, validate checks that the configuration is syntactically valid and internally consistent, regardless of variables or state. It does not contact remote services such as remote state or provider APIs, so a passing validate does not mean the plan will succeed. The -backend=false option on init lets this job run without credentials for the state backend, which keeps the cheap checks fast and low privilege.

Step 3: Test. Plan on every pull request

The plan is the center of the workflow. It shows what Terraform will create, update or destroy before anything changes. In a pipeline you run it non-interactively:

terraform init -input=false
terraform plan -input=false -lock-timeout=60s -out=tfplan

These options come from the plan command documentation:

  • -input=false stops Terraform from prompting for missing variable values, so a job fails instead of hanging.
  • -lock-timeout makes Terraform retry for a period when another run holds the state lock, instead of failing at once.
  • -out writes the plan to a file that terraform apply can execute later. Treat that file as sensitive, because it can contain values from your configuration.
  • -detailed-exitcode returns 0 for no changes, 1 for an error and 2 when changes are present. Scheduled drift checks use it.

Terraform also has a native test framework. Files ending in .tftest.hcl contain run blocks with assert blocks, and terraform test executes them. The documentation warns that tests can create real infrastructure that costs money, so use a sandbox account and watch cleanup.

run "bucket_name_has_environment" {
  command = plan

  assert {
    condition     = can(regex("-prod$", aws_s3_bucket.artifacts.bucket))
    error_message = "Bucket name must end with the environment name"
  }
}

Add policy checks at this stage as well. HCP Terraform evaluates policy sets against the plan during each run and supports Sentinel and Open Policy Agent (OPA). It also lists a native Terraform policy framework that requires Terraform v1.17 or later. Self-managed pipelines often run an external scanner against the plan output for the same purpose.

Step 4: Release. Review the plan like code

A plan only works as a safety net if a human reads it. Post the summary on the pull request so reviewers see which resources change before they approve. Look for three things:

  1. Replacements. A resource marked for destroy and re-create can mean downtime or data loss for databases and volumes.
  2. Unexpected resources. A plan that touches resources you did not edit often points to drift or a provider upgrade.
  3. Security-sensitive changes. Security groups, IAM policies and public access settings deserve a second reviewer.

HashiCorp's GitHub Actions tutorial for HCP Terraform shows one pattern: a speculative plan on every pull request, a comment with the plan result, and an apply run when the change merges to the main branch. The same pattern works in GitLab CI, Jenkins or Azure DevOps with plain CLI commands.

Step 5: Deploy. Apply from the main branch only

Apply runs after merge, in a pipeline job with the credentials needed to change the environment. Developers should not run apply from laptops against shared environments.

terraform init -input=false
terraform apply -input=false tfplan

Applying the saved plan file means Terraform executes exactly what the reviewers approved. If you plan again at apply time, a change made in between could slip in. When the saved plan no longer matches the state, Terraform refuses to apply it, and you re-run the plan.

Use separate state and credentials per environment. A common layout is one directory or workspace per environment (dev, staging, production), each with its own backend key, with production apply gated by a manual approval step in the pipeline.

State: the part that needs the most care

State maps your configuration to real objects. Lose it and Terraform no longer knows what it manages; corrupt it and plans become wrong. Rules that hold across teams:

  • Store state in a remote backend so the pipeline and engineers share one source of truth.
  • Enable locking so two runs cannot write at the same time.
  • Turn on versioning for the storage so you can recover from mistakes.
  • Keep state out of Git, because it can contain secrets in plain text.

For the S3 backend, the documentation says locking is opt-in through use_lockfile = true, and that DynamoDB-based locking via dynamodb_table is deprecated and will be removed in a future minor version. It also recommends enabling bucket versioning.

terraform {
  backend "s3" {
    bucket       = "example-terraform-state"
    key          = "network/prod/terraform.tfstate"
    region       = "ap-south-1"
    use_lockfile = true
  }
}

Our guide to Terraform remote state, backends and locking covers migration and recovery in detail.

Operate: drift, upgrades and cleanup

Infrastructure changes outside Terraform: someone edits a security group in the console, or an autoscaler adds a node. That gap is drift. Two commands help:

  • terraform plan -refresh-only builds a plan whose only goal is to update state and outputs to match remote objects. Review it before accepting.
  • A scheduled pipeline running terraform plan -detailed-exitcode alerts the team when it returns 2, meaning the real world no longer matches the code.

Treat provider and Terraform upgrades as ordinary changes: bump the version on a branch, run the plan, read the diff. Use terraform destroy (or plan -destroy first) to remove short-lived environments such as per-pull-request test stacks, so they do not keep billing. For more on this problem, read configuration drift detection and infrastructure stability.

How Terraform works with other DevOps tools

ToolHandlesHow it connects to Terraform
Git and pull requestsChange history and reviewHolds the configuration; the PR triggers the plan
CI/CD (GitHub Actions, GitLab CI, Jenkins)Running checks and appliesExecutes fmt, validate, plan and apply in jobs
AnsibleConfiguring software on serversTerraform creates the hosts; Ansible configures them
Kubernetes and HelmRunning application workloadsTerraform can create the cluster, and providers exist for Kubernetes and Helm
Secrets managerStoring credentialsThe pipeline reads secrets at run time instead of storing them in code

The boundary between Terraform and Ansible causes the most confusion. Terraform is strongest at creating and changing cloud resources through APIs; Ansible is strongest at configuring what runs inside a machine. Many teams use both, as covered in declarative vs imperative configuration in IaC.

Benefits and limits

Benefits teams report from this workflow:

  • Repeatable environments from the same code, which makes creating a test copy of production an ordinary task.
  • Review before change, because the plan is a diff of infrastructure.
  • A history of who changed what, and when, through Git.
  • Multi-provider scope. One workflow can manage cloud resources, DNS and SaaS settings.

Limits to plan for:

  • State handling is a skill of its own, and mistakes in shared state affect everyone.
  • Plans can be large. Splitting configuration into small root modules with separate state keeps plans readable and limits the impact of a bad apply.
  • Terraform does not roll back. To undo a change you revert the code and apply again, and data-bearing resources may not come back.
  • Secrets can end up in state and plan files, so protect both.

A starter pipeline checklist

  1. Pin Terraform and provider versions and commit .terraform.lock.hcl.
  2. Run fmt -check, init -backend=false and validate on every push.
  3. Run plan with -input=false and post the result to the pull request.
  4. Require review and, for production, a manual approval before apply.
  5. Apply the saved plan from the main branch only.
  6. Use a remote backend with locking and versioning, one state key per environment.
  7. Give the pipeline short-lived credentials with the narrowest permissions that work. Do not store long-lived cloud keys in the repository. See storing secrets in Ansible and Terraform.
  8. Schedule a drift check and alert on exit code 2.

Learn it hands-on

The fastest way to learn this workflow is to build it: create a small AWS network with Terraform, put the code in Git, and wire a pipeline that plans on pull requests and applies on merge. Our Terraform training in Pune (classroom in Kharadi, plus live online batches across India) covers this loop with lab work. To test yourself, try the workflow-focused Terraform interview questions or the longer Terraform interview guide.

Frequently asked questions

What is the role of Terraform in a DevOps workflow?

Terraform provisions and changes infrastructure from version-controlled code. In the pipeline it runs format and validation checks, produces a plan for review on each pull request, and applies the approved change after merge.

Is Terraform a CI/CD tool?

No. Terraform does not schedule jobs or watch repositories. A CI/CD system such as GitHub Actions, GitLab CI or Jenkins runs Terraform commands, and HCP Terraform can run them remotely for you.

What is the difference between terraform plan and terraform apply?

Plan previews the create, update and destroy actions without changing anything. Apply executes them. In a pipeline you can save the plan with -out and apply that exact file so the reviewed plan is what runs.

Where should Terraform state be stored in a team?

In a remote backend with locking and versioning, such as an S3 bucket with use_lockfile = true or HCP Terraform. Do not commit state to Git, since it can contain sensitive values.

Do I need both Terraform and Ansible?

Often yes. Terraform creates cloud resources such as networks and virtual machines through provider APIs. Ansible configures the operating system and applications on those machines. Container-based teams may replace the Ansible step with images and Kubernetes.

How do you detect configuration drift with Terraform?

Run terraform plan -refresh-only to compare real objects with state, or schedule terraform plan -detailed-exitcode and alert when it returns 2. Then either update the code to match or re-apply to restore the intended setting.

Can Terraform roll back a bad change?

Not automatically. Revert the commit and apply again, which re-creates the previous configuration. Resources that hold data, such as databases, may need a backup restore, so review replacements in the plan carefully.

Which Terraform version should I learn on?

Use the current stable release. On 12 November 2026 that is v1.17.2 according to the Terraform releases page on GitHub. Pin the version in required_version so your team and pipeline stay aligned.

Official references

What's Your Reaction?

Like Like 0
Dislike Dislike 0
Love Love 0
Funny Funny 0
Angry Angry 0
Sad Sad 0
Wow Wow 0
Mridul I am a passionate technology enthusiast with a strong focus on DevOps, Cloud Computing, and Cybersecurity. Through my blogs at DevOps Training Institute, I aim to simplify complex concepts and share practical insights for learners and professionals. My goal is to empower readers with knowledge, hands-on tips, and industry best practices to stay ahead in the ever-evolving world of DevOps.