Terraform vs AWS CloudFormation: An In-Depth Comparison

Terraform vs AWS CloudFormation: An In-Depth Comparison

In our last discussion on Pulumi vs. Terraform, we explored the intricate world of Infrastructure-as-Code (IaC) tools, delving into how these technologies streamline the deployment and management of cloud environment resources.

Continuing on this path, today we’re comparing two other IaC giants: Terraform and CloudFormation. Both tools have established substantial footholds within their respective areas, becoming the preferred options for developers aiming to automate their cloud infrastructure.

In this post, I’ll compare the tools, discuss their pros and cons, and demonstrate how they can be used with env0, leveraging the platform’s multi-framework support, which makes it compatible with any IaC tool.

What is Terraform?

Terraform, developed by HashiCorp, excels as an IaC tool facilitating the provisioning and management of AWS resources, as well as infrastructure resources across different cloud providers, embodying a cloud-agnostic approach with native support for Google Cloud, AWS Cloud, and more.

Historically speaking, Terraform’s open-source roots encouraged a vibrant community contribution, leading to an extensive provider ecosystem that spans beyond cloud providers to include SaaS and PaaS offerings. One of Terraform’s unique features is its ability to manage resources declaratively, allowing users to define their infrastructure in code that can be versioned, reused, and shared.

Note: Following the license change in August 2023, all future releases of Terraform will adopt the BUSL license, while all versions prior to 1.5.x will remain open-source.

After the shift, OpenTofu emerged as an open-source alternative to Terraform. Originating from a fork of Terraform as a drop-in replacement for Terraform version 1.6, OpenTofu preserves all of the core functionalities that have endeared Terraform to developers, including the use of all providers and Terraform modules.  As such, all of the points raised about Terraform in this article equally apply to OpenTofu

What is AWS CloudFormation?

On the flip side, CloudFormation is Amazon Web Services’ (AWS) native IaC service, designed to seamlessly integrate with AWS’s vast array of services. 

As a managed service, AWS CloudFormation allows users to define their AWS resources with JSON or YAML templates, automating the provisioning and updating processes. Its deep integration with AWS ensures that users can leverage the full spectrum of AWS features and services with minimal hassle, making it a powerful tool for those heavily invested in the AWS ecosystem.

What are the differences between Terraform and CloudFormation?

To compare Terraform and CloudFormation side-by-side, let’s look at several key aspects:

Terraform vs CloudFormation: Pros and Cons

The answer is “it depends,” as each tool has its strengths and weaknesses. Here is the TLDR:

Terraform Pros and Cons

Pros:

Terraform is renowned for its flexibility and support for multiple cloud providers, offering a consistent syntax and deployment strategy across various environments. While it’s true that you can’t directly transfer the same codebase from one provider to another, Terraform offers consistent syntax and deployment techniques across different clouds.

For many organizations, this consistency is a major advantage, as it allows for the use of familiar syntax and deployment strategies when managing resources across multiple cloud environments, which is undoubtedly beneficial.

Cons:

The versatility and multi-cloud capabilities of Terraform, while beneficial, can complicate state management and configuration across diverse environments. Tailoring deployments to suit each provider’s unique requirements may raise the risk of errors and demand a comprehensive grasp of each cloud platform’s specific characteristics, posing challenges for teams less experienced with multi-cloud strategies. 

In this context, platforms like env0 emerge as invaluable allies, offering targeted support that can streamline and simplify the scaling process for organizations looking to expand their Terraform implementations.

Furthermore, Terraform relies on providers that connect to the APIs of the cloud vendors. There is usually a delay between when a service or feature is released in the cloud and when it gets supported by the Terraform provider.

This is in contrast to AWS CloudFormation which, being a native AWS service, seamlessly integrates with AWS offerings faster.

CloudFormation Pros and Cons

Pros:

CloudFormation stands out in AWS-centric environments, providing deep integration and a managed service experience that simplifies the management of AWS resources. Its native design for AWS ensures that users can fully exploit the capabilities of the cloud service, streamlining the deployment process and reducing the overhead typically associated with infrastructure management. The service’s direct integration with AWS also means that users can rely on AWS’s robust support structure and continuous updates.

Cons:

The primary limitation of CloudFormation is its exclusive focus on AWS, which can be a significant constraint for organizations with a multi-cloud strategy or those looking to avoid vendor lock-in. Additionally, while CloudFormation simplifies AWS resource management, it may not offer the same level of flexibility or community support as Terraform, potentially limiting its adaptability to complex or highly customized deployment scenarios.

Use Cases

Scenario 1: Multi-Cloud Management

Terraform shines in scenarios where organizations aim to leverage the strengths of multiple cloud platforms, such as AWS, Azure, and Google Cloud. 

By offering a single configuration language (HCL) and workflow, Terraform simplifies the complexity of managing diverse cloud services and infrastructure. This unified approach enables teams to maintain consistency in infrastructure provisioning and management practices across different clouds, reducing the learning curve and operational overhead associated with using distinct tools or interfaces for each cloud provider. 

Furthermore, Terraform’s extensive provider ecosystem allows organizations to easily integrate with a wide array of cloud services, APIs, and custom in-house solutions, facilitating a cohesive and flexible infrastructure strategy that can dynamically adapt to changing business requirements and technological landscapes.

Scenario 2: AWS-Specific Projects

For AWS cloud-centric projects, AWS CloudFormation stands out, offering a managed AWS service experience with deep integration and native support for efficiently deploying custom resources within the AWS environment. It leverages AWS’s native integration to offer a seamless and optimized experience for defining, deploying, and managing AWS resources. 

With CloudFormation, users can utilize AWS-specific features and services to their fullest potential, taking advantage of AWS’s scalability, reliability, and security features without the need for bridging tools or external dependencies. 

This deep integration simplifies the process of configuring complex AWS environments, enabling automatic handling of dependencies between resources, rollbacks on failures, and updates to existing stacks. CloudFormation’s template-based configuration, using either JSON or YAML, also ensures that infrastructure as code (IaC) practices can be easily adopted, promoting version control, collaboration, and repeatability in AWS-focused development projects.

Scenario 3: Compliance and Governance

In environments where compliance and governance are critical, Terraform’s ability to integrate with policy-as-code tools like Open Policy Agent (OPA) allows organizations to enforce policies and ensure that infrastructure deployments comply with internal and external regulations.

This use case is particularly relevant for enterprises that need to adhere to stringent security standards, audit requirements, and governance policies across their cloud infrastructure, regardless of the cloud provider. 

Terraform’s state management and planning features also contribute to a transparent, auditable, and controlled infrastructure management process, making it easier to track changes, review impacts before applying them, and ensure consistency across environments.

A Practical Demo

Let’s take a look at a simple demo to show how to create an S3 bucket in AWS using these two tools. We will use env0 for this task, leveraging its multiple-framework support, which makes it compatible with any IaC tool, Terraform, OpenTofu, Cloudformation, Pulumi, etc.

Video Walkthrough

Requirements

A free GitHub account
Access to an AWS account
A free env0 account

TLDR: You can find the main repo here

Terraform Demo

Per the video above, let’s first start with Terraform.

1. Create an env0 Template for Terraform

Start by creating a template in env0 that connects our GitHub repo. Make sure to select Terraform as the template type and give it a name as shown below:

Now it’s time to connect our template with our GitHub repo. The Terraform configuration is in the TerraformS3.tf file and is written in HCL (HashiCorp Configuration Language). You don’t need to specify the Terraform folder or branch since TerraformS3.tf is in the main branch at the root of the repo.

No variables are necessary for this deployment, so the final step for the template is to associate it with our project.

Now we’re set to establish a new environment. Navigate to the Project Environments tab on the left and proceed to initiate a new environment, choosing the template we’ve recently crafted. The deployment will commence, allowing you to monitor the logs.

2. Terraform Plan Log

Take a look at terraform plan log in env0 below.

Terraform gives you a dry-run of your plan when you run either terraform plan or terraform apply. Check out this blog post to learn about Terrform CLI commands and examples.

Terraform Apply Log

Once you confirm that you’d like to proceed, you will see the output below.

4. View the Output in AWS

In the AWS console, we can now see the resulting S3 bucket with all the options that we requested.

Notice how bucket versioning is enabled along with a tag that shows we built this with Terraform.

Next, you can see the permissions and how we block public access to this S3 bucket.

Finally, you can see the lifecycle of this S3 bucket.

5. Destroy the S3 Bucket with Terraform

Once you’re done examining this S3 bucket, you can destroy it by clicking the red destroy button in env0 inside the environment.

The Terraform plan log will show you what is about to be destroyed.

Finally, the Terraform Destroy log will show you that the resources were destroyed.

AWS CloudFormation Demo

Let’s move on to our second demo to build the same S3 bucket using AWS CloudFormation.

1. Create an env0 Template for CloudFormation

We need to create a Template in env0 similar to the template we created for Terraform, except now we select CloudFormation as our template type, as shown below.

Next, we need to select the same GitHub repo as we did for Terraform. Please note that you need to specify the AWS CloudFormation template file name – in our case, CloudFormationS3.yaml.

Next, add the AWS region as a variable and add this template to either all your projects or the one you created for this demo called: Terraform vs CloudFormation.

We are now ready to create a new environment. From the Project Environments tab on the left, go ahead and create a new environment and select the template we just created. The deployment will start running and observing the logs.

2. CloudFormation Describe Change Set

The first log I captured for you is the one showing what will change, similar to the Terraform plan we saw before. You can see it below.

Cloudformation parameters: {}
> awsv2 cloudformation deploy –stack-name tf-vs-cloudformation –template-file CloudFormationS3.yaml –no-execute-changeset $ENV0_CF_CLI_ARGS_deploy

Waiting for changeset to be created..

Changeset created successfully. Run the following command to review changes:
aws cloudformation describe-change-set –change-set-name arn:aws:cloudformation:us-east-1:706933696988:changeSet/awscli-cloudformation-package-deploy-1707149843/fa8066ab-00ae-4004-af27-419c6eddd1c0

> awsv2 cloudformation describe-change-set –change-set-name arn:aws:cloudformation:us-east-1:706933696988:changeSet/awscli-cloudformation-package-deploy-1707149843/fa8066ab-00ae-4004-af27-419c6eddd1c0
{
“Changes”: [
{
“Type”: “Resource”,
“ResourceChange”: {
“Action”: “Add”,
“LogicalResourceId”: “DemoStorage”,
“ResourceType”: “AWS::S3::Bucket”,
“Scope”: [],
“Details”: []
}
}
],
“ChangeSetName”: “awscli-cloudformation-package-deploy-1707149843”,
“ChangeSetId”: “arn:aws:cloudformation:us-east-1:706933696988:changeSet/awscli-cloudformation-package-deploy-1707149843/fa8066ab-00ae-4004-af27-419c6eddd1c0”,
“StackId”: “arn:aws:cloudformation:us-east-1:706933696988:stack/tf-vs-cloudformation/0b641ca0-c442-11ee-8712-12bde5a0d6ff”,
“StackName”: “tf-vs-cloudformation”,
“Description”: “Created by AWS CLI at 2024-02-05T16:17:23.098906 UTC”,
“Parameters”: null,
“CreationTime”: “2024-02-05T16:17:23.382000+00:00”,
“ExecutionStatus”: “AVAILABLE”,
“Status”: “CREATE_COMPLETE”,
“StatusReason”: null,
“NotificationARNs”: [],
“RollbackConfiguration”: {},
“Capabilities”: [],
“Tags”: null,
“ParentChangeSetId”: null,
“IncludeNestedStacks”: false,
“RootChangeSetId”: null
}

Once you’ve gone through this, you can now accept the changes to move on to the next stage.

3. CloudFormation Deploy

The second log to pay attention to is the actual deployment. Below is what it will look like.

Cloudformation parameters: {}
> awsv2 cloudformation deploy –stack-name tf-vs-cloudformation –template-file CloudFormationS3.yaml $ENV0_CF_CLI_ARGS_deploy

Waiting for changeset to be created..

Waiting for stack create/update to complete

Successfully created/updated stack – tf-vs-cloudformation

The S3 bucket is created similarly to what happened with Terraform. CloudFormation adds some tags to the bucket, as shown in the AWS console Tags section:

Below is a screenshot of the events from the AWS console for the CloudFormation stack:

Finally, you can view the S3 bucket resource created:

4. Destroy the CloudFormation Stack

To destroy the CloudFormation stack, simply click the red Destroy button in env0 inside the environment you would like to destroy.

CloudFormation List Stack Resources

You will see env0 run the following command:

> awsv2 cloudformation list-stack-resources –stack-name env0e0d312 $ENV0_CF_CLI_ARGS_list_stack_resources
{
“StackResourceSummaries”: [
{
“LogicalResourceId”: “DemoStorage”,
“PhysicalResourceId”: “env0-demo-cloudformation-storage”,
“ResourceType”: “AWS::S3::Bucket”,
“LastUpdatedTimestamp”: “2024-02-05T16:48:33.037000+00:00”,
“ResourceStatus”: “CREATE_COMPLETE”,
“DriftInformation”: {
“StackResourceDriftStatus”: “NOT_CHECKED”
}
}
]
}

CloudFormation Delete Stack

Finally, env0 will delete the stack.

> awsv2 cloudformation delete-stack –stack-name env0e0d312 $ENV0_CF_CLI_ARGS_delete_stack
> awsv2 cloudformation wait stack-delete-complete –stack-name env0e0d312

Conclusion

Choosing between Terraform and CloudFormation depends largely on your specific needs and cloud strategy. If your environment spans across multiple cloud providers, Terraform offers the flexibility and ecosystem to support your projects. Conversely, for AWS-centric deployments, CloudFormation’s native integration and managed service benefits are hard to beat.

At env0, we understand that different teams have different preferences and requirements. That’s why the platform is designed to support all IaC frameworks – including both Terraform and CloudFormation, giving you the flexibility to choose the right tool for the job without compromising on functionality or efficiency. 

Whether you’re leaning towards the open-source community of Terraform or the AWS-native capabilities of CloudFormation, env0 facilitates a collaborative and efficient infrastructure management process across your organization.

Frequently Asked Questions

Q: Can Terraform and CloudFormation be used together?

Yes. Although they serve similar purposes, some organizations use both to leverage Terraform’s multi-cloud capabilities and CloudFormation’s deep AWS integration.

Q: Is Terraform more difficult to learn than CloudFormation?

The learning curve for each tool depends on the user’s background. Terraform’s HCL is intuitive for those with coding experience, while CloudFormation’s template-based approach may be simpler for users familiar with JSON or YAML.

Q: How do Terraform and CloudFormation handle state management?

Terraform maintains state files to keep track of resource deployment, while CloudFormation relies on AWS to manage the entire infrastructure and the state of resources.

Q: Are there any costs associated with using Terraform?

While Terraform itself is free, users may incur costs from the cloud resources provisioned through Terraform. Additionally, third-party state backends or enhanced security features may involve extra costs.

Q: How does CloudFormation integrate with other AWS services?

CloudFormation integrates natively with almost all AWS services, allowing users to define a wide range of AWS resources and configurations within its templates.

Leave a Reply

Your email address will not be published. Required fields are marked *