Repository navigation
Add CloudFormation, SAM and CDK to Terraform converter - #32
Merged
Merged
Conversation
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
…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
4 of 5 tasks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What and why
Fixes #9. Adds an AWS → Terraform converter: a
POST /convert/cfn-to-terraformendpoint inconverter-apiand a/cfn-to-terraformpage inweb. It accepts CloudFormation (JSON or YAML), AWS SAM templates and the templatecdk synthwrites. It returns Terraform files plus notes on everything that needs a decision, following the samenotesrule as compose-to-k8s.What it converts
sensitiveforNoEchoandvalidationblocks fromAllowedValues,AllowedPatternand the min/max limits. SSM parameter types become anaws_ssm_parameterlookup.locals.Ref,GetAtt,Sub,Join,Select,Split,If,Equals,And,Or,Not,FindInMap,GetAZs,Base64,Cidr,ImportValueand theLanguageExtensionsfunctions. Pseudo-parameters becomeaws_region/aws_caller_identity/aws_partitiondata sources.Conditionbecomescount,DependsOnbecomesdepends_on,DeletionPolicy: Retainbecomesprevent_destroy.AWS::NoValueis removed the way CloudFormation removes it.imports.tfwithimportblocks, to adopt the resources an existing stack created.Resource coverage
awsprovider mappings. Examples: S3 split into versioning, encryption, lifecycle and the other per-setting resources; IAM inline policies and attachments as separate resources; LambdaZipFilecode througharchive_file; security groups keep the implicit egress rule of CloudFormation.awsccprovider. 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.SAM
Globals.CodeUrifolders are zipped witharchive_file.CDK
api_handlerin place ofApiHandler5E7490E8).cdk.outassets are zipped.autoDeleteObjectsbecomesforce_destroyandlogRetentionbecomes a log group.Web page
awsorawscc), file layout, stack name and import blocks.CONVERSION_NOTES.md._files.html, used by both result fragments (Compose and Terraform).Code structure and house rules
constants.py, dataclasses inmodels.py, errors inerrors.py. Each hand-written mapping is aResourceConvertersubclass (resources/base.py) listed inresources/registry.py. SAM, CDK, Compose and render code are classes; YAML limits live inyaml_safety.py; request models inschemas.py.*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 outsidetests/.scripts/check_code_rules.pyruns inmake lintand 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 anddocs/.Design decisions to review
aws ~> 6.40, because DynamoDBkey_schemablocks need 6.30 or later. Terraform must be 1.5 or later forimportblocks.webwas raised to match. A 490 KB template converts in about 0.4 s using about 50 MB.How it was tested
Commands
make lint: ruff plusscripts/check_code_rules.pyon the whole repo.make test:converter-api509 tests,web82 tests, both at 100% coverage.make validate-terraform, the CI jobvalidate-terraform:scripts/validate-terraform.shconverts the 10 CloudFormation, SAM and CDK test templates inservices/converter-api/tests/fixtures/cfn/with theawsand theawsccprovider, then runsterraform fmt -checkandterraform validateon each. Warnings count as failures. All 20 runs pass (Terraform 1.17.2, aws 6.73, awscc 1.110).{name}).buildande2eCI jobs also run a CloudFormation conversion through the UI.Code review
Three independent reviewers went over the change. They reproduced issues with
terraform validateandplan; those issues are fixed with regression tests. The most important:DefinitionUrivalues could inject Terraform, includinglocal-exec.Fn::Cidrcounts plus several quadratic paths, including the regex CodeQL flagged innaming.py(now a linear scan).Join/Subpieces.Fn::Equalsagainst numbers and booleans gave conditions that were always false.AWS::NoValuein lists becamenullelements.Example (
curl localhost:8000/convert/cfn-to-terraform):Docker builds ran in the
buildande2eCI jobs; this environment has no Docker daemon. Locally, both apps import from exactly the files their Dockerfiles copy (converter-apinow also copiesschemas.py;webcopies*.pyandroutes/).Known limitations (documented in
docs/reference/cloudformation-to-terraform.md):!Ifchoosing between two whole lists of nested blocks is reported in the notes.Refto a Number parameter stays a number.Checklist
make lint testpasses (coverage stays at or above 95%)make validate-k8spasses, if anything ink8s/changed (k8s/is unchanged)docs/reference/api.md, the newdocs/reference/cloudformation-to-terraform.md, the roadmap, the architecture doc and the CI/CD doc🤖 Generated with Claude Code
https://claude.ai/code/session_01SmQPLQt2JAPt6J9EAPNF5F