Skip to content

Add CloudFormation, SAM and CDK to Terraform converter - #32

Merged
zainsohail88 merged 4 commits into
mainfrom
feature/cfn-to-terraform
Nov 21, 2026
Merged

zainsohail88 merged 4 commits into
mainfrom
feature/cfn-to-terraform

Conversation

@zainsohail88

@zainsohail88 zainsohail88 commented Nov 20, 2026 •

Copy link
Copy Markdown
Owner

What and why

Fixes #9. Adds an AWS → Terraform converter: a POST /convert/cfn-to-terraform endpoint in converter-api and a /cfn-to-terraform page in web. It accepts CloudFormation (JSON or YAML), AWS SAM templates and the template cdk synth writes. It returns Terraform files plus notes on everything that needs a decision, following the same notes rule as compose-to-k8s.

What it converts

  • Parameters → variables: types, defaults, sensitive for NoEcho and validation blocks from AllowedValues, AllowedPattern and the min/max limits. SSM parameter types become an aws_ssm_parameter lookup.
  • Mappings and conditions → locals.
  • Intrinsics → Terraform expressions: Ref, GetAtt, Sub, Join, Select, Split, If, Equals, And, Or, Not, FindInMap, GetAZs, Base64, Cidr, ImportValue and the LanguageExtensions functions. Pseudo-parameters become aws_region / aws_caller_identity / aws_partition data sources.
  • Resource attributes: Condition becomes count, DependsOn becomes depends_on, DeletionPolicy: Retain becomes prevent_destroy. AWS::NoValue is removed the way CloudFormation removes it.
  • Optional imports.tf with import blocks, to adopt the resources an existing stack created.

Resource coverage

  • 85 common types have hand-written aws provider mappings. Examples: S3 split into versioning, encryption, lifecycle and the other per-setting resources; IAM inline policies and attachments as separate resources; Lambda ZipFile code through archive_file; security groups keep the implicit egress rule of CloudFormation.
  • Every other type (1,713 in total) uses the awscc provider. An index generated from the provider schema (python -m tools.build_awscc_index) gives exact attribute names, map and JSON properties and the properties this provider version lacks.
  • Anything without an exact equivalent stays in the output as a comment and is listed in the notes.

SAM

  • Expanded the way the SAM transform does it, keeping the SAM logical IDs.
  • Covers roles and policy templates, all common event types, the implicit REST and HTTP APIs with generated OpenAPI bodies, aliases, function URLs, SimpleTable, LayerVersion, StateMachine, Connectors and Globals.
  • Local CodeUri folders are zipped with archive_file.

CDK

  • CDK bookkeeping is removed.
  • Terraform names come from construct paths (api_handler in place of ApiHandler5E7490E8).
  • cdk.out assets are zipped.
  • autoDeleteObjects becomes force_destroy and logRetention becomes a log group.

Web page

  • CloudFormation, SAM and CDK examples, plus upload or drag-and-drop.
  • Options: provider (aws or awscc), file layout, stack name and import blocks.
  • Results: a summary of the detected source and resource counts, file tabs with HCL highlighting (a new mode in the CodeMirror bundle), a table showing where each resource went, the notes and a zip download that includes CONVERSION_NOTES.md.
  • The file browser is now a shared _files.html, used by both result fragments (Compose and Terraform).

Code structure and house rules

  • Every module has one concern: constants in constants.py, dataclasses in models.py, errors in errors.py. Each hand-written mapping is a ResourceConverter subclass (resources/base.py) listed in resources/registry.py. SAM, CDK, Compose and render code are classes; YAML limits live in yaml_safety.py; request models in schemas.py.
  • The web service is split into one router per page plus settings, messages, inputs, conversions, rendering, middleware and error pages.
  • No nested functions, no lambdas, no * or ** syntax, imports at the top only and no checker silencers (noqa, type: ignore, pragma: no cover). Docstrings and return types on every class and function outside tests/.
  • Enforced in CI: scripts/check_code_rules.py runs in make lint and the CI lint job. It checks those code rules on every Python file plus the writing rules (no apostrophes, no comma before and/or, no em dashes) on the README, CONTRIBUTING, SECURITY and docs/.

Design decisions to review

  • Provider pins in the generated code: aws ~> 6.40, because DynamoDB key_schema blocks need 6.30 or later. Terraform must be 1.5 or later for import blocks.
  • Input limits for templates are larger than for compose files: 500,000 characters and 100,000 values. The body limit of web was raised to match. A 490 KB template converts in about 0.4 s using about 50 MB.
  • Names: logical IDs and other template names must be alphanumeric, the rule CloudFormation itself applies. Enforcing it also prevents HCL injection.

How it was tested

Commands

  • make lint: ruff plus scripts/check_code_rules.py on the whole repo.
  • make test: converter-api 509 tests, web 82 tests, both at 100% coverage.
  • make validate-terraform, the CI job validate-terraform: scripts/validate-terraform.sh converts the 10 CloudFormation, SAM and CDK test templates in services/converter-api/tests/fixtures/cfn/ with the aws and the awscc provider, then runs terraform fmt -check and terraform validate on each. Warnings count as failures. All 20 runs pass (Terraform 1.17.2, aws 6.73, awscc 1.110).
  • The restructure keeps the generated Terraform the same: every conversion the tests make was recorded on the old code and replayed on the new code. The only differences are reworded notes and one fix (the Compose depends_on note printed a literal {name}).
  • The three built-in examples convert and validate.
  • The page was checked in Chromium at desktop and phone widths, light and dark, with no console errors and no horizontal overflow.
  • The build and e2e CI jobs also run a CloudFormation conversion through the UI.

Code review
Three independent reviewers went over the change. They reproduced issues with terraform validate and plan; those issues are fixed with regression tests. The most important:

  • HCL injection: crafted logical IDs or SAM DefinitionUri values could inject Terraform, including local-exec.
  • Denial of service: Fn::Cidr counts plus several quadratic paths, including the regex CodeQL flagged in naming.py (now a linear scan).
  • Template-string escaping across Join/Sub pieces.
  • Fn::Equals against numbers and booleans gave conditions that were always false.
  • AWS::NoValue in lists became null elements.
  • Wrong defaults: ECS desired count, RDS apply-immediately, ALB stickiness and health-check thresholds, CloudFront HTTP version.
  • Aurora member instances were mapped to the wrong resource type.

Example (curl localhost:8000/convert/cfn-to-terraform):

Resources:
  Logs:
    Type: AWS::S3::Bucket
    Properties:
      VersioningConfiguration:
        Status: Enabled
resource "aws_s3_bucket" "logs" {}

resource "aws_s3_bucket_versioning" "logs_versioning" {
  bucket = aws_s3_bucket.logs.id
  versioning_configuration {
    status = "Enabled"
  }
}

Docker builds ran in the build and e2e CI jobs; this environment has no Docker daemon. Locally, both apps import from exactly the files their Dockerfiles copy (converter-api now also copies schemas.py; web copies *.py and routes/).

Known limitations (documented in docs/reference/cloudformation-to-terraform.md):

  • An !If choosing between two whole lists of nested blocks is reported in the notes.
  • An ECS environment value given as a Ref to a Number parameter stays a number.

Checklist

  • make lint test passes (coverage stays at or above 95%)
  • make validate-k8s passes, if anything in k8s/ changed (k8s/ is unchanged)
  • New behaviour has tests, including error cases
  • README / CONTRIBUTING updated, if endpoints or conversion rules changed. Also updated: docs/reference/api.md, the new docs/reference/cloudformation-to-terraform.md, the roadmap, the architecture doc and the CI/CD doc
  • No secrets, tokens or personal data added

🤖 Generated with Claude Code

https://claude.ai/code/session_01SmQPLQt2JAPt6J9EAPNF5F

New converter-api endpoint POST /convert/cfn-to-terraform and web page
/cfn-to-terraform. Templates (JSON or YAML) become Terraform files:
parameters to variables with validation, mappings and conditions to
locals, intrinsic functions to expressions, outputs, and optional import
blocks for adopting an existing stack.

- 85 common types have hand-written aws provider mappings; every other
  type uses the awscc provider through an index built from its schema
- AWS SAM resources are expanded the way the SAM transform does it
  (roles, events, APIs, policy templates, connectors, Globals)
- CDK templates: bookkeeping removed, construct-path names, cdk.out
  assets zipped with archive_file, common CDK custom resources replaced
- Anything without an exact equivalent is kept as a comment and noted
- CI converts every fixture with both providers and runs
  terraform fmt -check and terraform validate

Fixes #9

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SmQPLQt2JAPt6J9EAPNF5F
Security and limits:
- Reject logical IDs and other names that aren't alphanumeric (as
  CloudFormation does) and escape SAM DefinitionUri paths and generated
  names, so template text can never inject HCL
- Cap Fn::Cidr at 256 blocks, reject non-finite numbers, and make name
  de-duplication, SAM policy de-duplication and CDK clean-up linear

Expressions:
- Template strings escape literal runs as a whole, so text split across
  Join/Sub pieces can't form an interpolation
- Fn::Equals compares as text; Fn::Cidr works for IPv6 blocks
- AWS::NoValue is removed from lists, mappings and joins, and optional
  list items become counted resources
- Fn::If with differently shaped branches works inside JSON documents
- Extra resources can no longer collide with converted ones; outputs
  using a condition built from a NoEcho parameter are sensitive

SAM: VPC functions get AWSLambdaVPCAccessExecutionRole, implicit APIs
use Globals, and ${Api.Stage} in Fn::Sub points at the stage.

Mappings: ECS desired count defaults to 1, RDS names are lowercased,
Aurora members become aws_rds_cluster_instance, RDS applies changes
immediately, target group stickiness and health check defaults match
AWS, CloudFront defaults to HTTP/1.1, and many Fn::If shapes that used
to crash or produce invalid output are converted or reported.

Editor: the HCL highlighter tracks strings and braces inside ${...}.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SmQPLQt2JAPt6J9EAPNF5F
zainsohail88 and others added 2 commits November 21, 2026 13:55
…g rules in CI

- Split the cfn package by concern: constants, models, errors, expressions,
  pipeline, resources/base and resources/registry. Every hand-written mapping is
  a ResourceConverter subclass listed in its module CONVERTERS tuple.
- SAM, CDK, Compose and render code is now classes; YAML limits live in
  yaml_safety.py; request models in schemas.py.
- Split the web service into routes, settings, messages, inputs, conversions,
  rendering, middleware and error pages.
- Remove every nested function, lambda, star unpacking, late import and checker
  silencer. Add docstrings and return types throughout.
- Add scripts/check_code_rules.py (code rules plus writing rules for the docs) and
  run it in make lint and the CI lint job.
- Replace tools/validate_terraform.py with tools/convert_fixtures.py and
  scripts/validate-terraform.sh.
- Replace the regex flagged by CodeQL in naming.identifier with a linear scan.
- Rewrite docs and user-facing text: no apostrophes, no comma before and/or,
  roadmap without numbering.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SmQPLQt2JAPt6J9EAPNF5F
@zainsohail88
zainsohail88 added this pull request to stack #36 November 21, 2026 16:23
@zainsohail88
zainsohail88 merged commit 8738991 into main Nov 21, 2026
11 checks passed
@zainsohail88
zainsohail88 deleted the feature/cfn-to-terraform branch November 21, 2026 17:49
@github-project-automation github-project-automation Bot moved this from Backlog to Done in DevToolkit Roadmap Nov 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

AWS → Terraform converter (CloudFormation, SAM, CDK)

3 participants