Interview Prep/DevOps Fundamentals/Infrastructure & cloud basics

What is the difference between declarative and imperative infrastructure?

BeginnerConceptInfrastructure & cloud basics
Answer

In one line: Declarative means you describe the end state you want and the tool works out how to get there; imperative means you write the exact steps to run, in order.

Imperative example (a script):

aws ec2 run-instances --image-id ami-0abc --instance-type t3.micro --count 2

Run it twice and you get four servers — the script doesn't know what already exists.

Declarative example (Terraform):

resource "aws_instance" "web" {
  count         = 2
  ami           = "ami-0abc"
  instance_type = "t3.micro"
}

Run terraform apply ten times and you still have two servers. Terraform compares the desired state with the real state and only makes the needed changes.

Comparison:

Declarative Imperative
You write What you want How to do it
Re-running Safe (idempotent) Can repeat actions
Handles drift Yes, compares and corrects No
Examples Terraform, CloudFormation, Bicep, Kubernetes YAML, Helm Bash scripts, AWS CLI, SDK scripts

Ansible sits in between: you write tasks in order (imperative-style), but most modules are idempotent (state: present), so it behaves declaratively.

Pulumi and AWS CDK let you use real programming languages, but they still produce a declarative desired state.

Why DevOps prefers declarative:

  • Safe to re-run.
  • Easy to review: the code shows exactly what should exist.
  • Supports drift detection and GitOps (desired state in Git).

Where imperative is still useful: one-off tasks, migrations, quick automation, and glue scripts in pipelines.

Tip for interviews: use the "run it twice" example — it makes idempotency and the difference obvious.

All DevOps Fundamentals questions

More on Infrastructure & cloud basics