Skip to content

Backend Construct Authoring Guide

This guide covers writing Terraform backend constructs (classes that inherit from Backend and generate Terraform backend configuration). It complements the state backend guide, which focuses on StateBackend implementations for hybrid execution.

Requirements

  • Subclass Backend
  • Implement backend_type (string identifier like "s3")
  • Implement to_hcl() returning a dict of Terraform backend configuration

Literal-Only Backend Configuration

Terraform backend configuration does not allow interpolations. Backend constructs must enforce literal strings. Use the helper on Backend:

from typing import Any

from nf.core.constructs.backend_base import Backend


class S3Backend(Backend):
    @property
    def backend_type(self) -> str:
        return "s3"

    def __init__(self, *, nf_scope, nf_id, bucket, **kwargs):
        super().__init__(nf_scope=nf_scope, nf_id=nf_id)
        self.bucket = self.resolve_literal(
            bucket,
            "bucket",
            resource_attrs=("bucket",),
            allow_none=False,
        )

    def to_hcl(self) -> dict[str, Any]:
        return {"bucket": self.bucket}

When a value cannot be resolved to a literal, BackendLiteralError is raised.

Resource Dependencies for BackendChain

BackendChain scans backend attributes for Resource objects to detect dependencies. If a backend accepts a Resource input but stores a literal string in its config, keep the original resource on a separate attribute:

from typing import Any

from nf.core.constructs.backend_base import Backend


class S3Backend(Backend):
    @property
    def backend_type(self) -> str:
        return "s3"

    def __init__(self, *, nf_scope, nf_id, bucket, **kwargs):
        super().__init__(nf_scope=nf_scope, nf_id=nf_id)
        self.bucket_resource = bucket if hasattr(bucket, "_is_resource") else None
        self.bucket = self.resolve_literal(bucket, "bucket", resource_attrs=("bucket",))

    def to_hcl(self) -> dict[str, Any]:
        return {"bucket": self.bucket}

This preserves dependency detection while keeping the backend config literal.

Registration

Register backend constructs with the registry (or use decorators). See Backend Plugin System for registration patterns and entry points.

Testing

At minimum:

  • Literal string inputs succeed
  • Resource inputs with literal attributes succeed
  • Runtime/output references raise BackendLiteralError
  • to_hcl() output is free of interpolations