DEV Community

Python-T Point
Python-T Point

Posted on • Originally published at pythontpoint.in

☁️ Terraform vs CloudFormation for Lambda deployments — which one should you use?

Terraform provides predictable serverless pipelines by isolating drift, enforcing versioned state, and integrating directly with CI/CD. The following sections dissect the mechanisms of Terraform , CloudFormation , and AWS Lambda when you compare terraform vs cloudformation for lambda deployments across real‑world workflows.

📑 Table of Contents

  • 🚀 Architecture — How Lambda Deployments Work
  • 🛠 Terraform — Managing Serverless Resources Declaratively
  • 🔧 Example Terraform Configuration
  • 📦 CloudFormation — AWS‑Native Stacks
  • 🔧 Example CloudFormation Template
  • ⚖️ Comparison — Terraform vs CloudFormation for Lambda Deployments
  • 🟩 Final Thoughts
  • ❓ Frequently Asked Questions
  • Can I import an existing Lambda function into Terraform?
  • How does CloudFormation handle updates to function code without redeploying the whole stack?
  • Is it possible to store Terraform state in S3 with encryption?
  • 📚 References & Further Reading

🚀 Architecture — How Lambda Deployments Work

A Lambda deployment consists of packaging code, defining an execution role, and creating a function resource. The service stores the code in an S3 bucket, copies it into a sandboxed container, and attaches the role for permissions.

When a deployment request arrives, the Lambda service performs these steps:

  • Validate the ZIP payload against the runtime’s checksum (SHA‑256).
  • Allocate an execution environment in a sandboxed container, pulling the runtime from Amazon’s internal image store.
  • Mount the role’s policies and configure the handler entry point.

Both Terraform and CloudFormation ultimately invoke the same AWS APIs, but they differ in how they orchestrate these calls.

Key point: Understanding the Lambda lifecycle reveals where IaC tools intervene—during resource creation, update, and drift detection.


🛠 Terraform — Managing Serverless Resources Declaratively

Terraform stores a JSON state file that records the exact attribute values of every managed resource. During a plan operation the provider SDK compares the desired configuration with the recorded state, producing a diff that lists the required API calls without touching the live environment.

🔧 Example Terraform Configuration

resource "aws_iam_role" "lambda_exec" { name = "lambda_exec_role" assume_role_policy = jsonencode({ Version = "2012-10-17" Statement = [{ Action = "sts:AssumeRole" Effect = "Allow" Principal = { Service = "lambda.amazonaws.com" } }] })
} resource "aws_lambda_function" "my_func" { function_name = "my-function" role = aws_iam_role.lambda_exec.arn handler = "app.handler" runtime = "python3.9" filename = "lambda_package.zip"
}
Enter fullscreen mode Exit fullscreen mode

The terraform plan command computes the necessary API calls without applying them.

$ terraform plan
Refreshing Terraform state in-memory...
No changes. Your infrastructure matches the configuration.
Enter fullscreen mode Exit fullscreen mode

Running terraform apply sends a CreateFunction request to the Lambda API, then writes the response—including the function’s ARN—into the state file. (Also read: ☁️ Azure Cosmos DB vs MongoDB for FastAPI — Which One Should You Use?)

$ terraform apply -auto-approve
aws_iam_role.lambda_exec: Creating...
aws_lambda_function.my_func: Creating...
aws_lambda_function.my_func: Creation complete after 2s [id=my-function]
aws_iam_role.lambda_exec: Creation complete after 1s [id=lambda_exec_role]
Enter fullscreen mode Exit fullscreen mode

Because the state file is version‑controlled, rolling back is as simple as checking out a previous commit and re‑applying. Terraform will issue an UpdateFunctionCode call if the ZIP hash differs, ensuring the live function matches the recorded version.

Key point: Terraform’s immutable state model prevents accidental drift, making repeated terraform vs cloudformation for lambda deployments comparisons reliable. (Also read: 📦 Docker vs Podman comparison — which one should you)


📦 CloudFormation — AWS‑Native Stacks

CloudFormation treats a stack as a single unit of work. The template is stored in S3, and resource versions are tracked via change sets, which describe the exact API calls required for an update. (Also read: 💡 MySQL INNER JOIN vs LEFT JOIN — which one should you actually use?)

🔧 Example CloudFormation Template

AWSTemplateFormatVersion: '2010-09-09'
Resources: LambdaExecutionRole: Type: AWS::IAM::Role Properties: RoleName: lambda_exec_role AssumeRolePolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Principal: Service: [lambda.amazonaws.com] Action: ['sts:AssumeRole'] MyFunction: Type: AWS::Lambda::Function Properties: FunctionName: my-function Role:!GetAtt LambdaExecutionRole.Arn Handler: app.handler Runtime: python3.9 Code: ZipFile: | import json def handler(event, context): return {"statusCode": 200, "body": json.dumps("hello")}
Enter fullscreen mode Exit fullscreen mode

Deploying the stack with the AWS CLI creates a change set that lists the required API calls.

$ aws cloudformation deploy -template-file lambda.yml -stack-name my-stack
Waiting for changeset to be created..
Successfully created/updated stack - my-stack
Enter fullscreen mode Exit fullscreen mode

Generating a change set without applying it lets you inspect pending modifications:

$ aws cloudformation create-change-set -stack-name my-stack -template-body file://lambda.yml -change-set-name preview
{ "Id": "arn:aws:cloudformation:us-east-1:123456789012:changeSet/preview/abcd1234", "StackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/my-stack/efgh5678"
}
$ aws cloudformation describe-change-set -change-set-name preview -stack-name my-stack
{ "Changes": [ { "ResourceChange": { "Action": "Modify", "LogicalResourceId": "MyFunction", "PhysicalResourceId": "my-function", "Replacement": "False", "Details": [...] } } ]
}
Enter fullscreen mode Exit fullscreen mode

According to the AWS CloudFormation documentation, change sets allow you to preview modifications before they affect the live stack, reducing accidental outages.

Key point: CloudFormation’s change‑set model provides a built‑in review step, but it lacks the explicit state file that Terraform maintains. (More onPythonTPoint tutorials)


⚖️ Comparison — Terraform vs CloudFormation for Lambda Deployments

This section evaluates the two IaC tools against common criteria for serverless workloads.

Criterion Terraform CloudFormation
State Management Explicit JSON state file (local or remote); drift detection via terraform plan Implicit state stored in AWS; drift detection via detect-stack-drift
Multi‑cloud Support Provider ecosystem covers AWS, Azure, GCP, and more AWS‑only; no cross‑cloud abstraction
CLI Experience Unified binary; commands plan, apply, destroy AWS CLI or console; separate deploy and change-set steps
Modularization Modules with inputs/outputs, reusable across providers Nested stacks; limited reusability outside CloudFormation
Drift Handling Detects drift during plan and can reconcile automatically Requires explicit detect-stack-drift call; may miss subtle changes

Both tools ultimately call the same AWS APIs. Terraform’s explicit state and provider model give tighter control over versioning and rollback, while CloudFormation offers native integration with AWS services and automatic handling of resource dependencies.

Choosing the right IaC engine for Lambda is less about feature parity and more about the workflow guarantees you need.

Key point: In a strict CI/CD pipeline where reproducibility matters, Terraform often edges out CloudFormation for terraform vs cloudformation for lambda deployments.


🟩 Final Thoughts

When you evaluate terraform vs cloudformation for lambda deployments , focus on the guarantees each platform provides around state, drift, and multi‑cloud flexibility. Terraform’s immutable state and provider ecosystem make it a strong candidate for teams that already manage heterogeneous resources, while CloudFormation’s deep AWS integration can simplify pure‑AWS stacks that rely on native change‑set reviews.

Adopting one tool does not preclude using the other. Hybrid approaches let you leverage CloudFormation for core AWS resources and Terraform for cross‑cloud components, preserving the best of both worlds.


❓ Frequently Asked Questions

Can I import an existing Lambda function into Terraform?

Yes. Use terraform import aws_lambda_function.my_func arn:aws:lambda:region:account-id:function:my-function, then run terraform plan to generate the corresponding configuration.

How does CloudFormation handle updates to function code without redeploying the whole stack?

Update the Code property in the template and create a change set; the stack update will issue an UpdateFunctionCode API call while leaving other resources untouched.

Is it possible to store Terraform state in S3 with encryption?

Configure a backend block pointing to an S3 bucket with server‑side encryption enabled; Terraform will read and write the state file securely.


📚 References & Further Reading

Top comments (0)