Both tools allow provisioning AWS infrastructure as code, but have key differences in approach and capabilities.
Infrastructure Modeling
CloudFormation uses YAML/JSON templates that define resources sequentially.
CloudFormation uses JSON/YAML templates to define AWS resources and their properties sequentially. Resources are created in the order defined in the template.
Terraform uses declarative configuration files and references between resources.
Terraform uses declarative configuration files written in HCL to define resources. Resources can reference attributes of other resources to establish dependencies between them in a flexible way.
Example
# CloudFormation
Resources:
VPC:
Type: AWS::EC2::VPC
Subnet:
Type: AWS::EC2::Subnet
Properties:
VpcId: !Ref VPC
# Terraform
resource "aws_vpc" "main" {}
resource "aws_subnet" "example" {
vpc_id = aws_vpc.main.id
}
State Management
CloudFormation relies on the template to implicitly define the desired state. It does not maintain an explicit real-time state of deployed resources.
Terraform explicitly tracks the real-time state of all resources in a state file, usually stored locally or in remote storage like S3. This allows checking differences between the configuration and current state to maintain consistency.
Programming Interface
CloudFormation provides CLI and APIs.
CloudFormation provides a CLI and AWS APIs for managing templates and deployments. Custom logic can be added through custom resources.
Terraform offers rich plugins and SDK for custom providers.
In addition to the CLI and APIs, Terraform has a rich plugin ecosystem and supports programming infrastructure with its own API and SDK. This allows writing custom providers, provisioners and other automation tools.
Use Cases
Simple single AWS account deployments use CloudFormation
Complex multi-account infrastructure uses Terraform
Automating tasks beyond IaC requires Terraform
For example, a multi-tier app could use:
CloudFormation for per-account VPCs and load balancers
Terraform for cross-account databases/queues
Custom Terraform provider to deploy containers
Other Considerations
Version control
Stack policies
Change sets
Target types
Modules
Automation
IDE integration
In summary, while both serve IaC purposes, Terraform provides more flexibility, portability and automation capabilities - especially for multi-account, hybrid infrastructure deployments at scale.