Terraform & IaC (50 Qs)•Part 1: Terraform Core Architecture, HCL & Providers (1 - 15)
What is Infrastructure as Code (IaC), and how does Declarative (Terraform) differ from Imperative (Ansible / Scripts)?
senior LevelCode ExampleFormsCI/CD & DevOpsSystem Design
In Simple Words: Infrastructure as Code (IaC) is the practice of provisioning, configuring, and managing computing infrastructure using machine-readable configuration files rather than manual UI clicks or interactive CLI commands.
- Declarative (Terraform, OpenTofu, CloudFormation): You specify the desired end state ("I want 3 EC2 instances in a private subnet and a PostgreSQL database"). Terraform automatically calculates the dependency graph and executes the minimal set of CRUD operations to reach that state.
- Imperative (Ansible, Bash, Python scripts): You write explicit step-by-step instructions ("Step 1: run apt-get, Step 2: create security group, Step 3: launch VM"). If run twice, imperative scripts often fail unless carefully made idempotent.
hcl
# Declarative: Terraform ensures 3 instances exist. If 2 exist, it creates 1.
resource "aws_instance" "web" {
count = 3
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t3.micro"
}