Backend Bootstrapping
Overview
Backend bootstrapping is the process of creating the infrastructure needed to store your infrastructure state. This creates a circular dependency: you need infrastructure to store the state of your infrastructure.
The Challenge
When using remote state backends like AWS S3, you typically need: - An S3 bucket to store the state file - A DynamoDB table for state locking - Proper permissions and configuration
But these resources must be created by Terraform, which needs somewhere to store its state while creating them.
Traditional Approaches
1. Manual Pre-Creation
Create backend resources manually:
aws s3 mb s3://my-terraform-state
aws dynamodb create-table --table-name my-terraform-locks ...
Pros: Simple, works immediately
Cons: Not infrastructure-as-code, manual process, drift risk
2. Separate Bootstrap Stack
Create a dedicated stack for backend resources:
from nf.backends.aws import S3Backend
from nf.core import App, BackendSettings, Stack
from nf.providers.hashicorp.aws import S3Bucket
app = App(nf_id="infra")
# The bootstrap stack creates the bucket
bootstrap_stack = Stack(nf_scope=app, nf_id="bootstrap")
S3Bucket(nf_scope=bootstrap_stack, nf_id="state", bucket="my-state")
# The main stack stores its state in it, so it is applied after the bootstrap stack
main_stack = Stack(nf_scope=app, nf_id="main")
S3Backend(
nf_scope=main_stack,
nf_id="s3-backend",
bucket="my-state",
nf_backend_settings=BackendSettings(register=False),
)
Pros: Resources in code
Cons: Complex dependency management, two-step deployment
3. Manual Configuration Toggle
Comment/uncomment backend configuration:
# Step 1: Comment out backend
# backend = S3Backend(nf_scope=stack, ...)
# Step 2: Apply to create resources
# Step 3: Uncomment backend
# Step 4: Migrate state
Pros: Single stack, resources in code
Cons: Manual process, error-prone, not CI/CD friendly
The Netherframe Solution: BackendChain
BackendChain automates the manual toggle approach:
from nf.backends.aws import S3Backend
from nf.core import App, BackendChain, BackendSettings, LocalBackend, Stack
app = App(nf_id="infra")
stack = Stack(nf_scope=app, nf_id="main")
backend = BackendChain(
nf_scope=stack,
nf_id="backend",
backends=[
# Try this first
S3Backend(
nf_scope=stack,
nf_id="s3",
bucket="my-state",
nf_backend_settings=BackendSettings(register=False),
),
# Fall back to this
LocalBackend(
nf_scope=stack,
nf_id="local",
nf_backend_settings=BackendSettings(register=False),
),
],
)
Terraform backend configuration requires literal strings. You can pass Resource
objects (for example, bucket=state_bucket) as long as their input attributes
are literal. Output references like state_bucket.output.id are not supported
for Terraform backends.
How It Works
- Automatic Detection: Checks if backend resources exist
- Smart Selection: Chooses first backend with satisfied dependencies
- State Persistence: Remembers selection for migration
- Zero Manual Steps: No code changes between runs
Implementation Details
The BackendChain: - Evaluates backends in order - Checks resource dependencies - Persists selection to disk - Provides migration helpers
You can also resolve the backend decision and optionally bootstrap resources when the selected backend supports it:
from nf.backends.aws import S3Backend
from nf.core import App, BackendChain, BackendSettings, LocalBackend, Stack
from nf.core.constructs.backend_base import Backend
app = App(nf_id="infra")
stack = Stack(nf_scope=app, nf_id="main")
backend = BackendChain(
nf_scope=stack,
nf_id="backend",
backends=[
S3Backend(nf_scope=stack, nf_id="s3", bucket="my-state", nf_backend_settings=BackendSettings(register=False)),
LocalBackend(nf_scope=stack, nf_id="local", nf_backend_settings=BackendSettings(register=False)),
],
)
def bootstrap() -> None:
# Checks for the bucket, so it needs AWS credentials
decision = backend.resolve()
result = backend.bootstrap_resources(
policy=Backend.BootstrapPolicy.IF_MISSING,
dry_run=False,
)
print(result.action)
Bootstrapping only applies when the backend can be created out-of-band. If the backend depends on in-stack Resource objects, bootstrapping is skipped.
Native Mode Advantages
In hybrid execution mode, Netherframe can handle this even more elegantly:
from nf.backends.aws import S3Backend
from nf.core import App, BackendSettings, Stack
from nf.providers.hashicorp.aws import S3Bucket
app = App(nf_id="infra")
stack = Stack(nf_scope=app, nf_id="main")
# Hybrid mode can create resources and use them in the same run
app.enable_hybrid_execution()
state_bucket = S3Bucket(nf_scope=stack, nf_id="state", bucket="my-state-bucket")
backend = S3Backend(
nf_scope=stack,
nf_id="backend",
bucket="my-state-bucket",
nf_backend_settings=BackendSettings(register=False),
)
Hybrid mode benefits: - No Terraform backend limitations - Direct resource references - Automatic dependency ordering - Single-command deployment
Best Practices
1. Explicit Resource Names
Always use explicit names for backend resources:
from nf.core import App, Stack
from nf.providers.hashicorp.aws import S3Bucket
app = App(nf_id="infra")
stack = Stack(nf_scope=app, nf_id="main")
# Good
S3Bucket(nf_scope=stack, nf_id="state", bucket="mycompany-terraform-state-prod")
# Bad - might cause conflicts
S3Bucket(nf_scope=stack, nf_id="state_generic", bucket="terraform-state")
2. Environment Isolation
Separate backends per environment:
environment = "prod"
bucket = f"mycompany-terraform-state-{environment}"
table = f"mycompany-terraform-locks-{environment}"
3. Versioning and Backup
Enable versioning on S3 buckets:
from nf.core import App, Stack
from nf.providers.hashicorp.aws import S3Bucket, S3BucketVersioning
app = App(nf_id="infra")
stack = Stack(nf_scope=app, nf_id="main")
state_bucket = S3Bucket(nf_scope=stack, nf_id="state", bucket="my-state")
S3BucketVersioning(
nf_scope=stack,
nf_id="state_versioning",
bucket=state_bucket.output.id,
versioning_configuration={"status": "Enabled"},
)
4. Lifecycle Policies
Manage old state versions:
lifecycle_rule = [{"id": "expire-old-versions", "enabled": True, "noncurrent_version_expiration": {"days": 90}}]
Security Considerations
Encryption
Always encrypt state files:
from nf.backends.aws import S3Backend
from nf.core import App, Stack
app = App(nf_id="infra")
stack = Stack(nf_scope=app, nf_id="main")
S3Backend(
nf_scope=stack,
nf_id="encrypted-backend",
bucket="my-state",
encrypt=True, # Enable SSE
kms_key_id="alias/terraform-state", # Optional KMS
)
Access Control
Limit access to state files:
allowed_roles = ["arn:aws:iam::123456789012:role/state-writer"]
bucket_name = "mycompany-terraform-state-prod"
bucket_policy = {"Version": "2012-10-17", "Statement": [{"Effect": "Allow", "Principal": {"AWS": allowed_roles}, "Action": ["s3:GetObject", "s3:PutObject"], "Resource": f"arn:aws:s3:::{bucket_name}/*"}]}
State Locking
Always use DynamoDB for state locking:
from nf.backends.aws import S3Backend
from nf.core import App, Stack
app = App(nf_id="infra")
stack = Stack(nf_scope=app, nf_id="main")
S3Backend(
nf_scope=stack,
nf_id="locked-backend",
bucket="my-state",
dynamodb_table="terraform-locks", # Prevents concurrent modifications
)
Migration Strategies
Automated Migration
Use BackendChain's built-in helpers:
from nf.backends.aws import S3Backend
from nf.core import App, BackendChain, LocalBackend, Stack
app = App(nf_id="infra")
stack = Stack(nf_scope=app, nf_id="main")
backend = BackendChain(
nf_scope=stack,
nf_id="backend",
backends=[
S3Backend(nf_scope=stack, nf_id="s3", bucket="my-state"),
LocalBackend(nf_scope=stack, nf_id="local"),
],
)
backend.add_migration_outputs() # Adds helpful outputs
Manual Migration
If automatic migration fails:
1. Export current state: terraform state pull > state.json
2. Update backend configuration
3. Initialize new backend: terraform init -reconfigure
4. Import state: terraform state push state.json
Gradual Migration
For large teams: 1. Set up BackendChain 2. New deployments use remote backend automatically 3. Existing deployments migrate when convenient 4. Monitor persistence files to track progress
Troubleshooting
Common Issues
- Bucket Already Exists
- Use unique bucket names
-
Include account ID or timestamp
-
Permission Denied
- Check IAM policies
-
Verify credentials
-
State Lock Timeout
- Check DynamoDB table exists
-
Verify table permissions
-
Migration Fails
- Ensure both backends accessible
- Check for state locks
- Verify state file compatibility
Conclusion
Backend bootstrapping is a fundamental challenge in infrastructure-as-code. Netherframe's BackendChain provides an elegant solution that: - Automates the manual process - Maintains infrastructure-as-code principles - Supports gradual migration - Works with existing Terraform workflows
For new projects, start with BackendChain from day one. For existing projects, BackendChain enables smooth migration without disrupting current workflows.