Skip to content

Runtime Functions and Runtime Checks

Hybrid execution runs Python while it plans and applies. A runtime function computes a value from real values: an attribute of a resource once it exists, a file, an API's answer. A runtime check guards one resource at a fixed point of the run, and fails it when its condition does not hold. Both are plain Python; neither needs Terraform's functions, the external provider or a subprocess.

For checks over the whole run (an account guard before state is read, a policy over every change of a plan, evidence after it), see App checks.

Runtime functions

Decorate a function with @hybrid_runtime, and call it where a resource takes a value. Its arguments may be references to other resources:

# coding: nf_autoid

import json

from nf.core import App, Bind, BindContext, Stack
from nf.core.runtime import hybrid_runtime
from nf.providers.hashicorp.aws import AwsProvider, S3Bucket, S3BucketPolicy


@hybrid_runtime
def read_only(bucket_arn: str, reader_arn: str) -> str:
    """A bucket policy letting one role read the bucket's objects."""
    statement = {"Effect": "Allow", "Principal": {"AWS": reader_arn}, "Action": "s3:GetObject", "Resource": f"{bucket_arn}/*"}
    return json.dumps({"Version": "2012-10-17", "Statement": [statement]})


with App(nf_id="reports") as app, Stack() as reports, BindContext:
    aws: Bind = AwsProvider(region="eu-west-1")
    bucket: Bind = S3Bucket(bucket_prefix="reports-")
    policy: Bind = S3BucketPolicy(
        bucket=bucket.output.id,
        policy=read_only(bucket.output.arn, "arn:aws:iam::123456789012:role/report-reader"),
    )

Calling read_only(...) while the app is built runs nothing: it returns a value that hybrid execution evaluates once its arguments are known.

  • Known while planning (literals, values state already holds): the function runs during the plan, and the plan shows its result.
  • Known only after apply (here, a new bucket's ARN): the plan shows the value as known after apply, and the function runs during the apply, as soon as the bucket exists, before the policy is created.

A function that raises fails the resource that takes its value, with the exception's message, as a provider error would. With recovery_strategy="ROLLBACK" the apply then deletes what it created; examples/rollback_on_failure shows it with no cloud account.

Forms

Form Becomes
@hybrid_runtime on a function with parameters a function: each call is a value (read_only(arn, role))
@hybrid_runtime on a function without parameters the value itself (policy=current_policy)
runtime_lambda(lambda: ...) a value from an inline function, for a one-off expression
from datetime import UTC, datetime

from nf.core.runtime import hybrid_runtime, runtime_lambda


@hybrid_runtime
def build_date() -> str:
    return datetime.now(UTC).strftime("%Y-%m-%d")


tag = runtime_lambda(lambda: f"build-{datetime.now(UTC):%Y%m%d}")

A function's result may be anything the argument takes (a string, a number, a list, a mapping), and may hold references itself; those are evaluated in turn.

What a function should do

  • Return the same result for the same arguments. Every plan evaluates it again, and a different result plans a change. The date above changes daily, and so does what a resource built from it plans.
  • Read, not change. A function may run at any plan and any apply; changes belong to resources, which a plan shows and an apply approves.
  • Say what it reads besides its arguments, on graph state: @hybrid_runtime(reads=[]) declares a function that reads nothing else, which graph state's planning takes into account. Without reads, a function is taken to read the whole app.

Hybrid execution does not evaluate Terraform's functions (Fn.*); a resource that calls one is refused before anything starts. What Terraform does with jsonencode, cidrsubnet or formatdate, Python does here.

Runtime checks

A runtime check is a function of a RuntimeCheckContext that says whether one resource may go on. Attach it with runtime_checks= on the resource:

# coding: nf_autoid

from nf.core import App, Bind, BindContext, Stack
from nf.core.runtime import RuntimeCheckContext, post_apply_check, pre_apply_check
from nf.providers.hashicorp.aws import AwsProvider, DbInstance


@pre_apply_check("production databases keep deletion protection on")
def protected(context: RuntimeCheckContext, env: str) -> bool:
    return env != "prod" or bool((context.config or {}).get("deletion_protection"))


@post_apply_check("the database is encrypted at rest")
def encrypted(context: RuntimeCheckContext) -> bool:
    return bool((context.new_state or {}).get("storage_encrypted"))


def orders(env: str = "dev") -> App:
    with App(nf_id="orders") as app, Stack(nf_id=f"orders-{env}") as orders, BindContext:
        aws: Bind = AwsProvider(region="eu-west-1")
        database: Bind = DbInstance(
            identifier=f"orders-{env}",
            engine="postgres",
            instance_class="db.t4g.micro",
            allocated_storage=20,
            username="orders",
            manage_master_user_password=True,
            storage_encrypted=True,
            deletion_protection=env == "prod",
            skip_final_snapshot=env != "prod",
            runtime_checks=[protected(env), encrypted],
        )
    return app

A decorated check is attached as it is (encrypted), or called with its own arguments, which follow the context (protected(env)). runtime_check(function, phase=..., args=(...)) builds one without a decorator.

Phases

Phase (decorator) Runs Context it reads
pre_plan (pre_plan_check) before the resource is planned with its provider config, prior_state
post_plan (post_plan_check) once its change is planned config, prior_state, planned_state
pre_apply (pre_apply_check, the default) just before its provider changes it config, prior_state, planned_state
post_apply (post_apply_check) once its provider returned it config, prior_state, new_state
retained (retained_check) when a destroy keeps it (Keeping resources) prior_state (as state recorded it), current_state (as its provider reads it then)

config is the resource's configuration as planned, prior_state its attributes in state before the run, and stack_outputs the outputs of every stack, by stack. A replacement also runs the prior object's pre_apply checks before deleting it, with config and planned_state set to None, as a destroy does: a failing check stops the replacement before anything is deleted.

Results

  • None or True: passed. False: failed, saying the decorator's message.
  • RuntimeCheckResult(status="failed", detail="..."): failed, saying why; status="deferred" defers it.
  • Reading a value known only after apply (context.planned_state["arn"] of a resource not created yet), or calling defer_runtime_check("why"), defers the check. The plan records it as deferred, and the apply evaluates it again; still undecided then, the apply fails rather than go on.

A failing post_apply check fails the resource, but its object stays in state, as the provider created or changed it: the next apply does not create a second one.

Rules

  • Module level. A plan records each check by its module and name, and a saved plan's apply imports it again: a check defined inside a function, a bound method, or one in a script run as __main__ is refused where it is declared.
  • Read only. A check decides; it does not change what it checks.
  • Declared reads (runtime_check(..., reads=[...])): what it reads besides its resource ("app", a stack, another resource). The provenance report compares it with what the check read; a check without one is taken to read the whole app.

Hybrid execution refuses Terraform's precondition and postcondition blocks; runtime checks are what does their work here.

Legacy synthesis

An app exported for Terraform or OpenTofu (nf synth) cannot run Python while Terraform plans. There, runtime_function(module_function) writes the call as Terraform's external data source, which runs a Python entrypoint that imports the function. Runtime checks, @hybrid_runtime and runtime_lambda are hybrid only.