Skip to content

How to Import (Adopt) Existing Resources

In hybrid execution, importing an existing cloud or service object is called adoption and happens as a reviewed import action inside nf plan and nf apply—never as a blind out-of-band state edit.

Planning performs read-only provider lookups, shows every import alongside any update or replacement your Python code would trigger on top of it, and writes nothing until you review and apply the plan.

Using a legacy synthesized Terraform stack? Use nf import instead. For hybrid apps (the default), use one of the adoption methods below.


Choose your import method

Situation Recommended method Requires editing code?
Import one or a few resources whose provider IDs you know .import_from("vpc-0abc123") Temporarily (remove after apply)
Import resources identifiable from their config (bucket name, log group) LifecycleRules(adopt="required") or adopt=True Yes (safe to keep or remove)
Bulk import or migrate a Terraform state without touching Python --adopt-from manifest.json (+ --terraform-state) No
Adopt an object created automatically by another resource in the same apply .import_from(parent.output.default_id) Yes
Direct single-resource state import on PostgreSQL graph state nf state import ADDRESS [IMPORT_ID] [--identity JSON] No

Practical step-by-step workflow

Follow this sequence whenever you bring live infrastructure under Netherframe management:

  1. Declare the resource in Python with a stable nf_id and provider configuration pointing at the target account/region.
  2. Find the exact import ID or identity shape expected by the provider (for example, a VPC ID vpc-0abc123, a bucket name acme-logs, or a composite key such as <realm>/<scope_id>). Check the provider's documentation, nf providers describe, or run nf discover resources where supported.
  3. Request adoption using .import_from(...), LifecycleRules(adopt=...), or an --adopt-from manifest (details below).
  4. Save and inspect a plan with --diff and --adopt-missing error:
nf plan --app my_app --diff --adopt-missing error --out import-plan.json

Review two things carefully before applying: - Every target appears under Imports (not + create). - Any ~ update or ± replace listed on an imported object is intentional. If you see an unexpected diff—especially a replacement—adjust your Python arguments to match the live object and re-plan until the import is clean. 5. Apply the reviewed plan:

nf apply --app my_app --plan-file import-plan.json

In CI or unattended runs with --auto-approve, pass --approve-imports explicitly; --auto-approve alone refuses any plan containing imports. 6. Verify convergence and clean up:

nf plan --app my_app

Once the object is in state, the next plan should report no changes. Remove one-off .import_from(...) calls from Python (or stop passing --adopt-from)—Netherframe warns when a leftover import_from is no longer needed.


Asking for adoption

There are three ways to tell Netherframe which live object a resource construct represents.

1. By literal import ID (.import_from)

Attach .import_from(id) directly to the construct (substitute your real VPC ID):

from nf.core import App, Stack
from nf.providers.hashicorp.aws import AwsProvider, Vpc

with App() as app, Stack(nf_id="network"):
    AwsProvider(nf_id="aws", region="us-east-1")
    Vpc(nf_id="main", cidr_block="10.0.0.0/16").import_from("vpc-0abc123")

2. By resource identity (LifecycleRules(adopt=...))

When the provider publishes a resource identity schema (such as bucket for aws_s3_bucket or name for aws_cloudwatch_log_group), Netherframe can derive the identity directly from your resource arguments (providers without identity schemas use nf.drift.import_id_resolvers plugins):

from nf.core import App, LifecycleRules, Stack
from nf.providers.hashicorp.aws import AwsProvider, S3Bucket

with App() as app, Stack(nf_id="network"):
    AwsProvider(nf_id="aws", region="us-east-1")
    S3Bucket(nf_id="logs", bucket="acme-logs", lifecycle=LifecycleRules(adopt="required"))
  • adopt=True imports the object if found, or plans a create if it does not exist.
  • adopt="required" makes a missing object a plan error (safer when you expect the object to exist already).

See examples/aws_adopt_existing/ for a complete runnable app.

3. By an adoption manifest (--adopt-from)

Pass a JSON manifest to nf plan and nf apply to import many objects—or migrate from a Terraform state file—without editing your Python source:

nf plan --app network --adopt-from network.adopt.json --out import-plan.json
nf apply --app network --plan-file import-plan.json
{
  "format_version": 1,
  "terraform_state": "terraform.tfstate",
  "stack_map": {
    "generated_stack": "network"
  },
  "adopt": {
    "network.aws_vpc.main": {"import_id": "vpc-0abc123"},
    "network.aws_s3_bucket.logs": {"identity": {"bucket": "acme-logs"}, "required": true},
    "network.aws_instance.web_0": {"terraform_address": "aws_instance.web[0]"}
  },
  "adopt_patterns": [
    {"address": "network.aws_instance.replica_{0}", "terraform_address": "aws_instance.replica[*]"}
  ]
}

Manifest rules:

  • Keys are Netherframe addresses (<stack>.<type>.<nf_id>). A manifest entry overrides any adoption request on the construct itself, and an entry naming a resource the app does not declare is rejected.
  • import_id calls ImportResourceState + ReadResource.
  • identity looks up the object via the provider's resource identity schema.
  • terraform_address reads the object from terraform_state (relative to the manifest, or overridden with --terraform-state), preserving attributes, private data, and identity, upgrading to the provider's schema, and refreshing via ReadResource without calling ImportResourceState.
  • adopt_patterns expands every matching instance key ([*]) into {0}, {1}, ... using the same instance-naming normalization as nf convert ("example.com" becomes example_com_a379a6f6; keys of letters, digits, _, and - stay unchanged).
  • stack_map remaps generated stack names when you instantiate a converted stack under a different nf_id (applies to both adopt and adopt_patterns; duplicate destinations are rejected).
  • "required": true makes a missing object a plan error per entry.

nf convert and nf discover codify generate these manifests automatically beside the Python code they emit.


What the plan shows

Plan Summary:
  2 to import
  0 to create
  1 to update
  ...
Imports (2 existing objects adopted into state; auto-approve does not approve them without --approve-imports):
  network.aws_vpc.main <- import ID vpc-0abc123
  network.aws_s3_bucket.logs <- identity {"bucket": "acme-logs"} (and update)
  • Pure import: Live attributes match your Python configuration; apply records the object in state without mutating cloud infrastructure. Runtime checks on pure imports run during planning with the imported state as their planned state.
  • Import + update / replace: Live attributes differ from your Python configuration; apply imports the object and then applies the reviewed change.
  • Not found to adopt: Listed separately and planned as creates unless adopt_missing="error" or adopt="required".
  • Saved plans and rollback: nf plan --out freezes all import actions and policies. If an apply fails under recovery_strategy="ROLLBACK", Netherframe removes newly imported entries from state without deleting the underlying live cloud objects (completed updates to imported objects cannot be reverted and are reported).

When the provider is deferred

If a provider's configuration depends on resources created in the same run (for example, configuring a Kubernetes provider from a new EKS cluster), adoption requests on that provider are deferred with its resources rather than calling an unconfigured provider or guessing a create.

Once prerequisites finish, the deferred round performs the read-only lookup and plans an import, update, or replace against the found object:

  • Interactive runs follow deferred_approval (default each_round, showing and approving each deferred round separately; with once, the initial approval lists the deferred adoption requests and covers later rounds).
  • Unattended runs (--auto-approve or saved plans) require both --apply-deferred and --approve-imports. Without import approval, the run stops before changing anything—even before prerequisites—when a deferred lookup may adopt an object.
  • Saved plans retain deferred lookup requests, policies, and any referenced Terraform-state snapshots (including private data and identity), so protect saved plan files as you protect state files.

Import IDs discovered during the same apply

In hybrid execution, .import_from() also accepts a RuntimeValue[str] or an f-string containing runtime references. This lets you create a parent resource and adopt a side-effect resource that the provider creates automatically—all in one apply.

Two common examples:

  1. AWS VPC default security group (see examples/aws_adopt_default_sg/): default_sg.import_from(vpc.output.default_security_group_id) waits for the new VPC, then adopts and locks down its default security group in the same run.
  2. Keycloak built-in client scopes created automatically with a new realm:
# coding: nf_autoid

from nf.core import App, Bind, BindContext, LifecycleRules, Secret, Stack
from nf.core.runtime.runtime import hybrid_runtime
from nf.providers.keycloak.keycloak import KeycloakProvider, OpenidClientScope, Realm
from nf.providers.keycloak.keycloak.data_sources.openid_client_scope_data_source import (
    OpenidClientScopeDataSource,
)


@hybrid_runtime
def scope_import_id(realm_id: str, scope_id: str) -> str:
    return f"{realm_id}/{scope_id}"


def identity(client_secret: Secret[str]) -> App:
    with App(nf_id="identity") as app, Stack() as sso, BindContext:
        keycloak: Bind = KeycloakProvider(url="https://sso.example.com", client_id="nf-admin", client_secret=client_secret)
        acme: Bind = Realm(realm="acme", enabled=True)
        existing_profile: Bind = OpenidClientScopeDataSource(name="profile", realm_id=acme.output.id, depends_on=[acme])
        profile: Bind = OpenidClientScope(
            name="profile",
            realm_id=acme.output.id,
            include_in_token_scope=True,
            lifecycle=LifecycleRules(adopt="required"),
        )
        profile.import_from(scope_import_id(acme.output.id, existing_profile.ref_id_))
    return app

Define runtime helper functions at module level so saved plans can serialize them (an f-string such as profile.import_from(f"{acme.output.id}/{existing_profile.ref_id_}") works as well). Run with:

nf apply --app identity ++@secrets.toml --apply-deferred --approve-imports --auto-approve

An unresolved runtime ID appears in the initial plan as a deferred import (import_id_unknown), never a create; resources depending on it wait too. Once resolved to a non-empty string, normal lookup, missing-object, and duplicate-adoption checks apply.


Migrating a Terraform module

Convert existing HCL and adopt its Terraform state in three commands:

nf convert ./network ./converted          # writes converted/network and converted/network.adopt.json
nf plan --app network --adopt-from converted/network.adopt.json --terraform-state ./network/terraform.tfstate --diff
nf apply --app network --adopt-from converted/network.adopt.json --terraform-state ./network/terraform.tfstate

nf convert records every address rename (aws_instance.web[0] → web_0, module.edge.aws_vpc.main → edge_main) in the generated manifest so the plan imports every state entry cleanly and surfaces any config drift before apply. For the full walkthrough, see Convert a Terraform project.


Direct import on PostgreSQL graph state

Apps backed by PostgreSQL graph state also support recording a single existing resource directly via a fenced state operation:

nf state import --app platform network.aws_vpc.main vpc-0abc123
nf state import --app platform network.aws_s3_bucket.logs --identity '{"bucket": "acme-logs"}'

Prefer plan-time adoption (import_from, adopt=, or --adopt-from) whenever you want to review configuration diffs alongside the import in a saved plan.


Practical troubleshooting and common pitfalls

Problem Cause Fix
Plan shows ± replace on an imported resource An immutable (ForceNew) argument in Python differs from the live object's value. Run nf plan --diff, copy the live attribute value into Python (or add it to ignore_changes if intentionally unmanaged), and re-plan until the replacement disappears.
--auto-approve stops before applying Auto-approve refuses imports by default so unattended CI cannot silently take over live objects. Review the plan and pass --approve-imports (or apply interactively).
Plan refuses duplicate adoption State already manages the same live object under a different address. Use nf state mv if you are renaming an address; only pass --allow-duplicate-adoption if intentionally overriding.
Provider rejects import ID format Each provider resource defines its own ID syntax (often <parent>/<child> or an ARN). Check the provider's Terraform docs for that resource's "Import" section, or use LifecycleRules(adopt="required") when the provider publishes a resource identity schema.
Warning about leftover import_from The resource is already in state from an earlier apply. Remove .import_from(...) from your Python code (or omit --adopt-from).
nf import asks for a synthesized stack nf import is the legacy Terraform/OpenTofu CLI passthrough command. Use .import_from(...), LifecycleRules(adopt=...), or --adopt-from with nf plan / nf apply --app for hybrid apps.

Safety settings

Every adoption setting can be set via CLI flag, [tool.nf.config], or App(...) (precedence: flag > [tool.nf.config] > App(...) > default; no NF_* environment variables are read):

Setting Default Flag Meaning
approve_imports off nf apply --approve-imports Allow --auto-approve to approve imports. Without it, unattended applies stop before mutating anything.
adopt_missing create --adopt-missing create\|error Behavior when an object to adopt is not found (adopt="required" always errors per resource).
allow_duplicate_adoption off --allow-duplicate-adoption Allow adopting an object state already holds under another address (off refuses).
adopt_from none --adopt-from FILE Path to the adoption manifest.
adopt_terraform_state manifest's --terraform-state FILE Terraform state file for terraform_address entries in the manifest.

From Python (nf.sdk or HybridExecutionMode), plan() and apply() accept adopt_from= and terraform_state=, and apply() accepts approve_imports=.


Terraform synthesis

When synthesizing for legacy Terraform/OpenTofu compatibility (nf synth):

  • .import_from("literal-id") is emitted as a Terraform import block.
  • Runtime / deferred .import_from(runtime_value) requires native hybrid execution and is rejected during synthesis with an explicit error.
  • LifecycleRules(adopt=...) is hybrid-only and omitted from synthesized lifecycle blocks.
  • Legacy Import and Move constructs are rejected in hybrid execution (use import_from / --adopt-from and nf state mv instead).