Skip to content

Docstring API Reference

This section is generated from Python docstrings via mkdocstrings.

If you want the high-level map first, read nf.core.

Core Constructs

Bases: AppCachingMixin, BaseConstruct

Root application construct using minimal BaseConstruct.

app property

Get the App instance for this construct tree.

app_context property

The app's context, which every app creates with itself.

checks property

The app-wide checks it declares (check), in order.

nf_path property

Get the construct path.

__enter__()

Enter context manager - push this construct as current scope.

__exit__(*args)

Exit context manager - pop this construct from context stack.

__init__(*, nf_id='app', context=None, disable_validation=None, deferred_validation=None, enable_circular_dep_resolution=None, max_concurrent_resources=None, max_concurrent_reads=None, recovery_strategy=None, enable_progress_reporting=None, apply_deferred=None, deferred_approval=None, incomplete_exit_code=None, provider_data_sources=None, deleted_objects=None, drift_correction=None, concurrent_applies=None, graph_plan_scope=None, approve_imports=None, adopt_missing=None, allow_duplicate_adoption=None, adopt_from=None, adopt_terraform_state=None, provenance_report=None, baseline=None, prefer_mine=(), run_status=None)

Initialize App.

Each setting below is overridden by its flag (nf --max-concurrent-resources 20 ...) or [tool.nf.config] in pyproject.toml, in that order; nothing is read from the environment.

Parameters:

Name Type Description Default
nf_id str

App ID (default "app")

'app'
context dict[str, Any] | None

App context dictionary

None
disable_validation bool | None

Disable all validation

None
deferred_validation bool | None

Defer validation until synthesis

None
enable_circular_dep_resolution bool | None

Enable multi-phase circular dependency handling

None
max_concurrent_resources int | None

Max resources to process concurrently

None
recovery_strategy str | None

Recovery strategy (CHECKPOINT, ROLLBACK, NONE)

None
enable_progress_reporting bool | None

Enable progress callbacks when available

None
apply_deferred bool | None

Let an apply that cannot ask for each deferred round (a saved plan, auto-approve) plan and apply its deferred changes in the same run (default False)

None
deferred_approval str | None

How deferred rounds are approved: once (default), each_round, auto (needs apply_deferred) or always

None
incomplete_exit_code int | None

CLI exit code of an apply that left deferred changes (default 4)

None
run_status bool | None

Keep a running apply's live status beside its state, for nf follow and nf tui elsewhere (default True)

None
provider_data_sources str | None

read (default) the data sources a provider's settings refer to before configuring it, or take them from state

None
deleted_objects str | None

What a plan does with an object its provider reports gone: review (default; re-create, refused under auto-approve), recreate, or error

None
drift_correction bool | None

Correct drift in graph state plans (default True). False accepts refreshed values when the recorded configuration is unchanged; explicit edits, taint and replacement triggers still apply.

None
concurrent_applies bool | None

Use automatic resource grants for graph applies (default False). Requires a pinned baseline; unsupported identity contracts retain app-wide exclusion.

None
graph_plan_scope str | None

Full planning (default) or the affected graph closure with a retained baseline. Unsupported work reports full fallback; this does not change the grant policy.

None
approve_imports bool | None

Let an auto-approved hybrid apply import existing objects (default False)

None
adopt_missing str | None

What a hybrid plan does when an object to adopt is not found: "create" (default) or "error"

None
allow_duplicate_adoption bool | None

Adopt an object state holds under another address too (default False)

None
adopt_from str | None

Adoption manifest every hybrid plan adopts from

None
adopt_terraform_state str | None

Terraform state the manifest's terraform_address entries come from

None
provenance_report bool | None

Record what a hybrid plan or apply reads and report it with its result (default False; see netherframe.core.execution.provenance_report)

None
baseline GraphBaseline | Path | str | int | None

Graph state origin: pinned reference, file, sequence or run ID. None reads nf.baseline from the current directory when present.

None
prefer_mine tuple[str, ...]

Addresses whose baseline intent conflicts use this configuration, after review. Requires a graph baseline.

()

__repr__()

String representation.

add_circular_dependency_validation(*, from_stack_path, from_stack_id, to_stack, check_fn)

Record a deferred circular dependency validation.

add_duplicate_resource_validation(*, parent_path, child_id, existing_children, construct_key)

Record a deferred duplicate-resource validation.

add_metadata(key, value)

Add metadata to this construct.

add_validation(validation)

Add a validation to this construct.

auto_configure_backend(stack)

Auto-configure backend for a stack if none is set.

check(function=None, /, *, phase='apply', description=None)

Declare an app-wide check, run in phase: prerequisites, plan or apply (the default).

@app.check, @app.check(phase="plan") or app.check(function, phase=...); the function is returned as it is. It gets an AppCheckContext and fails a run by returning False or a string saying why, or by raising. See netherframe.core.constructs.app_checks.

enable_hybrid_execution(state_backend=None, state_backend_config=None, provider_cache_dir=None, parallelism=None, outdir=None, refresh_timeout=30.0, approval=None, read_parallelism=None, refresh=True, targets=(), plan_scope='full')

Enable hybrid execution mode for this app (arguments as for HybridExecutionMode).

enable_hybrid_execution_local(*, path=None, **kwargs)

Enable hybrid execution with a local state backend.

enable_hybrid_execution_s3(*, bucket, key='terraform.tfstate', region=None, encrypt=True, dynamodb_table=None, profile=None, workspace_key_prefix=None, kms_key_id=None, **kwargs)

Enable hybrid execution with an S3 state backend.

find_all(predicate=None)

Find all constructs in the tree matching a predicate.

Parameters:

Name Type Description Default
predicate Any

Optional callable that takes a construct and returns True if it matches. If not provided, returns all constructs including self.

None

Returns:

Type Description
list[BaseConstruct]

List of matching constructs

find_child(child_id)

Find a direct child by ID.

Parameters:

Name Type Description Default
child_id str

The ID of the child to find

required

Returns:

Type Description
BaseConstruct | None

The child construct if found, None otherwise

get_app_dir()

Get the app directory path.

Returns:

Type Description
Path

Path to the app directory

hybrid_apply(auto_approve=False, plan=None)

Apply with hybrid execution (see HybridExecutionMode.apply).

hybrid_destroy(auto_approve=False)

Destroy with hybrid execution (see HybridExecutionMode.destroy).

hybrid_plan()

Plan with hybrid execution (see HybridExecutionMode.plan).

lint(rules=None, *, packs=None)

Run all matching offline lints, returning a report without raising on findings.

pending_validation_count()

Return the number of queued deferred validations.

run_deferred_validations()

Execute deferred validations and return failures with context.

synth(*, outdir=None, output_format='json', parallel=None)

Synthesize all stacks.

Parameters:

Name Type Description Default
outdir str | Path | None

Output directory (defaults to Path(".nf.out")). Accepts str or Path.

None
output_format str

Output format ("json" or "hcl")

'json'
parallel bool | None

Enable parallel synthesis for multiple stacks

None

uses_deferred_validation()

Return whether validation should be accumulated until synthesis.

validate()

Validate the app and all stacks.

validation_disabled()

Return whether app-level validation is disabled.

Bases: StackCachingMixin, BaseConstruct

Stack with flat resource registry using BaseConstruct.

app property

Get the parent app.

nf_path property

Get the construct path.

resources property

Get all resources in this stack.

__enter__()

Enter context manager - push this construct as current scope.

__exit__(*args)

Exit context manager - pop this construct from context stack.

__init__(*, nf_scope=None, nf_id=None, description=None, metadata=None)

Initialize Stack.

Parameters:

Name Type Description Default
nf_scope App | None

Parent App (optional, will try to detect from context)

None
nf_id str | None

Stack ID (required; the nf_autoid codec supplies it at a Bind or BindContext site)

None
description str | None

Stack description

None
metadata dict[str, Any] | None

Stack metadata

None

__repr__()

String representation.

add_dependency(stack)

Add a stack dependency.

Parameters:

Name Type Description Default
stack Stack

Stack instance this stack depends on

required

Raises:

Type Description
ValidationError

If adding self-dependency or circular dependency

add_metadata(key, value)

Add metadata to this construct.

add_validation(validation)

Add a validation to this construct.

depends_on(*stacks)

Add stack dependencies.

As Terraform's depends_on on a module, every construct of this stack then waits for every construct of the stacks it depends on (hybrid execution; synthesis orders stacks).

Parameters:

Name Type Description Default
*stacks Stack

One or more Stack instances this stack depends on

()

Raises:

Type Description
ValidationError

If adding self-dependency or circular dependency

ensure_provider(provider_id, provider_factory, /, **provider_kwargs)

Return an existing provider or register a new one.

find_all(predicate=None)

Find all constructs in the stack matching a predicate.

This override searches both children (other constructs) and resources.

Parameters:

Name Type Description Default
predicate Any

Optional callable that takes a construct/resource and returns True if it matches. If not provided, returns all constructs including self.

None

Returns:

Type Description
list[Any]

List of matching constructs/resources

find_child(child_id)

Find a direct child by ID.

Parameters:

Name Type Description Default
child_id str

The ID of the child to find

required

Returns:

Type Description
BaseConstruct | None

The child construct if found, None otherwise

get_assets_dir()

Get the assets directory path for this stack.

Returns:

Type Description
Path

Path to the assets directory

get_backend()

Return the configured backend, if any.

get_construct(mode, resource_type, name)

The construct the stack declares with that mode (resource, data, ...), type and name, if any.

get_provider(provider_id)

Return a registered provider by ID.

get_resource_count()

Get the count of resources in this stack.

get_stack_dir()

Get the stack directory path.

Returns:

Type Description
Path

Path to the stack directory

get_state_file_path()

Get the terraform state file path for this stack.

Returns:

Type Description
Path

Path to the terraform.tfstate file

get_tf_hcl_path()

Get the Terraform HCL file path for this stack.

Returns:

Type Description
Path

Path to the nf.tf file

get_tf_json_path()

Get the Terraform JSON file path for this stack.

Returns:

Type Description
Path

Path to the nf.tf.json file

has_runtime_functions()

Return whether this stack contains Terraform runtime functions.

iter_assets()

Return registered assets.

iter_imports()

Return registered import blocks.

iter_moves()

Return registered move blocks.

iter_outputs()

Return registered outputs.

iter_providers()

Return registered providers.

iter_resources()

Return registered resources.

iter_variables()

Return registered variables.

mark_runtime_function_usage()

Record that this stack contains Terraform runtime functions.

register_asset(asset)

Register an asset.

register_backend(backend)

Assign a backend to the stack.

register_import(import_block)

Register an import block.

register_move(move_block)

Register a move block.

register_output(output)

Register an output.

register_provider(provider)

Register a provider.

register_resource(resource, *, nf_key=None)

Register a resource in the stack registry.

register_variable(variable)

Register a variable.

validate()

Run validations on this construct.

Returns:

Type Description
list[str]

List of validation error messages

Bases: SimpleNamespace

Resource using SimpleNamespace for maximum performance.

Resources are created with explicit scope and ID

instance = aws.Instance( nf_scope=stack, nf_id="web-server", ami="ami-123", instance_type="t3.micro" )

nf_path property

Get the resource path (includes resource type for uniqueness).

nf_provider_type property

Local name of the provider that implements this construct (see provider_local_name).

output property

Access output attributes.

ref property

Reference to resource ID.

__init__(*, nf_scope=None, nf_id=None, nf_type=None, nf_provider=None, nf_mutable_config=None, **config)

Initialize resource with explicit nf_scope and nf_id.

Parameters:

Name Type Description Default
nf_scope BaseConstruct | None

Parent scope (typically a Stack)

None
nf_id str | None

Resource ID within the scope

None
nf_type str | None

Terraform resource type (e.g. 'aws_instance')

None
nf_provider Any | None

Provider instance to use

None
nf_mutable_config bool | None

Track nested config mutations after creation. When omitted, falls back to the module-level RESOURCE_CONFIG_IMMUTABLE_BY_DEFAULT flag.

None
**config Any

Resource configuration attributes

{}

__setattr__(name, value)

Set an attribute; an argument updates the configuration and marks the resource changed.

Its stack bumps the resource's configuration version, so what is built from the configuration (its synthesized form, its compiled holes and dependency edges) is built again from the new one.

get_all_attributes(include_tokens=True)

Get all resource attributes, optionally filtering out runtime tokens.

Parameters:

Name Type Description Default
include_tokens bool

Whether to include RuntimeValue attributes

True

Returns:

Type Description
dict[str, Any]

Dictionary of resource attributes

import_from(import_id)

Adopt the existing object with this import ID instead of creating one.

A hybrid plan imports it (ImportResourceState, then ReadResource) when state does not hold the resource yet, and shows an import action. Runtime IDs infer dependencies and wait for their inputs during native convergence; synthesis accepts literal IDs only. Once the object is in state the ID is not used again, and the plan says the call can go.

move_from(from_address, idempotent=False)

Create a moved block for this resource.

synthesize_hcl_attributes()

Synthesize attributes for HCL output, restoring Python keyword names.

Bases: StackBoundMixin, SimpleNamespace

Provider using SimpleNamespace.

nf_provider_settings property

Framework-owned provider settings.

__dir__()

Expose provider-bound exports for interactive discovery.

__enter__()

Set this as the active provider for the context.

__exit__(*args)

Remove this from the active provider context.

__getattr__(name)

Lazy loading of provider resources.

__init__(*, nf_scope=None, nf_id=None, nf_type=None, nf_provider_settings=None, **config)

Initialize provider with explicit nf_scope and nf_id.

__setattr__(name, value)

Override setattr to mark provider as dirty when attributes change.

Bases: Resource

Data source using SimpleNamespace.

Example

ami = aws.DataAmi( nf_scope=stack, nf_id="ubuntu", most_recent=True, owners=["099720109477"] )

nf_path property

Get the resource path (includes resource type for uniqueness).

nf_provider_type property

Local name of the provider that implements this construct (see provider_local_name).

output property

Access output attributes.

ref property

Reference to resource ID.

__init__(*, nf_scope=None, nf_id=None, nf_type=None, nf_provider=None, nf_mutable_config=None, **config)

Initialize resource with explicit nf_scope and nf_id.

Parameters:

Name Type Description Default
nf_scope BaseConstruct | None

Parent scope (typically a Stack)

None
nf_id str | None

Resource ID within the scope

None
nf_type str | None

Terraform resource type (e.g. 'aws_instance')

None
nf_provider Any | None

Provider instance to use

None
nf_mutable_config bool | None

Track nested config mutations after creation. When omitted, falls back to the module-level RESOURCE_CONFIG_IMMUTABLE_BY_DEFAULT flag.

None
**config Any

Resource configuration attributes

{}

__setattr__(name, value)

Set an attribute; an argument updates the configuration and marks the resource changed.

Its stack bumps the resource's configuration version, so what is built from the configuration (its synthesized form, its compiled holes and dependency edges) is built again from the new one.

get_all_attributes(include_tokens=True)

Get all resource attributes, optionally filtering out runtime tokens.

Parameters:

Name Type Description Default
include_tokens bool

Whether to include RuntimeValue attributes

True

Returns:

Type Description
dict[str, Any]

Dictionary of resource attributes

import_from(import_id)

Adopt the existing object with this import ID instead of creating one.

A hybrid plan imports it (ImportResourceState, then ReadResource) when state does not hold the resource yet, and shows an import action. Runtime IDs infer dependencies and wait for their inputs during native convergence; synthesis accepts literal IDs only. Once the object is in state the ID is not used again, and the plan says the call can go.

move_from(from_address, idempotent=False)

Create a moved block for this resource.

synthesize_hcl_attributes()

Synthesize attributes for HCL output, restoring Python keyword names.

Bases: StackBoundMixin, SimpleNamespace

Terraform output value.

Bases: StackBoundMixin, SimpleNamespace

Terraform variable.

ref property

Get reference to this variable's value.

type property

Compatibility alias for the Terraform variable type.

value(expected_type=None)

Get deferred reference to variable value.

Runtime and Functions

nf.core.Fn is the function catalog of the configured binary: terraform (below) or tofu, installed as netherframe.legacy_functions.hashicorp.terraform or netherframe.legacy_functions.opentofu.tofu.

Bases: LegacyFnHelpers, FnGenerated

Netherframe built-in functions for Terraform legacy mode.

abs_(num) staticmethod

abs returns the absolute value of the given number. In other words, if the number is zero or positive then it is returned as-is, but if it is negative then it is multiplied by -1 to make it positive before returning it. @param num

abspath(path) staticmethod

abspath takes a string containing a filesystem path and converts it to an absolute path. That is, if the path is not absolute, it will be joined with the current working directory. @param path

alltrue(list_) staticmethod

alltrue returns true if all elements in a given collection are true or "true". It also returns true if the collection is empty. @param list_

anytrue(list_) staticmethod

anytrue returns true if any element in a given collection is true or "true". It also returns false if the collection is empty. @param list_

base64decode(str_) staticmethod

base64decode takes a string containing a Base64 character sequence and returns the original string. @param str_

base64encode(str_) staticmethod

base64encode applies Base64 encoding to a string. @param str_

base64gzip(str_) staticmethod

base64gzip compresses a string with gzip and then encodes the result in Base64 encoding. @param str_

base64sha256(str_) staticmethod

base64sha256 computes the SHA256 hash of a given string and encodes it with Base64. This is not equivalent to base64encode(sha256("test")) since sha256() returns hexadecimal representation. @param str_

base64sha512(str_) staticmethod

base64sha512 computes the SHA512 hash of a given string and encodes it with Base64. This is not equivalent to base64encode(sha512("test")) since sha512() returns hexadecimal representation. @param str_

basename(path) staticmethod

basename takes a string containing a filesystem path and removes all except the last portion from it. @param path

bcrypt(str_, cost=None) staticmethod

bcrypt computes a hash of the given string using the Blowfish cipher, returning a string in the Modular Crypt Format usually expected in the shadow password file on many Unix systems. @param str_ @param cost The cost argument is optional and will default to 10 if unspecified.

can(expression) staticmethod

can evaluates the given expression and returns a boolean value indicating whether the expression produced a result without any errors. @param expression

ceil(num) staticmethod

ceil returns the closest whole number that is greater than or equal to the given value, which may be a fraction. @param num

chomp(str_) staticmethod

chomp removes newline characters at the end of a string. @param str_

chunklist(list_, size) staticmethod

chunklist splits a single list into fixed-size chunks, returning a list of lists. @param list_ @param size The maximum length of each chunk. All but the last element of the result is guaranteed to be of exactly this size.

cidrhost(prefix, hostnum) staticmethod

cidrhost calculates a full host IP address for a given host number within a given IP network address prefix. @param prefix prefix must be given in CIDR notation, as defined in RFC 4632 section 3.1. @param hostnum hostnum is a whole number that can be represented as a binary integer with no more than the number of digits remaining in the address after the given prefix.

cidrnetmask(prefix) staticmethod

cidrnetmask converts an IPv4 address prefix given in CIDR notation into a subnet mask address. @param prefix prefix must be given in CIDR notation, as defined in RFC 4632 section 3.1.

cidrsubnet(prefix, newbits, netnum) staticmethod

cidrsubnet calculates a subnet address within given IP network address prefix. @param prefix prefix must be given in CIDR notation, as defined in RFC 4632 section 3.1. @param newbits newbits is the number of additional bits with which to extend the prefix. @param netnum netnum is a whole number that can be represented as a binary integer with no more than newbits binary digits, which will be used to populate the additional bits added to the prefix.

cidrsubnets(prefix, *newbits) staticmethod

cidrsubnets calculates a sequence of consecutive IP address ranges within a particular CIDR prefix. @param prefix prefix must be given in CIDR notation, as defined in RFC 4632 section 3.1. @param *newbits

coalesce(*vals) staticmethod

coalesce takes any number of arguments and returns the first one that isn't null or an empty string. @param *vals

coalescelist(*vals) staticmethod

coalescelist takes any number of list arguments and returns the first one that isn't empty. @param *vals List or tuple values to test in the given order.

compact(list_) staticmethod

compact takes a list of strings and returns a new list with any empty string elements removed. @param list_

concat(*seqs) staticmethod

concat takes two or more lists and combines them into a single list. @param *seqs

conditional(condition, true_val, false_val) staticmethod

Conditional expression (ternary operator).

contains(list_, value) staticmethod

contains determines whether a given list or set contains a given single value as one of its elements. @param list_ @param value

convert(value, type_) staticmethod

convert converts a value to the given type constraint. @param value @param type_

csvdecode(str_) staticmethod

csvdecode decodes a string containing CSV-formatted data and produces a list of maps representing that data. @param str_

dirname(path) staticmethod

dirname takes a string containing a filesystem path and removes the last portion from it. @param path

distinct(list_) staticmethod

distinct takes a list and returns a new list with any duplicate elements removed. @param list_

element(list_, index) staticmethod

element retrieves a single element from a list. @param list_ @param index

endswith(str_, suffix) staticmethod

endswith takes two values: a string to check and a suffix string. The function returns true if the first string ends with that exact suffix. @param str_ @param suffix

ephemeralasnull(value) staticmethod

ephemeralasnull takes a value of any type and returns a similar value of the same type with any ephemeral values replaced with non-ephemeral null values and all non-ephemeral values preserved. @param value

file(path) staticmethod

file reads the contents of a file at the given path and returns them as a string. @param path

filebase64(path) staticmethod

filebase64 reads the contents of a file at the given path and returns them as a base64-encoded string. @param path

filebase64sha256(path) staticmethod

filebase64sha256 is a variant of base64sha256 that hashes the contents of a given file rather than a literal string. @param path

filebase64sha512(path) staticmethod

filebase64sha512 is a variant of base64sha512 that hashes the contents of a given file rather than a literal string. @param path

fileexists(path) staticmethod

fileexists determines whether a file exists at a given path. @param path

filemd5(path) staticmethod

filemd5 is a variant of md5 that hashes the contents of a given file rather than a literal string. @param path

fileset(path, pattern) staticmethod

fileset enumerates a set of regular file names given a path and pattern. The path is automatically removed from the resulting set of file names and any result still containing path separators always returns forward slash (/) as the path separator for cross-system compatibility. @param path @param pattern

filesha1(path) staticmethod

filesha1 is a variant of sha1 that hashes the contents of a given file rather than a literal string. @param path

filesha256(path) staticmethod

filesha256 is a variant of sha256 that hashes the contents of a given file rather than a literal string. @param path

filesha512(path) staticmethod

filesha512 is a variant of sha512 that hashes the contents of a given file rather than a literal string. @param path

flatten(list_) staticmethod

flatten takes a list and replaces any elements that are lists with a flattened sequence of the list contents. @param list_

floor(num) staticmethod

floor returns the closest whole number that is less than or equal to the given value, which may be a fraction. @param num

format_(format_, *args) staticmethod

The format function produces a string by formatting a number of other values according to a specification string. It is similar to the printf function in C, and other similar functions in other programming languages. @param format_ @param *args

formatdate(format_, time) staticmethod

formatdate converts a timestamp into a different time format. @param format_ @param time

formatlist(format_, *args) staticmethod

formatlist produces a list of strings by formatting a number of other values according to a specification string. @param format_ @param *args

indent(spaces, str_) staticmethod

indent adds a given number of spaces to the beginnings of all but the first line in a given multi-line string. @param spaces Number of spaces to add after each newline character. @param str_

index(list_, value) staticmethod

index finds the element index for a given value in a list. @param list_ @param value

issensitive(value) staticmethod

issensitive takes a value and returns a boolean indicating if the value is sensitive. @param value

join(separator, *lists) staticmethod

join produces a string by concatenating together all elements of a given list of strings with the given delimiter. @param separator Delimiter to insert between the given strings. @param *lists One or more lists of strings to join.

jsondecode(str_) staticmethod

jsondecode interprets a given string as JSON, returning a representation of the result of decoding that string. @param str_

jsonencode(val) staticmethod

jsonencode encodes a given value to a string using JSON syntax. @param val

keys(inputMap) staticmethod

keys takes a map and returns a list containing the keys from that map. @param inputMap The map to extract keys from. May instead be an object-typed value, in which case the result is a tuple of the object attributes.

length(value) staticmethod

length determines the length of a given list, map, or string. @param value

log(num, base) staticmethod

log returns the logarithm of a given number in a given base. @param num @param base

lookup(inputMap, key, *default) staticmethod

lookup retrieves the value of a single element from a map, given its key. If the given key does not exist, the given default value is returned instead. @param inputMap @param key @param *default

lower(str_) staticmethod

lower converts all cased letters in the given string to lowercase. @param str_

map(**kwargs) staticmethod

Creates a map from keyword arguments.

matchkeys(values, keys, searchset) staticmethod

matchkeys constructs a new list by taking a subset of elements from one list whose indexes match the corresponding indexes of values in another list. @param values @param keys @param searchset

max_(*numbers) staticmethod

max takes one or more numbers and returns the greatest number from the set. @param *numbers

md5(str_) staticmethod

md5 computes the MD5 hash of a given string and encodes it with hexadecimal digits. @param str_

merge(*maps) staticmethod

merge takes an arbitrary number of maps or objects, and returns a single map or object that contains a merged set of elements from all arguments. @param *maps

min_(*numbers) staticmethod

min takes one or more numbers and returns the smallest number from the set. @param *numbers

nonsensitive(value) staticmethod

nonsensitive takes a sensitive value and returns a copy of that value with the sensitive marking removed, thereby exposing the sensitive value. @param value

one(list_) staticmethod

one takes a list, set, or tuple value with either zero or one elements. If the collection is empty, one returns null. Otherwise, one returns the first element. If there are two or more elements then one will return an error. @param list_

parseint(number, base) staticmethod

parseint parses the given string as a representation of an integer in the specified base and returns the resulting number. The base must be between 2 and 62 inclusive. @param number @param base

pathexpand(path) staticmethod

pathexpand takes a filesystem path that might begin with a ~ segment, and if so it replaces that segment with the current user's home directory path. @param path

plantimestamp() staticmethod

plantimestamp returns a UTC timestamp string in RFC 3339 format, fixed to a constant time representing the time of the plan.

pow_(num, power) staticmethod

pow calculates an exponent, by raising its first argument to the power of the second argument. @param num @param power

range_(*params) staticmethod

range generates a list of numbers using a start value, a limit value, and a step value. @param *params

regex(pattern, string) staticmethod

regex applies a regular expression to a string and returns the matching substrings. @param pattern @param string

regexall(pattern, string) staticmethod

regexall applies a regular expression to a string and returns a list of all matches. @param pattern @param string

replace(str_, substr, replace) staticmethod

replace searches a given string for another given substring, and replaces each occurrence with a given replacement string. @param str_ @param substr @param replace

reverse(list_) staticmethod

reverse takes a sequence and produces a new sequence of the same length with all of the same elements as the given sequence but in reverse order. @param list_

rsadecrypt(ciphertext, privatekey) staticmethod

rsadecrypt decrypts an RSA-encrypted ciphertext, returning the corresponding cleartext. @param ciphertext @param privatekey

sensitive(value) staticmethod

sensitive takes any value and returns a copy of it marked so that Terraform will treat it as sensitive, with the same meaning and behavior as for sensitive input variables. @param value

setintersection(first_set, *other_sets) staticmethod

The setintersection function takes multiple sets and produces a single set containing only the elements that all of the given sets have in common. In other words, it computes the intersection of the sets. @param first_set @param *other_sets

setproduct(*sets) staticmethod

The setproduct function finds all of the possible combinations of elements from all of the given sets by computing the Cartesian product. @param *sets The sets to consider. Also accepts lists and tuples, and if all arguments are of list or tuple type then the result will preserve the input ordering

setsubtract(a, b) staticmethod

The setsubtract function returns a new set containing the elements from the first set that are not present in the second set. In other words, it computes the relative complement of the second set. @param a @param b

setunion(first_set, *other_sets) staticmethod

The setunion function takes multiple sets and produces a single set containing the elements from all of the given sets. In other words, it computes the union of the sets. @param first_set @param *other_sets

sha1(str_) staticmethod

sha1 computes the SHA1 hash of a given string and encodes it with hexadecimal digits. @param str_

sha256(str_) staticmethod

sha256 computes the SHA256 hash of a given string and encodes it with hexadecimal digits. @param str_

sha512(str_) staticmethod

sha512 computes the SHA512 hash of a given string and encodes it with hexadecimal digits. @param str_

signum(num) staticmethod

signum determines the sign of a number, returning a number between -1 and 1 to represent the sign. @param num

slice_(list_, start_index, end_index) staticmethod

slice extracts some consecutive elements from within a list. @param list_ @param start_index @param end_index

sort(list_) staticmethod

sort takes a list of strings and returns a new list with those strings sorted lexicographically. @param list_

split(separator, str_) staticmethod

split produces a list by dividing a given string at all occurrences of a given separator. @param separator @param str_

startswith(str_, prefix) staticmethod

startswith takes two values: a string to check and a prefix string. The function returns true if the string begins with that exact prefix. @param str_ @param prefix

strcontains(str_, substr) staticmethod

strcontains takes two values: a string to check and an expected substring. The function returns true if the string has the substring contained within it. @param str_ @param substr

strrev(str_) staticmethod

strrev reverses the characters in a string. Note that the characters are treated as Unicode characters (in technical terms, Unicode grapheme cluster boundaries are respected). @param str_

substr(str_, offset, length) staticmethod

substr extracts a substring from a given string by offset and (maximum) length. @param str_ @param offset @param length

sum_(list_) staticmethod

sum takes a list or set of numbers and returns the sum of those numbers. @param list_

templatefile(path, vars_) staticmethod

templatefile reads the file at the given path and renders its content as a template using a supplied set of template variables. @param path @param vars_

templatestring(template, vars_) staticmethod

templatestring takes a string from elsewhere in the module and renders its content as a template using a supplied set of template variables. @param template A simple reference to a string value containing the template source code. @param vars_ Object of variables to expose in the template scope.

textdecodebase64(source, encoding) staticmethod

textdecodebase64 function decodes a string that was previously Base64-encoded, and then interprets the result as characters in a specified character encoding. @param source @param encoding

textencodebase64(string, encoding) staticmethod

textencodebase64 encodes the unicode characters in a given string using a specified character encoding, returning the result base64 encoded because Terraform language strings are always sequences of unicode characters. @param string @param encoding

timeadd(timestamp, duration) staticmethod

timeadd adds a duration to a timestamp, returning a new timestamp. @param timestamp @param duration

timecmp(timestamp_a, timestamp_b) staticmethod

timecmp compares two timestamps and returns a number that represents the ordering of the instants those timestamps represent. @param timestamp_a @param timestamp_b

timestamp() staticmethod

timestamp returns a UTC timestamp string in RFC 3339 format.

title(str_) staticmethod

title converts the first letter of each word in the given string to uppercase. @param str_

tobool(v) staticmethod

tobool converts its argument to a boolean value. @param v

tolist(v) staticmethod

tolist converts its argument to a list value. @param v

tomap(v) staticmethod

tomap converts its argument to a map value. @param v

tonumber(v) staticmethod

tonumber converts its argument to a number value. @param v

toset(v) staticmethod

toset converts its argument to a set value. @param v

tostring(v) staticmethod

tostring converts its argument to a string value. @param v

transpose(values) staticmethod

transpose takes a map of lists of strings and swaps the keys and values to produce a new map of lists of strings. @param values

trim(str_, cutset) staticmethod

trim removes the specified set of characters from the start and end of the given string. @param str_ @param cutset A string containing all of the characters to trim. Each character is taken separately, so the order of characters is insignificant.

trimprefix(str_, prefix) staticmethod

trimprefix removes the specified prefix from the start of the given string. If the string does not start with the prefix, the string is returned unchanged. @param str_ @param prefix

trimspace(str_) staticmethod

trimspace removes any space characters from the start and end of the given string. @param str_

trimsuffix(str_, suffix) staticmethod

trimsuffix removes the specified suffix from the end of the given string. @param str_ @param suffix

type(value) staticmethod

Determine the type of a given value.

upper(str_) staticmethod

upper converts all cased letters in the given string to uppercase. @param str_

urlencode(str_) staticmethod

urlencode applies URL encoding to a given string. @param str_

uuid() staticmethod

uuid generates a unique identifier string.

uuidv5(namespace, name) staticmethod

uuidv5 generates a name-based UUID, as described in RFC 4122 section 4.3, also known as a "version 5" UUID. @param namespace @param name

values(mapping) staticmethod

values takes a map and returns a list containing the values of the elements in that map. @param mapping

yamldecode(src) staticmethod

yamldecode parses a string as a subset of YAML, and produces a representation of its value. @param src

yamlencode(value) staticmethod

yamlencode encodes a given value to a string using YAML 1.2 block syntax. @param value

zipmap(keys, values) staticmethod

zipmap constructs a map from a list of keys and a corresponding list of values. @param keys @param values

Bases: ABC

Concrete base class for runtime values.

eq(other)

Whether this value equals another (Terraform's ==).

evaluate() abstractmethod

Evaluate the runtime value (expression nodes also take an expressions.Environment).

get_dependencies() abstractmethod

Get other runtime values this value depends on.

ne(other)

Whether this value differs from another (Terraform's !=).

resolve(context) abstractmethod

Resolve this value to its concrete type.

Backends

Bases: Backend

Local file backend.

Example

backend = LocalBackend( nf_scope=stack, nf_id="local", path="./terraform.tfstate" )

backend_type property

Get backend type.

nf_backend_settings property

Framework-owned backend settings.

BootstrapPolicy

Bases: StrEnum

Policy for backend bootstrapping.

__init__(*, nf_scope, nf_id, path=None, workspace_dir=None, nf_backend_settings=None)

Initialize local backend.

Parameters:

Name Type Description Default
nf_scope BaseConstruct

Parent stack

required
nf_id str

Backend ID

required
path str | None

Path to the state file

None
workspace_dir str | None

Directory for workspace state files

None
nf_backend_settings BackendSettings | None

Framework-owned backend settings

None

bootstrap_ready()

Local backend does not require bootstrapping.

create_bootstrap_resources(stack)

Create any resources needed to bootstrap this backend.

Override in subclasses to create necessary resources like S3 buckets.

get_bootstrapper()

Return a bootstrapper for this backend if supported.

Backends should override this to provide a provider-specific bootstrapper.

get_resource_dependencies()

Return any in-stack resource dependencies for backend selection.

get_state_resources()

Get list of resources from local state file.

has_state()

Check if local state file exists.

resolve_literal(value, field_name, *, resource_attrs=None, allow_none=False)

Resolve backend configuration values to literal strings.

resource_exists_at_address(address)

Check if resource exists in local state file.

to_hcl()

Convert to HCL configuration.

Bases: Backend

A chain of backends with automatic fallback based on dependency availability.

This solves the bootstrap problem by allowing you to specify multiple backends in priority order, or provide a custom selector function. The chain will automatically select the first backend whose dependencies are satisfied.

Example

Try S3 backend first, fall back to local if S3 bucket doesn't exist

BackendChain( nf_scope=stack, nf_id="backend_chain", backends=[ S3Backend( nf_scope=stack, nf_id="s3", bucket=my_bucket, nf_backend_settings=BackendSettings(register=False), ..., ), # Depends on my_bucket Resource LocalBackend( nf_scope=stack, nf_id="local", nf_backend_settings=BackendSettings(register=False), ) # No dependencies, always available ] )

backend_type property

Get the backend type name.

nf_backend_settings property

Framework-owned backend settings.

BootstrapPolicy

Bases: StrEnum

Policy for backend bootstrapping.

__init__(*, nf_scope, nf_id, backends=None, selector=None, nf_backend_settings=None, **kwargs)

Initialize backend chain.

Parameters:

Name Type Description Default
nf_scope Stack

Parent stack

required
nf_id str

Backend ID

required
backends list[Backend] | None

List of backends in priority order (required if selector is not set)

None
selector Callable[[BackendChain], BackendSelection] | None

Optional callable to select a backend. Must return a BackendSelection.

None
**kwargs Any

Additional configuration

{}

add_migration_outputs()

Add outputs to help with backend migration.

bootstrap_ready()

Return whether the chain has an eligible backend for bootstrapping.

bootstrap_resources(*, policy=Backend.BootstrapPolicy.IF_MISSING, dry_run=False)

Bootstrap backend resources for the chain if supported.

create_bootstrap_resources(stack)

Create any resources needed to bootstrap this backend.

Override in subclasses to create necessary resources like S3 buckets.

get_bootstrapper()

Return a bootstrapper for this backend if supported.

Backends should override this to provide a provider-specific bootstrapper.

get_migration_status()

Get the current migration status.

Returns:

Type Description
dict[str, Any]

Dictionary with migration status information

get_resource_dependencies()

Return any in-stack resource dependencies for backend selection.

get_state_resources()

Get list of resources from the backend's state.

Returns:

Type Description
list[dict[str, Any]] | None

List of resource dicts from state, or None if can't determine

has_state()

Check if this backend has an existing state file.

Returns:

Type Description
bool

True if state exists, False otherwise

resolve()

Resolve backend selection and bootstrap recommendations.

resolve_literal(value, field_name, *, resource_attrs=None, allow_none=False)

Resolve backend configuration values to literal strings.

resource_exists_at_address(address)

Check if a resource exists at the given address in state.

Returns:

Type Description
bool | None

True if resource exists, False if not, None if can't determine

select_backend()

Select the appropriate backend from the chain.

Selection algorithm: 1. First, check if any backend already has state (was previously used) 2. Then, select the first backend with satisfied dependencies 3. Finally, fall back to the last backend (assumed to be simplest)

Returns:

Type Description
Backend

The selected backend

Raises:

Type Description
BackendError

If no suitable backend is found

should_migrate()

Check if migration is recommended.

Returns True if: - A higher-priority backend now has satisfied dependencies - But we're currently using a lower-priority backend with state

to_hcl()

Convert to HCL configuration.