A declarative tool keeps a record of what it believes already exists, called state. Terraform stores this in a terraform.tfstate file, usually kept in an S3 bucket or Terraform Cloud rather than on a laptop. When you run a plan, the tool compares three things: the desired state in your files, the recorded state, and the live state queried from the cloud API.
From that comparison it builds an execution plan: create these two resources, modify that one, delete this orphan. You review the plan, approve it, and the tool calls the provider APIs (AWS, GCP, Azure, Cloudflare, and so on) in dependency order. It knows the database must exist before the app that connects to it, so it builds a graph and walks it.
Idempotency is the key property. Running apply twice with no file changes produces zero changes the second time, because the live state already matches. This is what makes IaC safe to run repeatedly and safe to automate inside a CI/CD pipeline.
Pulumi works the same way but lets you write the definitions in TypeScript, Python, Go, or C# instead of a custom language, so you get loops, functions, and real package management. CloudFormation and Azure Bicep are the cloud-vendor-native equivalents, scoped to one provider.