Skip to content

Deferred Provider Configuration

A provider may be configured from resources the same run creates: the kubernetes and helm providers from the endpoint, CA and token of an EKS cluster the app creates. Hybrid execution converges such an app from nothing in one apply. The plan defers the resources of a provider it cannot configure yet, as Terraform's deferred actions do (Terraform 1.9+, -allow-deferral); apply configures that provider once its prerequisites finish, then plans and applies its resources. By default the initial approval covers these deferred changes. An apply nobody is asked about (a saved plan, auto-approve) does that only with the apply_deferred opt-in, and otherwise stops incomplete (see Approval and settings).

Pass an existing EKS role ARN and subnet IDs when building this app. The Kubernetes provider takes its endpoint from the cluster resource.

from nf.core import App, Provider, Resource, Stack


def build_app(cluster_role_arn: str, subnet_ids: list[str]) -> App:
    with App(nf_id="installer") as app, Stack(nf_id="platform"):
        aws = Provider(nf_type="aws", nf_id="aws", region="us-east-1")
        cluster = Resource(
            nf_type="aws_eks_cluster",
            nf_id="main",
            name="main",
            role_arn=cluster_role_arn,
            vpc_config=[{"subnet_ids": subnet_ids}],
            nf_provider=aws,
        )

        kubernetes = Provider(
            nf_type="kubernetes",
            nf_id="kubernetes",
            host=cluster.output.endpoint,
            exec=[
                {
                    "api_version": "client.authentication.k8s.io/v1beta1",
                    "command": "aws",
                    "args": ["eks", "get-token", "--region", "us-east-1", "--cluster-name", "main"],
                }
            ],
        )
        Resource(
            nf_type="kubernetes_namespace",
            nf_id="apps",
            metadata=[{"name": "apps"}],
            nf_provider=kubernetes,
        )
    return app

On the first apply the cluster does not exist, so host is not known when the plan is made: the namespace is deferred, and created once the cluster is. The same holds for settings taken from the cluster's CA or from a token data source that depends on it.

Planning

A provider configuration's settings are evaluated like a resource's configuration. When the plan is made:

Settings What the plan does
Constants, or values known from state (a cluster created by an earlier run) Configures the provider and plans its resources, as before
A value not known yet (a resource not created yet, a data source not read yet) Starts the provider for its schemas only, never configures or calls it, and defers its resources (provider_config_unknown)
Known, but a planned change makes a value unknown or different (the cluster is replaced) Defers its resources (provider_config_unknown): they are reached through what that change makes

Imports can also wait for a resource or data-source output used in import_from() even when their provider is already configured (import_id_unknown). Their input references are graph prerequisites, and later rounds resolve the ID before importing and planning changes; see Import IDs discovered during the same apply.

Whatever depends on a deferred change is deferred too (deferred_prereq): resources referring to a deferred resource, outputs, data sources, ephemeral resources, and deletes whose provider is deferred. A deferred change is not planned: no PlanResourceChange, no read, no runtime checks. The plan summary lists it under deferred_changes, apart from the changes counted in creates, updates and deletes:

{
  "resource": "platform.kubernetes_namespace.apps",
  "stack": "platform",
  "action": "create",
  "reason": "provider_config_unknown",
  "provider": "kubernetes",
  "waiting_for": ["${aws_eks_cluster.main.endpoint}"]
}

action is what the change is expected to be: import for a requested adoption (with its lookup source in import), create for a resource not in state, update for one in state (which may turn out to be no change once planned), delete for one removed from the app, read, open or output for the other kinds. The CLI shows them under "Deferred changes".

With graph state, apply_deferred=True and deferred_approval="once" or "auto" also let qualified fresh creates defer provider planning when resource inputs are unknown. These appear as resource_config_unknown. Their provider settings must be constant, their cloud identity known, and their dependencies concrete. Lifecycle rules, runtime checks, adoption, resource grants and unsupported metadata keep their existing planning paths. Broad or opaque dependency models also retain ordinary planning.

An eligible live app apply validates and plans each such create once its inputs are available, immediately before its fenced provider call. This avoids planning the same create first with unknown inputs and again with final values. Validation errors for a deferred create are therefore reported during apply, potentially after its prerequisites have been created. Saved plans retain the deferral and the existing opt-in and approval rules; their deferred work still passes through full plan-round validation.

Every construct is ordered after what its provider's settings refer to, as Terraform orders it after its provider configuration: planned and applied after those resources, destroyed before them. State records those edges in the entry's dependencies, so a destroy deletes the namespace before the cluster. Destroy also derives these edges from the declared provider configurations for older or adopted state that lacks them. It uses each state's exact provider key (including its alias), even if the consumer's resource declaration has been removed. Keep the provider configuration declared until its last managed consumer has been destroyed.

Refresh diagnostics

Plans retain resource-level refresh problems in summary.refresh_diagnostics, including objects with no planned changes. nf plan and nf show --plan-file display each resource address, provider configuration (including its alias), operation and fixed failure category. Timed-out reads include their configured deadline and measured elapsed seconds. Elapsed time measures the provider call; waiting for a concurrency slot is excluded.

For example:

platform.helm_release.monitoring: helm, ReadResource, timed out, deadline 30s, elapsed 30.01s

Interactive apply approval, deferred approval and auto-approve refusal include the same diagnostics. Unknown refreshed state still requires review; reporting does not relax that guard. Categories distinguish timeouts, provider errors, unsupported reads, missing provider configurations, incompatible stored state, invalid responses and objects deleted outside nf. The records omit raw exception messages, resource attributes, credentials, private state and identity payloads. Successful reads produce no diagnostic rows. Older plan files remain readable but cannot recover resource-level diagnostics that were never saved.

Provider-reported read failures additionally carry provider_diagnostics: fixed categories such as expired_credentials, cloud_authorization or authentication. Recognized AWS SDK error framing may contribute an allowlisted aws_error_code and a UUID-form aws_request_id; unknown codes, other request-ID formats and arbitrary diagnostic text are omitted. Plan/show and apply review display these facts beside the address, provider, operation and timing. This adds evidence without retrying failed reads, changing permissions or accepting unknown state. Old plans without these optional facts still display normally.

Apply errors use the same fixed guidance and identify ApplyResourceChange and the resource type. Both provider summary and detail are withheld because either may contain credentials, manifests or API response bodies; nf does not claim to redact arbitrary provider text safely. Unknown errors remain explicit but may need read-only inspection of the affected resource to diagnose. Partial object state returned with an apply error is still retained for recovery.

Apply

Apply walks the plan's other changes as one graph, as always; nothing that is not deferred depends on a deferred change. With the default deferred_approval="once", statically bounded changes become eligible as soon as their concrete prerequisites finish; unrelated resources can still be running. Graph state requires qualified identities for these overlapping operations. Equal provider settings reuse the client while recording fresh graph input revisions.

Explicit per-round approval (each_round or always), adoption sets, opaque evaluation, and graph identities requiring conservative exclusion use rounds after the current graph finishes:

  1. Each provider configuration whose settings use runtime values is evaluated against the state the apply wrote. One whose settings are now known (or differ from those its client runs with) gets a client of its own, configured with them: a provider is configured once per process.
  2. The deferred changes alone are planned, as a plan of their own: their state entries refreshed through the newly configured providers, the rest of the app's values from state, runtime checks and lifecycle rules as in any plan. A change whose provider still waits (a provider configured from a resource of another deferred provider) stays deferred for the next round. Requested adoptions are looked up only once their providers can be configured, then planned against the objects found; see Adopting Existing Infrastructure.
  3. That plan is approved as deferred_approval says (below), then applied as any plan: dependency order, parallelism, state batching, data sources read and outputs recorded.

A round that can plan none of its changes (a provider's settings still wait for values after the resources they refer to were applied) fails the apply, naming what each provider waits for. A round that is not approved stops the apply incomplete; the next plan has its changes, as ordinary changes once their providers can be configured.

Approval and settings

Nothing applies that a human, or an explicit opt-in, did not approve. The plan the user approves lists the deferred changes but holds no plan of them, so:

  • Interactive apply (apply(), nf apply, nf deploy): the default once policy includes deferred work in the initial approval. Choose each_round to review each later plan (ApprovalRequest.operation == "apply-deferred").
  • Auto-approve approves the plan's own changes only. Without the apply_deferred opt-in, the apply applies them and stops incomplete, leaving the deferred changes for the next plan and review. With it, each round's plan is logged and applied.
  • A saved plan (an artifact loaded from a file, nf apply --plan-file) applies only what it holds: its deferred changes are left for the next plan, and the approval prompt says so. With apply_deferred they are planned and applied in the same run, each round approved as below. A plan made in the same run (apply() without a plan, nf deploy) is not a saved plan.

An apply that succeeds but leaves deferred changes returns ExecutionResult(success=True, complete=False), with deferred listing them and warnings saying why; the CLI reports them and exits with incomplete_exit_code (2 by default, as Terraform's detailed exit codes tell changes from none), so CI can tell a converged apply from a partial one.

Setting (App attribute, [tool.nf.config] key) nf apply / nf deploy flag Default Values
apply_deferred --apply-deferred / --no-apply-deferred False Let a saved plan, or an auto-approved apply, plan and apply its deferred changes in the same run
deferred_approval --deferred-approval once each_round: ask for each round (logged under auto-approve with the opt-in); once: the plan's approval covers every round, which is said in its prompt, and the rounds are logged; auto: ask for none, only with apply_deferred (refused otherwise); always: ask for each round even under auto-approve, which then approves the plan's own changes only
incomplete_exit_code --incomplete-exit-code 2 The CLI's exit code for an incomplete apply; 0 treats it as converged
provider_data_sources --provider-data-sources read read: read the data sources a provider's settings refer to before configuring it; state: take their results from state (not recommended)
deleted_objects --deleted-objects review review: plan creating an object deleted outside Netherframe again, and refuse it under auto-approve; recreate: the same, unattended too; error: fail the plan

Flags win over [tool.nf.config], which wins over the app's values; nothing is read from the environment. An unknown value falls back to the default, with a warning.

Provider settings that read data sources

The data sources a provider's settings refer to (a cluster's auth token, say) are read before the provider is configured, once per run, so its settings hold values read now, not the results state keeps from the last run (an EKS token expires after 15 minutes). Planning keeps that read rather than reading the data source again, so the provider's settings and the plan agree, and a plan after convergence is still empty. A data source whose configuration waits for a value not known yet (a cluster not created yet), or whose own provider is not configured yet, is not read: the provider waits for it and is deferred, then configured during apply once the data source can be read. provider_data_sources = "state" restores taking the results state keeps (not recommended). A saved plan's provider fingerprints are taken from state either way: a token read now differs on every read, while state does not change between plan and apply.

Process-local provider endpoints

A provider reached through a process-owned SDK tunnel may use a different loopback port in every nf plan and nf apply process. Its transport owner can return a LocalProviderEndpoint rather than an ordinary URL:

from nf.core.values.provider_endpoint import LocalProviderEndpoint


def grafana_endpoint(listener_port: int, ca_sha256: str) -> LocalProviderEndpoint:
    """The tunnel's local listener, bound to the in-cluster service it reaches."""
    return LocalProviderEndpoint(
        f"http://127.0.0.1:{listener_port}",  # HTTP(S) loopback listener with an explicit port
        target="http://grafana.monitoring.svc:3000",
        scope={
            "api_server": "https://10.0.0.1:6443",
            "ca_sha256": ca_sha256,  # the digest of the cluster CA the tunnel verified
            "service": "monitoring/grafana",
            "service_port": "3000",
        },
    )


# This process's tunnel listens on 43211; the next process's may listen elsewhere
endpoint = grafana_endpoint(43211, "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08")

Pass this value directly to the generated provider's URL argument, including as the result of a hybrid runtime function. The provider receives the actual local URL. Saved-plan validation fingerprints the canonical target, transport scope, URL scheme/host/path and every other provider setting; only the marked listener's port may change. Target, CA/scope, credentials and provider source/version changes still invalidate the plan. Ordinary URL strings retain their existing hashes and exact-port checks. Casting or interpolating the value into a plain string discards the explicit transport identity.

The transport owner is responsible for verifying the remote endpoint and binding scope to it. Use stable, nonsecret identities such as the API server and the digest of its verified CA, not a context nickname, credential token, temporary CA filename or pod name. The marker does not establish trust or open a tunnel by itself. It rejects non-loopback listeners and URLs with credentials, queries or fragments, and keeps immutable identity metadata when copied.

Objects deleted outside Netherframe

When a provider's ReadResource returns no object, the object is gone, as Terraform reads it. By default (deleted_objects = "review") the plan creates it again, shows it as "deleted outside Netherframe" (deleted_outside and deleted_outside_resources in the summary, deleted_outside on the change), and needs review: requires_refresh_review is set, so auto-approve refuses the plan as it does for unknown refreshed state, and the interactive prompt lists the objects. An object gone that the app no longer declares is dropped from state. recreate re-creates such objects unattended too; error fails the plan, naming them.

This is what happens after a cluster is replaced: the kube objects are deferred, and once kube is configured for the new cluster, refreshing them finds them gone there. They are re-created after review: interactively, the round's prompt shows them; under auto-approve (with apply_deferred) the round stops incomplete rather than re-creating them unattended, and the next plan, which configures kube for the new cluster from state, shows them for review. With deleted_objects = "recreate" the round re-creates them.

A second apply after convergence is a no-op: the providers are configured from state when the plan is made, and their resources plan no change.

Failures and recovery

A failure in the first part skips the deferred changes (they are reported in ExecutionResult.deferred, and their provider is never configured). A failure in a round stops the apply there. The recovery strategy covers the whole apply: the CHECKPOINT written before the first part is the restore point, and ROLLBACK deletes what every part created. An apply that stops incomplete (not approved, needing review, or not allowed to run its rounds) has not failed: nothing is rolled back.

Saved plans

A saved plan holds each deferred change's record with its reason and what it waits for ("deferred" in the node's change), and never a planned state for it: nothing was planned. Applying it applies the plan's own changes exactly as saved and, by default, stops incomplete. With apply_deferred, it then plans the deferred ones at apply time with the app loaded, approved as deferred_approval says, as the plan the user saw did not hold them. A saved plan applied without its app's constructs cannot plan its deferred changes and is refused before anything is applied. The reader also accepts development plans from before deferred changes were recorded.

The plan's provider fingerprint of a deferred configuration is that of what its settings wait for, so applying a saved plan checks that the provider still waits for the same values.

Planning part of the app

plan_stack and apply_stack load the provider configurations of the stack and of the stacks it needs (those it depends on, and those its resources, providers and outputs refer to), not every provider of the app, and refresh those stacks' resources only. The other stacks' values come from state.

Differences from Terraform

  • Terraform applies a plan with deferred changes without them and reports the run incomplete; the next plan picks them up. Hybrid does the same for saved and auto-approved plans by default, and otherwise plans and applies them in the same run, with an approval of their own.
  • Terraform configures a provider during the plan walk, after the data sources its settings refer to are read. Hybrid reads those data sources and configures the provider when the providers are loaded, before refresh, with the resources' values from state: a planned change to a resource the settings refer to defers the provider's constructs rather than configuring it with planned values.
  • Terraform plans the deferred resources of one round with the other deferred changes still unknown. Hybrid plans each round after the previous one is applied, so a round's independent slow resources wait for the round before.