Skip to content

nf convert

Convert a Terraform module into typed Netherframe Python.

Synopsis

nf convert MODULE_DIR [--output DIR] [--package NAME] [--generic] [--force] [--no-format] [--report FILE]
Option Meaning
-o, --output DIR Directory to write the package into (default: the current directory)
--package NAME Python package name (default: the module directory's name)
--generic Write generic Resource(nf_type=...) constructs even where generated bindings are installed
--force Replace the package directory if it exists (otherwise the command refuses)
--no-format Do not format the written code with Ruff
--report FILE Also write the conversion report to FILE
--fetch-modules Download public registry modules, GitHub sources and HTTP(S) archives for conversion; no Terraform or git executable is needed
--module-cache DIR Download cache (default ~/.cache/netherframe/modules); use a fresh cache to refresh an unpinned source

What It Does

nf convert reads the module's .tf and .tf.json files, and those of every local module it calls (source = "./..." or "../..."), and writes a Python package:

<output>/<package>/
  __init__.py          # re-exports the stack class
  main.py              # the root module: a Stack subclass
  modules/<name>.py    # a class per local module
  _support.py          # small helpers, when the code needs them

With --fetch-modules, remote modules are converted recursively too. Public registry version constraints and GitHub ?ref= pins are supported, as are archive subdirectories (//modules/x). Use pinned versions or revisions for reproducible conversions. Without this flag, remote calls keep their existing TODO markers. Private registries and arbitrary Git transports are not fetched.

It converts the mechanical part of a migration and marks the rest: whatever it cannot convert keeps its original HCL in a # TODO(nf convert): ... comment, and the written package still imports and builds an app. The command prints a report of what it converted and every TODO marker with its file and line:

nf convert: Terraform module network -> Python package network

Converted:
  root module -> network.main.NetworkStack
    variables: 7, locals: 3, providers: 2, resources: 5, data sources: 1, module calls: 1, module calls (not converted): 1, outputs: 7
    constructs: 7 typed (generated bindings), 1 generic (acme_widget: no generated binding installed)
  module modules/edge -> network.modules.edge.EdgeModule
    variables: 2, resources: 1, outputs: 1
    constructs: 1 typed (generated bindings), 0 generic

TODO markers (3):
  main.tf:102: acme_widget.probe: provisioner "local-exec" is not converted (run it as a netherframe runtime function or outside the stack)
  main.tf:116: module.vpc: a registry or remote module is not converted (source terraform-aws-modules/vpc/aws, version 5.8.1)
  outputs.tf:24: output vpc_id: refers to vpc, a module that is not converted

Review the TODO markers like code review comments, then run the stack the usual way.

Adoption Manifest

Besides the package, the command writes <package>.adopt.json next to it: an adoption manifest mapping each converted resource's netherframe address to its address in Terraform's state. The converter renames addresses (a count or for_each instance key joins the name, aws_instance.web[0] becomes web_0; a local module's resources get the call's name first, module.edge.aws_vpc.main becomes edge_main), and records each rename; loops become adopt_patterns ([*] for an instance key). A key with characters a name cannot hold (anything but letters, digits, _ and -) joins it with each run of them as _ and the start of the key's SHA-256 digest after it: aws_route53_zone.zone["example.com"] becomes zone_example_com_a379a6f6, so keys that read alike (a.b, a_b) stay apart. The generated code names instances with the same function (netherframe.core.values.address.instance_name) the manifest's patterns resolve keys with. Migrating a module whose objects exist is then:

nf convert ./network --output ./converted
nf plan --adopt-from converted/network.adopt.json --terraform-state ./network/terraform.tfstate
nf apply --adopt-from converted/network.adopt.json --terraform-state ./network/terraform.tfstate

The plan shows every object of the Terraform state as an import, with any difference between the converted code and the object.

How Terraform Maps To Python

Terraform Python
root module class <Package>Stack(Stack), built with NetworkStack(nf_scope=app, name="demo")
variable a keyword argument, typed from type (list(string) is list[str]), with its default; a static validation becomes a check raising ValueError
locals Python local variables, ordered so each comes after what it uses
provider the generated provider class (AwsProvider(...)); alias becomes nf_provider_settings=ProviderSettings(alias=...)
resource, data, ephemeral the generated class (Vpc, AmiDataSource), stored as a stack attribute (self.vpc_main) with nf_id set to the resource name
nested blocks the class's block classes (Network.Subnet(...)); dynamic blocks become list comprehensions
count / for_each a Python loop filling a list or dict (keyed by the Terraform key), each nf_id suffixed with the index or key (web_0, zonal_a; zone_example_com_a379a6f6 for example.com, see above)
depends_on, lifecycle, provider the depends_on=, lifecycle=LifecycleRules(...) and nf_provider= arguments
output Output(nf_scope=self, nf_id=..., value=...) in the root module, an attribute of a local module's object
local module self.edge = EdgeModule(self, nf_prefix="edge_", ...): its constructs go into the caller's stack, nf_id prefixed with the module name; module.edge.x is self.edge.x

Explicit depends_on references to converted local modules expand to their resources and data sources, including nested modules. A module call's depends_on applies to every construct it creates. Whole count and for_each collections and selected instances are supported; an empty module or collection retains its explicit prerequisites.

Local modules inherit default provider configurations from their caller. An explicit providers = { aws = aws.west, aws.other = aws.east } map is passed to the module and its resources; nested calls inherit their parent's mapped defaults. Aliases are passed explicitly.

Generated helpers, import aliases and module bookkeeping use the reserved _nf_ prefix. Terraform names starting with _nf_ become user_nf_... in Python; other names are disambiguated when necessary. The generated module classes track their constructs explicitly.

Constructs get the names Terraform gives them: aws_vpc.main is synthesized as aws_vpc.main, an instance aws_instance.web[0] as aws_instance.web_0, and a module's resource module.edge.aws_vpc.this as aws_vpc.edge_this. Moving existing state to the converted stack needs those renames (see nf state).

Typed bindings and generic constructs

A type whose provider package is installed (netherframe.providers.hashicorp.aws for aws_*, or the source in required_providers) converts to its generated class, with the argument names the generator gives (type is type_, filter blocks are FilterBlock) and typed references (vpc.ref_id_). Other types convert to Resource(nf_type="...", ...) with dict blocks. Generate the missing provider packages with nf generate providers and convert again to get typed code.

Expressions

A value Python knows while building the stack (a variable, a local computed from variables, count.index, each.key) is translated to plain Python: "${var.name}-${each.key}" is f"{name}-{key}", upper(var.env) is env.upper(), merge(var.tags, {...}) is {**tags, ...}, var.enabled ? 2 : 0 is 2 if enabled else 0. A value only known at apply time (a resource attribute) becomes a runtime value: aws_vpc.main.id is self.vpc_main.ref_id_, an interpolation of it an f-string, a comparison x.eq(...), a conditional Fn.conditional(...), and Terraform functions without a Python equivalent Fn.<name>(...) calls of the function catalog.

Build-time tostring(...) uses a helper in the generated package: booleans become "true" or "false", null stays null, strings keep their case, and numbers use decimal notation. Collections are rejected instead of being converted to Python representations. Runtime values still use Fn.tostring(...). This follows Terraform's tostring scalar conversions.

count and for_each must be Python values (Terraform requires them known at plan time too). When they depend on a resource attribute or a data source, the loop gets a TODO marker.

Collection for expressions over runtime values use expression nodes that render Terraform comprehensions and evaluate against provider state in hybrid runs. Filters and grouped object results are supported. try and can evaluate their arguments lazily; an unknown first value stays unknown. Nested %{ if ... } and %{ for ... } template directives support whitespace strip markers and escaped directive openers.

TODO Markers

Each marker names what was not converted and quotes the HCL. The usual ones:

Marker What to do
provisioner "..." is not converted Run the command as a runtime function or outside the stack
a registry or remote module is not converted (source ..., version ...) Port the module (or the resources it creates) by hand; the call is kept as UnconvertedModule(...) with its arguments
refers to X, a module that is not converted The expression is kept as a Terraform string ("${module.vpc.vpc_id}"); replace it once the module is ported
validation is not converted A validation that is not a Python condition (can(regex(...))): write the check in Python
count / for_each is not known before apply here Compute the collection in Python (a variable, a data lookup done before building)
depends_on a module that is not converted Port the remote module and depend on its constructs
depends_on is not converted for an unconverted module Port the remote module and apply the dependency to its constructs
terraform backend is not converted Configure state with a Netherframe backend
moved / import / removed / check blocks Use move_from / import_from on the construct, or drop them

An expression with a TODO marker is kept as the Terraform expression it was ("${try(var.settings.ami, \"ami-1\")}"), so the package still builds; the reference only resolves where Terraform would resolve it.

Example

nf convert infra/network --output src --package network

Save the following as src/app.py next to the generated network package. Adjust the constructor arguments to match the original module's variables.

from nf.core import App

from network import NetworkStack

app = App(nf_id="app")
NetworkStack(nf_scope=app, nf_id="network", name="demo", environment="prod")
app.synth()

Run uv run python src/app.py from the project root to inspect the converted stack's synthesized configuration.