Bird
Raised Fist0
Terraformcloud~15 mins

Declarative vs imperative IaC in Terraform - Trade-offs & Expert Analysis

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Overview - Declarative vs imperative IaC
What is it?
Infrastructure as Code (IaC) is a way to manage and provision computer resources using code instead of manual steps. Declarative IaC means you describe the desired end state of your infrastructure, and the system figures out how to get there. Imperative IaC means you write step-by-step instructions telling the system exactly what to do. Both help automate infrastructure but in different ways.
Why it matters
Without IaC, managing infrastructure is slow, error-prone, and hard to repeat. Declarative IaC solves this by letting you focus on what you want, not how to do it, making infrastructure reliable and consistent. Imperative IaC gives you control but can be complex and fragile. Understanding the difference helps you choose the right approach to build and maintain cloud systems efficiently.
Where it fits
Before this, you should know basic cloud infrastructure concepts and manual resource management. After this, you can learn specific IaC tools like Terraform (declarative) or Ansible (imperative), and how to write and deploy infrastructure code safely.
Mental Model
Core Idea
Declarative IaC describes the desired final infrastructure state, while imperative IaC describes the exact steps to reach that state.
Think of it like...
Declarative IaC is like telling a GPS your destination and letting it find the best route, while imperative IaC is like giving someone turn-by-turn driving directions.
┌───────────────┐       ┌─────────────────────┐
│ Desired State │──────▶│ Declarative IaC Tool │
└───────────────┘       └─────────┬───────────┘
                                   │
                                   ▼
                        ┌─────────────────────┐
                        │ Infrastructure State │
                        └─────────────────────┘


┌───────────────┐       ┌─────────────────────┐
│ Step-by-Step  │──────▶│ Imperative IaC Tool  │
│ Instructions  │       └─────────┬───────────┘
└───────────────┘                 │
                                 ▼
                      ┌─────────────────────┐
                      │ Infrastructure State │
                      └─────────────────────┘
Build-Up - 7 Steps
1
FoundationWhat is Infrastructure as Code
🤔
Concept: Introduce the basic idea of managing infrastructure using code instead of manual actions.
Infrastructure as Code means writing code to create, update, and delete cloud resources like servers, networks, and databases. This replaces clicking buttons or typing commands manually. It makes infrastructure repeatable and less error-prone.
Result
You understand that infrastructure can be managed by code, making it automated and consistent.
Knowing that infrastructure can be controlled by code opens the door to automation and reliability in cloud management.
2
FoundationDifference Between Declarative and Imperative
🤔
Concept: Explain the two main styles of writing IaC: declarative and imperative.
Declarative IaC means you write what you want the infrastructure to look like at the end. The tool figures out how to get there. Imperative IaC means you write exact commands to create or change resources step by step.
Result
You can tell the difference between describing the goal (declarative) and describing the process (imperative).
Understanding these two styles helps you choose the right approach for your infrastructure tasks.
3
IntermediateHow Declarative IaC Works in Terraform
🤔Before reading on: do you think Terraform requires you to write commands for each step or just the final desired state? Commit to your answer.
Concept: Show how Terraform uses declarative code to manage infrastructure.
In Terraform, you write configuration files describing resources like servers or databases and their desired properties. Terraform compares this desired state with the current state and figures out what changes to make to reach the goal.
Result
Terraform automatically plans and applies only the necessary changes to match your declared infrastructure.
Knowing Terraform focuses on the end state reduces the need to manage complex sequences of commands manually.
4
IntermediateHow Imperative IaC Works in Tools Like Ansible
🤔Before reading on: do you think imperative IaC tools automatically figure out changes or follow exact instructions? Commit to your answer.
Concept: Explain how imperative IaC tools require explicit step-by-step instructions.
Imperative IaC tools like Ansible run tasks in the order you write them. You tell the tool to create a server, then install software, then configure settings. The tool follows these steps exactly, without guessing the final state.
Result
The infrastructure changes exactly as scripted, but you must manage the order and details carefully.
Understanding that imperative IaC requires explicit instructions helps avoid mistakes from missing or wrong steps.
5
IntermediatePros and Cons of Declarative IaC
🤔Before reading on: do you think declarative IaC gives you more control or more simplicity? Commit to your answer.
Concept: Discuss the advantages and limitations of declarative IaC.
Declarative IaC simplifies infrastructure management by focusing on the desired state, reducing errors and making changes predictable. However, it can be less flexible for complex sequences or conditional logic.
Result
You see why many teams prefer declarative IaC for standard infrastructure but may need other tools for complex tasks.
Knowing the tradeoffs helps you pick declarative IaC when you want simplicity and reliability.
6
AdvancedChallenges in Imperative IaC at Scale
🤔Before reading on: do you think imperative IaC scales easily for large infrastructures? Commit to your answer.
Concept: Explore why imperative IaC can become complex and error-prone as infrastructure grows.
Imperative IaC requires managing exact steps and their order. In large systems, this leads to fragile scripts that break if steps run out of order or fail. It also makes it hard to know the current state without extra tracking.
Result
You understand why imperative IaC can cause maintenance headaches in big projects.
Recognizing these challenges explains why declarative IaC is often preferred for large, dynamic environments.
7
ExpertTerraform’s State and Plan Mechanism
🤔Before reading on: do you think Terraform applies changes blindly or plans them first? Commit to your answer.
Concept: Deep dive into how Terraform tracks infrastructure state and plans changes before applying.
Terraform keeps a state file recording the current infrastructure. When you run it, Terraform compares this state with your configuration and creates a plan showing what will change. You review and approve this plan before Terraform makes any changes, ensuring safety and predictability.
Result
Terraform prevents accidental changes and helps you understand impact before applying.
Understanding Terraform’s state and plan system reveals why declarative IaC can be both safe and efficient in production.
Under the Hood
Declarative IaC tools maintain a record of the current infrastructure state and compare it with the desired state described in code. They calculate a difference (diff) and generate a plan of actions to reconcile the two. Imperative IaC tools execute commands in the order given without tracking state, relying on the user to manage correctness.
Why designed this way?
Declarative IaC was designed to reduce human error and improve repeatability by focusing on the end goal rather than the process. Imperative IaC reflects traditional scripting and manual operations, offering fine control but requiring more effort to maintain correctness. The tradeoff is between simplicity and control.
┌───────────────┐          ┌───────────────┐          ┌───────────────┐
│ Desired State │─────────▶│ Diff & Plan   │─────────▶│ Apply Changes │
└───────────────┘          └───────────────┘          └───────────────┘
         ▲                                                      │
         │                                                      ▼
┌───────────────┐                                         ┌───────────────┐
│ Current State │────────────────────────────────────────▶│ Updated State │
└───────────────┘                                         └───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does declarative IaC require you to write every step explicitly? Commit to yes or no.
Common Belief:Declarative IaC means you must write all the steps to create infrastructure.
Tap to reveal reality
Reality:Declarative IaC only requires you to describe the desired final state; the tool figures out the steps.
Why it matters:Believing this leads to unnecessary complexity and defeats the purpose of declarative IaC.
Quick: Do imperative IaC tools automatically detect and fix drift? Commit to yes or no.
Common Belief:Imperative IaC tools automatically detect differences between desired and actual infrastructure and fix them.
Tap to reveal reality
Reality:Imperative IaC tools run commands as given and do not track or fix drift automatically.
Why it matters:Assuming automatic drift correction causes unexpected infrastructure mismatches and failures.
Quick: Is declarative IaC always simpler and better than imperative? Commit to yes or no.
Common Belief:Declarative IaC is always the best choice because it is simpler and less error-prone.
Tap to reveal reality
Reality:Declarative IaC can be less flexible for complex workflows where imperative control is needed.
Why it matters:Ignoring this can lead to forcing declarative IaC where imperative scripting would be more effective.
Quick: Can Terraform apply changes without a plan? Commit to yes or no.
Common Belief:Terraform applies changes immediately without showing what will happen first.
Tap to reveal reality
Reality:Terraform generates a plan first, which you review and approve before applying changes.
Why it matters:Misunderstanding this can cause fear or misuse of Terraform, missing its safety features.
Expert Zone
1
Terraform’s state file is a single source of truth but can become a bottleneck or cause conflicts in team environments if not managed properly.
2
Imperative IaC scripts can be wrapped in idempotent tasks to mimic declarative behavior, but this requires careful scripting and testing.
3
Declarative IaC tools often support limited conditional logic; complex workflows may require combining declarative and imperative approaches.
When NOT to use
Declarative IaC is not ideal when you need precise control over the order of operations or complex conditional logic. In such cases, imperative tools like Ansible or scripting languages are better. Conversely, imperative IaC is less suitable for large, dynamic environments where state tracking and drift detection are critical.
Production Patterns
In production, teams use Terraform for core infrastructure provisioning with state locking and remote backends for collaboration. Imperative tools handle configuration management and application deployment steps. Combining both approaches in pipelines balances control and simplicity.
Connections
Functional Programming
Declarative IaC shares the declarative style of functional programming, focusing on what to do rather than how to do it.
Understanding declarative IaC helps grasp functional programming concepts like immutability and pure functions, which also emphasize describing outcomes over steps.
Project Management
Imperative IaC resembles detailed project plans with step-by-step tasks, while declarative IaC is like setting project goals and letting teams decide how to achieve them.
This connection shows how different management styles affect complexity and flexibility in both infrastructure and projects.
Cooking Recipes
Imperative IaC is like following a recipe step-by-step, while declarative IaC is like telling a chef the dish you want and letting them decide the process.
This cross-domain link helps understand the tradeoff between control and flexibility in instructions.
Common Pitfalls
#1Writing imperative commands inside a declarative tool configuration.
Wrong approach:resource "aws_instance" "example" { provisioner "local-exec" { command = "echo 'Step 1: Create instance'" } # Trying to script steps imperatively inside Terraform }
Correct approach:resource "aws_instance" "example" { ami = "ami-123456" instance_type = "t2.micro" # Declare desired resource properties only }
Root cause:Confusing declarative syntax with imperative scripting leads to misuse and complexity.
#2Running imperative IaC tasks without checking current state.
Wrong approach:- name: Install package apt: name: nginx state: present # No check if nginx is already installed, blindly runs every time
Correct approach:- name: Ensure nginx is installed apt: name: nginx state: present # Idempotent task that only changes if needed
Root cause:Not understanding idempotency causes unnecessary changes and errors.
#3Ignoring Terraform plan before apply.
Wrong approach:terraform apply -auto-approve # Applies changes immediately without review
Correct approach:terraform plan terraform apply # Review plan output before applying changes
Root cause:Skipping plan removes safety checks and can cause unexpected infrastructure changes.
Key Takeaways
Infrastructure as Code automates cloud resource management by using code instead of manual steps.
Declarative IaC focuses on describing the desired final state, letting tools handle the process.
Imperative IaC requires explicit step-by-step instructions, giving fine control but more complexity.
Terraform is a popular declarative IaC tool that uses state and plans to safely apply changes.
Choosing between declarative and imperative IaC depends on the task complexity, control needs, and team workflow.

Practice

(1/5)
1. What is the main difference between declarative and imperative Infrastructure as Code (IaC)?
easy
A. Declarative IaC describes the desired end state, while imperative IaC specifies exact steps to reach it.
B. Declarative IaC requires manual commands, while imperative IaC is fully automatic.
C. Declarative IaC is only for cloud, imperative IaC is for on-premises.
D. Declarative IaC uses scripts, imperative IaC uses configuration files.

Solution

  1. Step 1: Understand declarative IaC

    Declarative IaC focuses on describing the final desired state of infrastructure without specifying how to achieve it.
  2. Step 2: Understand imperative IaC

    Imperative IaC lists the exact commands or steps needed to create or change infrastructure.
  3. Final Answer:

    Declarative IaC describes the desired end state, while imperative IaC specifies exact steps to reach it. -> Option A
  4. Quick Check:

    Declarative = final state, Imperative = steps [OK]
Hint: Declarative = what you want; imperative = how to do it [OK]
Common Mistakes:
  • Confusing declarative with imperative steps
  • Thinking declarative requires manual commands
  • Assuming declarative only works for cloud
2. Which of the following Terraform code snippets correctly shows a declarative resource definition?
easy
A. create_instance("ami-123", "t2.micro")
B. resource "aws_instance" "web" { ami = "ami-123" instance_type = "t2.micro" }
C. if not instance_exists() then create_instance()
D. run_command("aws ec2 run-instances --image-id ami-123")

Solution

  1. Step 1: Identify declarative syntax

    Terraform resource blocks declare the desired state, like the resource "aws_instance" "web" { ... } block.
  2. Step 2: Compare with imperative styles

    Options B, C, and D show commands or logic steps, which are imperative, not declarative.
  3. Final Answer:

    The Terraform resource block syntax is declarative. -> Option B
  4. Quick Check:

    Terraform resource block = declarative [OK]
Hint: Terraform resource blocks are declarative descriptions [OK]
Common Mistakes:
  • Choosing imperative command syntax as declarative
  • Confusing function calls with resource declarations
  • Ignoring the resource block structure
3. Given this Terraform snippet, what will Terraform do when you run terraform apply if the AWS instance does not exist yet?
resource "aws_instance" "example" {
  ami           = "ami-abc123"
  instance_type = "t2.micro"
}
medium
A. Terraform will prompt for manual commands to create the instance.
B. Terraform will delete any existing instances and do nothing else.
C. Terraform will create a new AWS instance with the specified AMI and instance type.
D. Terraform will throw a syntax error because the resource block is incomplete.

Solution

  1. Step 1: Understand Terraform apply behavior

    Terraform compares the current state with the desired state defined in the resource block.
  2. Step 2: Predict action if resource missing

    If the AWS instance does not exist, Terraform will create it to match the declared state.
  3. Final Answer:

    Terraform will create a new AWS instance with the specified AMI and instance type. -> Option C
  4. Quick Check:

    Missing resource = Terraform creates it [OK]
Hint: Terraform creates missing resources to match declared state [OK]
Common Mistakes:
  • Thinking Terraform deletes resources by default
  • Expecting manual commands during apply
  • Assuming syntax error in valid resource block
4. You wrote this Terraform code but terraform apply fails with an error:
resource "aws_instance" "web" {
  ami = "ami-123"
  instance_type = t2.micro
}
What is the likely cause of the error?
medium
A. Terraform requires an explicit create command inside the resource block.
B. The resource name "web" is invalid and must be changed.
C. The AMI ID "ami-123" is not allowed in Terraform.
D. Missing quotes around the instance_type value causes a syntax error.

Solution

  1. Step 1: Check syntax of resource attributes

    Terraform requires string values to be in quotes. The instance_type value is missing quotes.
  2. Step 2: Identify error cause

    Missing quotes cause a syntax error, preventing Terraform from parsing the file.
  3. Final Answer:

    Missing quotes around the instance_type value causes a syntax error. -> Option D
  4. Quick Check:

    Strings need quotes in Terraform [OK]
Hint: Always quote string values in Terraform resource blocks [OK]
Common Mistakes:
  • Ignoring missing quotes around strings
  • Thinking resource names cause syntax errors
  • Expecting commands inside resource blocks
5. You want to create a cloud infrastructure using Terraform declarative IaC. Which approach best fits this goal?
hard
A. Write a Terraform configuration file describing the desired resources and run terraform apply.
B. Write a script with commands to create each resource step-by-step manually.
C. Manually create resources in the cloud console, then import them into Terraform.
D. Use a shell script to run cloud CLI commands in order.

Solution

  1. Step 1: Understand declarative IaC goal

    Declarative IaC means describing the final infrastructure state in configuration files.
  2. Step 2: Identify Terraform usage

    Terraform uses configuration files to declare resources, then applies changes automatically.
  3. Final Answer:

    Write a Terraform configuration file describing the desired resources and run terraform apply. -> Option A
  4. Quick Check:

    Declarative IaC = config files + apply [OK]
Hint: Use Terraform config files, not manual scripts, for declarative IaC [OK]
Common Mistakes:
  • Confusing declarative IaC with manual scripting
  • Thinking manual cloud console use is declarative
  • Using imperative CLI commands instead of config files