Declarative vs Imperative IaC: Differences and Examples

Declarative vs imperative infrastructure as code with side-by-side examples, where Terraform, Ansible, Pulumi and Kubernetes fit, and how to choose.

Aug 16, 2025 - 11:06
Nov 9, 2026 - 08:37
 0  104
Declarative vs Imperative IaC: Differences and Examples

Declarative infrastructure as code describes the end state you want, and the tool works out the steps to reach it. Imperative IaC lists the steps to run, in order. Declarative tools such as Terraform, CloudFormation and Kubernetes manifests handle drift and repeat runs well; imperative scripts give finer control over sequence but you must make them safe to re-run yourself.

This guide explains the two models with side-by-side examples, shows where popular tools really sit (several are mixed), and gives a practical way to choose. For a ranked overview of the tools themselves, see the 12 Infrastructure as Code Tools Ranked for DevOps pillar.

Key takeaways

  • Declarative = "what". Imperative = "how". The difference is who owns the plan: the tool or you.
  • Declarative tools compare desired state with actual state and compute a change set. That makes previews (terraform plan, CloudFormation change sets, kubectl diff) possible.
  • Imperative code is not automatically worse. It is the right fit for ordered procedures such as database migrations, failovers and one-off runbooks.
  • Idempotency (same result however many times you run it) comes built in with declarative tools. Imperative scripts need explicit checks.
  • Many tools mix the two. Ansible runs tasks in order but most modules are declarative about state. Pulumi and AWS CDK use general-purpose languages to build a declarative model that an engine then applies.

The two models in one example

Goal: an S3 bucket named example-logs-prod with versioning enabled.

Imperative (AWS CLI script)

#!/usr/bin/env bash
set -euo pipefail
BUCKET=example-logs-prod
REGION=ap-south-1

if ! aws s3api head-bucket --bucket "$BUCKET" 2>/dev/null; then
  aws s3api create-bucket --bucket "$BUCKET" --region "$REGION" \
    --create-bucket-configuration LocationConstraint="$REGION"
fi

aws s3api put-bucket-versioning --bucket "$BUCKET" \
  --versioning-configuration Status=Enabled

You decide the order, you add the existence check so the script can run twice, and you would have to write more code to handle every other property, or to delete the bucket if it is no longer wanted.

Declarative (Terraform)

resource "aws_s3_bucket" "logs" {
  bucket = "example-logs-prod"
}

resource "aws_s3_bucket_versioning" "logs" {
  bucket = aws_s3_bucket.logs.id
  versioning_configuration {
    status = "Enabled"
  }
}

Terraform reads current state, builds a dependency graph from the reference between the two resources, shows a plan and applies only the difference. Remove the blocks and the next apply plans a deletion. Run it again with no changes and the plan is empty.

Side-by-side comparison

AspectDeclarativeImperative
You writeThe desired end stateA sequence of commands
OrderingInferred from dependenciesExplicit, top to bottom
Re-runningIdempotent by designOnly if you add checks
Preview of changesBuilt in (plan, diff, change set)Usually none, or a dry-run flag per command
Drift handlingDetected on the next plan, corrected on applyNot detected unless you script it
DeletionsRemoving code removes the resourceNeeds a separate teardown script
State trackingOften a state file or the platform's own record (Terraform state, CloudFormation stacks, Kubernetes API)None by default
Learning curveNew language or schema, thinking in end statesFamiliar scripting
FlexibilityLimited to what the provider modelsAnything an API or CLI allows
Best forLong-lived infrastructure, environments, platformsOrdered procedures, migrations, glue, one-off tasks

Why declarative became the default for infrastructure

Drift detection

Someone changes a security group in the console during an incident. With a declarative tool, the next plan shows the difference between code and reality, and the team decides whether to revert or update the code. With a script, the change goes unnoticed until it causes trouble. Read more in the role of configuration drift detection and why drift is a silent killer in IaC environments.

Reviewable changes

A plan output in a pull request tells reviewers exactly what will be created, changed or destroyed. Policy-as-code tools can check that plan before apply. Reviewing a script tells you what it will try, not what it will change in this specific environment.

Repeatable environments

The same declarative module with different variables produces dev, staging and production that match in shape. Scripts tend to accumulate environment-specific branches.

Safe parallelism

Because the tool knows the dependency graph, it can create independent resources in parallel. Terraform does this by default, with a configurable parallelism limit.

Where imperative still wins

  • Ordered operations. Draining a node, failing over a database, rotating credentials across services in a set sequence.
  • Data changes. Schema migrations and backfills are procedures by nature. Tools such as Flyway and Liquibase run ordered migration scripts.
  • Things the provider does not model. A brand-new API feature may exist in the CLI before the Terraform provider supports it.
  • Bootstrapping. Creating the state bucket that Terraform itself will use is a classic chicken-and-egg step often done with a short script.
  • Runbooks. Incident procedures are step lists, and making them executable scripts is a good form of automation.

Where common tools really sit

ToolModelNotes
Terraform / OpenTofuDeclarativeHCL describes resources; plan and apply against a state file
AWS CloudFormationDeclarativeYAML or JSON templates; stacks and change sets
Azure Bicep / ARM templatesDeclarativeWhat-if operation previews changes
Kubernetes manifestsDeclarativekubectl apply and controllers reconcile to desired state; kubectl create and kubectl scale are imperative commands
PulumiImperative language, declarative engineTypeScript, Python, Go or C# build a resource graph; the engine diffs and applies it
AWS CDKImperative language, declarative outputCode synthesizes CloudFormation templates
AnsibleMixedTasks run in order (procedural), but modules like ansible.builtin.package with state: present are declarative and idempotent; command and shell are not unless you add creates or changed_when
PuppetDeclarativeResources and a catalog the agent enforces
ChefMostly declarative resources in a Ruby DSLRecipes run in order; resources converge to state
Bash / PowerShell with cloud CLIsImperativeFull control, no state

Kubernetes as a clear example

# Imperative commands
kubectl create deployment web --image=nginx:1.27
kubectl scale deployment web --replicas=3

# Declarative: the file is the source of truth
kubectl diff  -f web-deployment.yaml
kubectl apply -f web-deployment.yaml

The Kubernetes documentation describes three techniques: imperative commands, imperative object configuration, and declarative object configuration, and recommends the declarative approach for production. GitOps tools such as Argo CD and Flux take this further by continuously reconciling the cluster with a Git repository.

Ansible as a mixed example

- name: Web server baseline
  hosts: web
  become: true
  tasks:
    - name: Nginx is installed           # declarative module
      ansible.builtin.package:
        name: nginx
        state: present

    - name: Nginx is running and enabled # declarative module
      ansible.builtin.service:
        name: nginx
        state: started
        enabled: true

    - name: Initialise app data once     # imperative, guarded
      ansible.builtin.command: /opt/app/bin/init-data
      args:
        creates: /var/lib/app/.initialised

The first two tasks describe state and are safe to re-run. The third runs a command, and the creates argument makes it idempotent by skipping it when the marker file exists. The Ansible playbooks used in production article has more patterns.

Idempotency: the property that matters most

Whatever model you use, aim for code that you can run any number of times with the same result. Ways to get there in imperative code:

  • Check before you act (does the resource exist? is the setting already correct?).
  • Use "create or update" API calls where they exist.
  • Write marker files or tags to record that a one-time step has run.
  • Use set -euo pipefail in Bash so a failure stops the script instead of continuing in a half-done state.

Mutable versus immutable is a separate choice

People sometimes mix up declarative/imperative with mutable/immutable. They are different axes. Immutable infrastructure replaces servers or containers instead of changing them in place, and you can do that declaratively (a new launch template version in Terraform) or imperatively (a script that bakes an image and swaps instances). See the pros and cons of immutable infrastructure in CI/CD.

How to choose

  1. Is the thing long-lived? Networks, clusters, databases, IAM: declarative.
  2. Is order the whole point? Migrations, failovers, rotations: imperative, written to be idempotent.
  3. Do you need previews and approvals? Declarative tools give you plans to review.
  4. Does the declarative provider support the feature? If not, a small scripted step, tracked and later replaced, is fine.
  5. What does the team already know? Pulumi or CDK can help developers who prefer general-purpose languages while keeping a declarative engine.

A common, healthy pattern is declarative for infrastructure (Terraform), declarative for cluster workloads (Kubernetes manifests with GitOps), Ansible for host configuration, and small idempotent scripts for ordered procedures, all run from CI/CD.

Common mistakes

MistakeWhy it hurtsFix
Using Terraform local-exec provisioners for real configuration workHides imperative steps inside a declarative tool, with no state or drift trackingMove configuration to Ansible, cloud-init or images; keep provisioners as a last resort, as HashiCorp's docs advise
Ansible playbooks built mostly from shell tasksNot idempotent; always report "changed"Use proper modules; add creates, removes or changed_when
Fixing production by hand and never updating codeDrift; the next apply reverts the fixUpdate code first, or import and reconcile right after
Mixing kubectl edit with GitOpsController reverts manual editsChange the Git repository only
Scripts without error handlingPartial changes on failureset -euo pipefail, checks, and clear rollback steps

Learn it hands-on

Our Terraform training covers declarative infrastructure, state, plans and modules with labs, and pairs well with the Ansible course for configuration. Classes run in Kharadi, Pune and live online across India. For interview practice, try the Terraform interview questions.

Frequently asked questions

What is declarative infrastructure as code?

Code that describes the desired end state of infrastructure. The tool compares it with the current state and decides which create, update or delete actions to run. Terraform, CloudFormation and Kubernetes manifests are examples.

What is imperative infrastructure as code?

Code that lists the exact steps to run in order, such as a Bash script calling cloud CLI commands. You control the sequence and must handle existence checks and errors yourself.

Is Terraform declarative or imperative?

Declarative. You describe resources in HCL, and Terraform builds a dependency graph, compares it with state and plans the changes.

Is Ansible declarative or imperative?

Both. Playbooks run tasks in order, which is procedural, but most modules declare a desired state and are idempotent. Command and shell tasks are imperative unless guarded.

Is Pulumi declarative?

Pulumi programs are written in general-purpose languages, but they produce a desired-state resource graph that Pulumi's engine diffs and applies, so the deployment model is declarative.

Which approach is better for production?

Declarative for long-lived infrastructure, because of previews, drift detection and idempotency. Use imperative, idempotent scripts for ordered procedures such as migrations and failovers.

What is idempotency in IaC?

Running the same code many times produces the same result without unwanted changes. Declarative tools provide it by design; imperative scripts need checks.

Can I combine declarative and imperative tools?

Yes, and most teams do: Terraform for infrastructure, Kubernetes manifests for workloads, Ansible for configuration and small scripts for procedures, all orchestrated by a CI/CD pipeline.

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.