Logo

dev-resources.site

for different kinds of informations.

Terraform vs. AWS CloudFormation: A Detailed Comparison

Published at
10/3/2024
Categories
aws
terraform
cloudformation
Author
uendi_hoxha
Categories
3 categories in total
aws
open
terraform
open
cloudformation
open
Author
11 person written this
uendi_hoxha
open
Terraform vs. AWS CloudFormation: A Detailed Comparison

Two prominent Infrastructure as Code (IaC) tools for automating cloud resources are Terraform and AWS CloudFormation. Both enable you to define, deploy, and manage cloud infrastructure efficiently. However, there are significant differences in terms of usability, multi-cloud capabilities, state management, etc. In this article I will provide an in-depth comparison between the two, including use cases, examples and more technical details.

What is Terraform?
Terraform is an open-source IaC tool developed by HashiCorp. It uses the declarative language HCL (HashiCorp Configuration Language) to define and manage infrastructure. Terraform is multi-cloud—it supports not only AWS, but also other cloud providers like Microsoft Azure, Google Cloud and even on-premise infrastructure.
This is how a simple instance would look like in terraform:

provider "aws" {
  region = "us-east-2"
}

resource "aws_instance" "example" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"

  tags = {
    Name = "TerraformExample"
  }
}
Enter fullscreen mode Exit fullscreen mode

In the example above, Terraform uses the AWS provider to launch an EC2 instance using a specific Amazon Machine Image (AMI) and instance type. After the script is written, running terraform apply will deploy the instance.

What is AWS CloudFormation?
AWS CloudFormation is Amazon’s native IaC tool, allowing AWS users to automate the deployment of infrastructure using JSON or YAML templates. CloudFormation provides an integration with AWS services, automatically manages dependencies and handles the creation, update, and deletion of resources.
Now let's see how an instance would look like in CloudFormation:

Resources:
  MyEC2Instance:
    Type: "AWS::EC2::Instance"
    Properties:
      InstanceType: "t2.micro"
      ImageId: "ami-0c55b159cbfafe1f0"
      Tags:
        - Key: Name
          Value: CloudFormationExample
Enter fullscreen mode Exit fullscreen mode

The CloudFormation template above defines an EC2 instance using the AWS::EC2::Instance resource type. Similar to Terraform, running the aws cloudformation create-stack command will provision the instance.

Key Differences Between Terraform and AWS CloudFormation
a. Multi-Cloud vs AWS-Specific
Terraform's most significant advantage is its multi-cloud support. You can manage infrastructure across various cloud providers using a single tool and language. This makes it ideal for companies pursuing hybrid or multi-cloud strategies.
At the other hand, CloudFormation is AWS-specific. It’s tailored for AWS services and is integrated with the AWS ecosystem, giving you immediate access to the latest AWS features. If your infrastructure is fully based on AWS, CloudFormation may provide better AWS-specific optimizations and service integration.

b. Language and Syntax
Terraform uses the HCL syntax, designed to be human-readable and intuitive. HCL makes it easier to write infrastructure code, and its modular approach encourages code reuse. Modules in Terraform allow you to organize and standardize your infrastructure deployments.
Example of terraform module:

module "network" {
  source = "./modules/network"
  cidr_block = "10.0.0.0/16"
}

module "ec2" {
  source = "./modules/ec2"
  instance_type = "t2.micro"
}
Enter fullscreen mode Exit fullscreen mode

CloudFormation templates are written in YAML or JSON, both of which are more verbose and can be harder to manage for large templates. However, YAML is still widely used and preferred over JSON for its readability. CloudFormation also offers nested stacks, which allow for some modularity but are more rigid than Terraform’s modules.

c. State Management
Terraform maintains a state file that records the infrastructure’s current status. This state file is critical for determining what changes are needed in the next deployment. However, managing state files especially in team environments can be challenging and requires careful handling (for example storing the state file in a remote backend like S3).

CloudFormation does not expose state to the user. AWS manages the state internally, which simplifies usage. You don’t need to worry about handling state files, which can reduce complexity for simpler deployments. However, for more complex deployments that need granular control over state, Terraform might be the better choice.

d. Error Handling and Rollbacks
Terraform provides detailed and informative error messages, which are helpful for debugging. However, in some cases Terraform might leave infrastructure in a partially deployed or failed state, requiring manual intervention to fix inconsistencies.

Meanwhile, CloudFormation has built-in rollback functionality. If a stack fails to deploy, CloudFormation will automatically attempt to revert to the last known stable state. This makes it more robust in terms of error recovery, especially for large deployments.

e. Provisioners and Extensibility
Terraform has the concept of provisioners, which allow you to execute scripts on your resources after they’re created. This feature makes it possible to configure servers or services in ways that go beyond basic resource creation.

resource "aws_instance" "example" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"

  provisioner "local-exec" {
    command = "echo Instance created!"
  }
}
Enter fullscreen mode Exit fullscreen mode

CloudFormation doesn’t support provisioners in the same way Terraform does. Instead, AWS recommends using services like AWS Lambda or AWS Systems Manager to execute post-deployment tasks. While these can achieve similar outcomes, they add extra complexity.

f. Compliance and Security
Terraform supports integrations with security and compliance tools like AWS Config and Cloud Custodian, but it requires custom configurations. Terraform is more flexible for companies with complex compliance needs spanning multiple cloud providers.

CloudFormation integrates with AWS Config and AWS Organizations, making it easier to implement compliance rules and security policies directly within AWS. For AWS-centric environments, CloudFormation may be more straightforward for enforcing compliance.

g. Cost
Terraform itself is free and open-source, though you might incur costs for remote state storage, version control, and CI/CD pipelines (e.g., using S3 or Terraform Cloud).

CloudFormation is free to use, as it’s included with AWS services. However, depending on the resources you deploy, there could be indirect costs like storage or execution time for rollback operations.

Here’s an outline I created with the key factors to consider when choosing between Terraform and AWS CloudFormation:

Image description

cloudformation Article's
30 articles in total
Favicon
Thrilled to Announce the Launch of My Book "Mastering Infrastructure as Code with AWS CloudFormation"
Favicon
[Solved] AWS Resource limit exceeded
Favicon
A Comparative Analysis of Terraform and CloudFormation
Favicon
AWS CDK Typescript Simple Project for Cloud Formation of Resources Required for Kubernetes Study
Favicon
Customize VPCs with CloudFormation Conditions
Favicon
AWS CloudFormation: Infrastructure as Code for Efficient Cloud Management
Favicon
Using CloudFormation to deploy a web app with HA
Favicon
Automated Control Rollout in AWS Control Tower
Favicon
Launch an EC2 instance in a custom-made VPC using cloud formation
Favicon
AWS Automatically Accept Transit Gateway Attachments for allowed CIDR and Account pairs
Favicon
AWS CloudFormation Git sync now allows you to review your stack changes via Pull Request (PR)
Favicon
Terraform vs. AWS CloudFormation: A Detailed Comparison
Favicon
Terraform vs CloudFormation: Choosing the Best IaC Tool
Favicon
Automating AWS Cost and Usage Report with CloudFormation
Favicon
Calling All Senior DevOps Trailblazers!
Favicon
Move aws resources from one stack to another cloudformation stack
Favicon
Amazon CloudFormation Custom Resources Best Practices with CDK and Python Examples
Favicon
Domesticate AWS nested stacks in Java: doing the chores Cloudformation doesn't do (w/ code samples)
Favicon
Please stop publishing AWS S3 buckets as static websites! Read here for a secure, fast, and free-ish approach [1st episode]
Favicon
App runner with CloudFormation AWS (json, nodejs, java )
Favicon
Introducing AWS CloudFormation
Favicon
Simple steps to create AWS EKS Cluster and Nodes
Favicon
Deep Dive on Amazon Managed Workflows for Apache Airflow Using CloudFormation
Favicon
Importing CloudFormation Resources to help fix deployments to Production
Favicon
Update Github token in Codepipeline with Cloudformation
Favicon
Integration of Chatbot(Amazon Lex) in a static website (Hosted on S3 and cloud front)
Favicon
AWS CloudFormation - Automating Cloud Infrastructure
Favicon
Creating an AWS Auto Scaling Architecture with a monitoring dashboard
Favicon
Terraform vs. AWS CloudFormation
Favicon
Use AWS StepFunctions for SSM Patching Alerts

Featured ones: