Skip to content

Discovery, Import, and Drift

Brownfield infrastructure rarely starts from an empty account. Netherframe provides a continuous three-stage workflow for taking ownership of existing resources and keeping code and reality aligned:

flowchart LR
    A["1. Discover (nf discover)"] --> B["Inventory or codify live objects"]
    B --> C["2. Import / Adopt (nf plan & apply)"]
    C --> D["Record existing objects in state"]
    D --> E["3. Detect & Reconcile Drift (nf drift / nf plan)"]
    E --> F["Revert live drift or patch Python code"]

Stage 1: Discover live resources (nf discover)

Discovery packages are separate optional distributions installed alongside netherframe.cli:

uv add netherframe.discovery.hashicorp.aws       # AWS inventory
uv add netherframe.discovery.keycloak.keycloak   # Keycloak inventory & codification
uv add netherframe.discovery.gitlabhq.gitlab     # GitLab inventory

Check installed providers and supported resource types

nf discover list providers
nf discover list resource-types aws --filter "aws_s3_*"
nf discover list resource-types aws --filter "aws_vpc*"

Example 1: Inventory a targeted AWS slice

Always start by validating credentials and restricting discovery to the specific resource types you plan to bring under management:

nf discover validate aws --region us-east-1

# Human-readable table of VPCs and S3 buckets
nf discover resources aws --region us-east-1 \
  --resource-types aws_vpc \
  --resource-types aws_s3_bucket

# Full JSON inventory (with attributes and import IDs) for scripting or review
nf discover resources aws --region us-east-1 \
  --resource-types aws_vpc \
  --resource-types aws_s3_bucket \
  --json > inventory-aws.json

Example 2: Codify an existing Keycloak realm into Python + an adoption manifest

For Keycloak, nf discover codify reads the realm through the admin API, imports each object through the provider, and writes both Python code and a ready-to-use adoption manifest (realm_demo.adopt.json) beside it:

export KEYCLOAK_USER=admin
export KEYCLOAK_PASSWORD="..."

nf discover codify keycloak \
  --url https://sso.example.com \
  --realm demo \
  -o realm_demo.py

Secrets are never written into realm_demo.py. See Codifying a Keycloak Realm for the complete walkthrough.

Example 3: Inventory a GitLab instance

nf discover resources gitlab \
  --url https://gitlab.example.com \
  --token "$GITLAB_TOKEN" \
  --json > inventory-gitlab.json

Stage 2: Model and import into state (Adoption)

Discovery does not take ownership of live objects by itself. Once you have the resource IDs or identities from Stage 1, model the target slice in Python and import it through a reviewed plan.

Example 4: Model discovered AWS resources and request adoption

Suppose inventory-aws.json returned VPC vpc-0abc123def456 and bucket acme-prod-logs:

# coding: nf_autoid

from nf.core import App, Bind, BindContext, LifecycleRules, Stack
from nf.providers.hashicorp.aws import AwsProvider, CloudwatchLogGroup, S3Bucket, Vpc


def platform(region: str = "us-east-1") -> App:
    with App(nf_id="platform") as app, Stack() as core, BindContext:
        aws: Bind = AwsProvider(region=region)

        # Known provider ID from discovery -> .import_from(...)
        vpc: Bind = Vpc(
            nf_provider=aws,
            cidr_block="10.0.0.0/16",
            enable_dns_support=True,
            enable_dns_hostnames=True,
        ).import_from("vpc-0abc123def456")

        # Identifiable directly from config -> LifecycleRules(adopt="required")
        logs: Bind = S3Bucket(
            nf_provider=aws,
            bucket="acme-prod-logs",
            lifecycle=LifecycleRules(adopt="required"),
        )

        # Import if it already exists, otherwise create it
        log_group: Bind = CloudwatchLogGroup(
            nf_provider=aws,
            name="/acme/platform",
            retention_in_days=30,
            lifecycle=LifecycleRules(adopt=True),
        )
    return app

Save and inspect the import plan before changing anything:

# Preview imports and any configuration diffs; fail if a required object is missing
nf plan --app platform --diff --adopt-missing error --out import-plan.json

# Apply the exact reviewed plan (pass --approve-imports in unattended CI)
nf apply --app platform --plan-file import-plan.json

# Confirm convergence: should report 0 changes
nf plan --app platform

Example 5: Bulk-import via an adoption manifest (no code edits)

If you generated a manifest with nf discover codify or nf convert (or wrote one by hand), keep your Python clean of .import_from(...) calls and pass --adopt-from:

{
  "format_version": 1,
  "adopt": {
    "core.aws_vpc.vpc": {"import_id": "vpc-0abc123def456", "required": true},
    "core.aws_s3_bucket.logs": {"identity": {"bucket": "acme-prod-logs"}, "required": true}
  }
}
nf plan --app platform --adopt-from core.adopt.json --diff --out import-plan.json
nf apply --app platform --plan-file import-plan.json

For deferred providers, runtime import_from() IDs, Terraform state migration (--terraform-state), and troubleshooting import diffs, see How to Import (Adopt) Existing Resources.


Stage 3: Detect, check, and reconcile drift

Netherframe gives you two complementary ways to detect out-of-band changes:

Tool Compares Best for Exit code on drift
nf plan --app <app> --expect-no-changes Desired app + recorded state vs. live provider refresh Scheduled CI drift checks on deployed apps; reverting live cloud back to Python code 3
nf drift detect \| check \| fix Python source files vs. live providers (via state or resource identity) Auditing source trees, checking unmanaged resources by identity, or patching Python code to match accepted live changes 3

Example 6: Scheduled CI drift check with nf plan

For an already-deployed hybrid app, the fastest drift check is a non-mutating plan with --expect-no-changes:

nf plan --app platform --expect-no-changes --diff --json > drift-plan.json
case $? in
  0) echo "No drift detected" ;;
  3) echo "Drift detected — inspect drift-plan.json" ; exit 3 ;;
  *) echo "Plan failed" ; exit 1 ;;
esac

Example 7: Source-level drift inspection and patching (nf drift)

Create a providers.json file naming the provider configuration for live reads:

{
  "providers": {
    "aws": {
      "region": "us-east-1"
    }
  },
  "sources": {
    "aws": "hashicorp/aws"
  }
}

Inspect drift across your Python modules (by default, resources already in state are refreshed from state; resources not in state are imported by their provider identity):

# Human-readable drift report for a directory
nf drift detect infra/ --provider hashicorp/aws --provider-config providers.json

# Narrow to a single resource type
nf drift detect infra/ -f aws_s3_bucket --provider-config providers.json

# CI check (exits 0 = clean, 3 = drift detected, 1 = error)
nf drift check infra/ --provider-config providers.json --json

# Compare against an exported legacy Terraform state file without calling cloud APIs
nf drift detect infra/ --legacy --state-file legacy.tfstate

If an out-of-band change (such as a tag added in the AWS console) was intentional and you want to bring your Python code into sync with live infrastructure, preview the source patch first with --dry-run before writing it:

nf drift fix infra/ --dry-run --provider-config providers.json
nf drift fix infra/ --provider-config providers.json

Example 8: Programmatic drift check via nf.sdk

Drive drift detection from Python automation without parsing CLI output:

from nf.sdk import Project


def check_environment_drift(project_root: str) -> dict[str, object]:
    project = Project(project_root)

    # Whole-app plan drift check
    plans = project.plan(app="platform", expect_no_changes=True)

    # Source-level drift report
    drift = project.drift.check(paths=("infra",), provider_config="providers.json")

    return {
        "plan_has_changes": plans.has_changes,
        "plan_exit_code": plans.exit_code,  # 0 clean, 3 changes
        "source_drifted": drift.drifted,
        "source_exit_code": drift.exit_code,  # 0 clean, 3 drift
    }

Deciding how to resolve drift

Once drift is detected, choose one of three concrete actions:

Situation Action
Someone changed cloud settings accidentally; code is the source of truth Run nf plan --app <app> --diff --out fix.json, review, and run nf apply --app <app> --plan-file fix.json to restore desired state.
An emergency console change was valid and should stay Run nf drift fix --dry-run, apply the patch to your Python code, then confirm nf plan --app <app> reports no changes.
An external controller (such as an autoscaler or tag bot) owns specific attributes Add those attribute paths to LifecycleRules(ignore_changes=["tags", "desired_count"]) on the construct so future plans ignore them.