Let's think about this for a second
CloudFormation is AWS's own IaC tool — it only works for AWS resources (AWS-only, cloud-vendor lock-in). Terraform, on the other hand, is cloud-agnostic — it works with AWS, Azure, GCP, Kubernetes, and hundreds of other SaaS providers through a single unified 'provider' concept. Ansible is a 'configuration management' tool — it's designed for installing/configuring software on servers that already exist (whereas Terraform is designed for 'creating' the servers themselves). Pulumi shares Terraform's concept but lets you write in a real programming language like Python/TypeScript/Go instead of HCL.
Let's connect this to a real scenario
In real-world projects, Terraform and Ansible are often used together — Terraform first creates the servers/network/database (infrastructure), then Ansible installs/configures software inside those servers (the application layer). It's the same distinction as 'building the house (Terraform)' versus 'arranging the furniture inside it (Ansible).'
Let's look at an example
Tool Purpose Vendor lock-in
---------------------------------------------------------------
CloudFormation AWS resources only Yes (AWS only)
Terraform Any provider via HCL No
Ansible Configure existing servers No
Pulumi Terraform-like, real languages NoBe able to distinguish the purpose of each of the 4 IaC tools.5-minute try-it
For a web app (AWS server + database + installing Nginx software), write out at which stage you'd use Terraform and at which stage you'd use Ansible (or another tool).
A quick word of caution
Don't assume 'Terraform is better than every other tool' — the right tool depends on your project's requirements (single-cloud vs multi-cloud, your team's familiarity with the tool).