Build your first reusable construct
In this tutorial you will refactor repeated S3 bucket declarations out of a single script
into a reusable StorageStack module with a small, explicit Python interface, and verify
it with nf plan.
Before you start: Complete Tutorial 1 and install AWS bindings with AWS credentials configured for planning.
Step 1: Create the package layout
my-infra/
pyproject.toml
app.py
constructs/
__init__.py
storage.py
Create an empty constructs/__init__.py so Python treats constructs/ as a package.
Step 2: Define the reusable stack in constructs/storage.py
Provider-backed resources belong to a Stack, so a focused Stack subclass is the
cleanest reusable unit for a cohesive infrastructure domain:
from nf.core import App, Output, Stack
from nf.providers.hashicorp.aws import AwsProvider, S3Bucket
class StorageStack(Stack):
def __init__(
self,
*,
nf_scope: App,
nf_id: str,
region: str,
assets_bucket_name: str,
logs_bucket_name: str,
) -> None:
super().__init__(nf_scope=nf_scope, nf_id=nf_id)
AwsProvider(nf_scope=self, nf_id="aws", region=region)
self.assets = S3Bucket(
nf_scope=self,
nf_id="assets",
bucket=assets_bucket_name,
force_destroy=True,
)
self.logs = S3Bucket(
nf_scope=self,
nf_id="logs",
bucket=logs_bucket_name,
force_destroy=True,
)
Output(nf_scope=self, nf_id="assets_bucket_id", value=self.assets.output.id)
Output(nf_scope=self, nf_id="logs_bucket_id", value=self.logs.output.id)
Step 3: Instantiate StorageStack from app.py
from constructs.storage import StorageStack
from nf.core import App
app = App(nf_id="platform")
storage = StorageStack(
nf_scope=app,
nf_id="storage",
region="us-east-1",
assets_bucket_name="replace-with-a-globally-unique-name",
logs_bucket_name="replace-with-a-second-globally-unique-name",
)
app.enable_hybrid_execution_local(path=".nf.out/hybrid.tfstate")
Register the app in pyproject.toml:
[tool.nf]
apps = ["app:app"]
Step 4: Verify the plan
Substitute two globally unique bucket names in app.py and run:
nf plan --app app
Confirm that the plan shows storage.aws_s3_bucket.assets, storage.aws_s3_bucket.logs,
and both outputs under the storage stack.
Next steps
- Write an offline unit test for
StorageStack: Test an app without cloud credentials. - Learn reusable design guidelines: Author reusable constructs and Provider patterns.