Provider Protocol and gRPC Communication
This document describes how Netherframe communicates with Terraform providers using the gRPC-based provider protocol, enabling direct provider interaction without the Terraform CLI.
Overview
The Terraform Provider Protocol is a gRPC-based protocol that allows tools to communicate directly with Terraform providers. Netherframe implements this protocol to:
- Configure providers with credentials and settings
- Validate resource configurations
- Plan infrastructure changes
- Apply changes to create, update, or delete resources
- Import existing resources
Protocol Architecture
Protocol Version
Netherframe implements Provider Protocols v5 and v6 (the handshake says which a provider speaks), which support: - Enhanced type system - Improved error handling - Better performance - Nested attributes and blocks
Communication Flow
Netherframe Provider Binary
| |
|-- 1. Start Provider -------->|
|<---- Handshake Response -----|
| |
|-- 2. Configure Provider ---->|
|<---- Config Response --------|
| |
|-- 3. ValidateResourceConfig ->|
|<---- Validation Result ------|
| |
|-- 4. PlanResourceChange ----->|
|<---- Planned Changes ---------|
| |
|-- 5. ApplyResourceChange ---->|
|<---- New State --------------|
| |
|-- 6. Stop Provider --------->|
Implementation Details
Provider Protocol Client
The ProviderProtocolClient class handles all communication with provider binaries:
from nf.core.providers.provider_models import ProviderConfig
from nf.core.providers.provider_protocol import ProviderProtocolClient
# Create provider configuration
config = ProviderConfig(
name="hashicorp/aws",
version="5.0.0",
config={"region": "us-east-1"},
binary_path="/path/to/terraform-provider-aws", # omit it to have the provider installed
)
# Initialize client: nothing is started yet
client = ProviderProtocolClient(config)
def list_resource_types() -> list[str]:
# Entering the client starts the provider; leaving it stops it
with client:
return sorted(client.get_schema()["resources"])
Starting a Provider
Providers are started as a subprocess with the go-plugin handshake:
from nf.core.providers.provider_handshake import ProviderHandshake
handshake = ProviderHandshake("/path/to/terraform-provider-aws")
# The environment the provider is started with: the magic cookie and the protocol versions it may speak
environment = handshake.create_environment()
assert environment["PLUGIN_PROTOCOL_VERSIONS"] == "5,6"
# The provider answers on its stdout with: core version | protocol version | network | address | grpc
network, address = handshake.parse_handshake_line("1|6|tcp|127.0.0.1:12345|grpc")
assert (network, address) == ("tcp", "127.0.0.1:12345")
assert handshake.app_protocol_version == 6
# A line that is not a handshake raises ValueError
try:
handshake.parse_handshake_line("1|6|tcp|127.0.0.1:12345|netrpc")
except ValueError as error:
print(error)
ProviderSessionStartup launches the process with that environment, reads the line, opens a gRPC
channel to the address (a TCP port or a unix socket) and builds the stubs of the version the provider
announced.
Provider Configuration
After starting, providers must be configured with credentials:
from nf.core.providers.provider_protocol import ProviderProtocolClient
def configure(client: ProviderProtocolClient) -> None:
client.start_provider()
client.configure_provider({"region": "us-east-1"}) # raises ProviderError when the provider refuses
assert client.configured
Resource Operations
Validate Resource Configuration
from nf.core.providers.provider_protocol import ProviderProtocolClient
def validate(client: ProviderProtocolClient) -> list[str]:
"""The summaries of the errors the provider finds in a resource's configuration."""
return client.validate_resource_config("aws_s3_bucket", {"bucket": "logs"})
Plan Resource Changes
from nf.core.providers.provider_models import ResourceChange
from nf.core.providers.provider_protocol import ProviderProtocolClient
def plan(client: ProviderProtocolClient, prior_state: dict | None, config: dict) -> ResourceChange:
"""Plan a change to a bucket; ``prior_state`` is None when it does not exist yet."""
change = client.plan_resource_change("aws_s3_bucket", prior_state, config, config)
print(change.action, change.requires_replace, change.planned_state)
return change
Apply Resource Changes
from nf.core.providers.provider_models import ObjectState, ResourceChange
from nf.core.providers.provider_protocol import ProviderProtocolClient
def apply(client: ProviderProtocolClient, change: ResourceChange, config: dict) -> ObjectState | None:
"""Apply a planned change: create, update or, with no planned state, delete."""
return client.apply_resource_change(change.resource_type, change.prior_state, change.planned_state, config)
Private Data and Resource Identity
A provider returns, beside an object's state, its private data (opaque bytes it reads back
itself) and the object's resource identity. Terraform keeps both with the object in state and
sends them back with the object's next plan, apply and read; so does ProviderProtocolClient:
from dataclasses import dataclass, field
from typing import Any
from nf.core.providers.provider_protocol import ProviderProtocolClient
@dataclass
class Entry:
"""What state keeps of an object: its attributes and what the provider returned beside them."""
attributes: dict[str, Any]
private: bytes = b""
identity: dict[str, Any] | None = None
other: dict[str, Any] = field(default_factory=dict)
def roundtrip(client: ProviderProtocolClient, entry: Entry, proposed: dict[str, Any], config: dict[str, Any]) -> None:
change = client.plan_resource_change("aws_s3_bucket", entry.attributes, proposed, config, prior_private=entry.private, prior_identity=entry.identity)
new_state = client.apply_resource_change("aws_s3_bucket", entry.attributes, change.planned_state, config, planned_private=change.planned_private, planned_identity=change.planned_identity)
new_state.private, new_state.identity, new_state.identity_schema_version # an ObjectState: the state dict, with what came beside it
read = client.read_resource("aws_s3_bucket", entry.attributes, private=entry.private, current_identity=entry.identity)
[imported], _private = client.import_resource_state("aws_s3_bucket", identity={"bucket": "logs"})
imported["private"], imported["identity"]
Identities are encoded and decoded against the resource type's identity schema
(GetResourceIdentitySchemas), fetched once, the first time an identity is sent or returned;
providers without identities never fetch it. Both protocol versions (5 and 6) carry them.
move_resource_state sends the source's private data and identity and returns the target's.
Data Encoding
The provider protocol uses a special DynamicValue format that combines MessagePack-encoded data with type information:
Encoding Values
from nf.core.serialization.cty_msgpack import CtyMsgpackDecoder, schema_implied_type
from nf.core.serialization.message_encoding import MessageEncoder
schema = {"attributes": {"bucket": {"type": "string"}, "force_destroy": {"type": "bool"}, "versions": {"type": "number"}}}
implied_type = schema_implied_type(schema)
value = {"bucket": "logs", "force_destroy": False, "versions": 3}
# A DynamicValue message of the protocol version (5 or 6), its msgpack typed as go-cty types it
message = MessageEncoder.encode_dynamic_value(value, protocol_version=6, implied_type=implied_type)
assert MessageEncoder.decode_dynamic_value(message, decoder=CtyMsgpackDecoder(implied_type)) == value
Encoded against the type a resource's schema implies (implied_type=), a number is a number and a
set a set, as the provider expects. Without a type, the value is encoded as a dynamically typed
value: [type JSON, value].
Decoding Values
Providers encode values against the type their schema implies (go-cty's
msgpack.Marshal), and the client decodes them against that same type with
CtyMsgpackDecoder (netherframe.core.serialization.cty_msgpack), as go-cty's
msgpack.Unmarshal does:
- an unknown value (msgpack extension 0, or 0x0C with refinements, which are
dropped) is
UNKNOWN, apart from null (None) - a number go-cty sent as text, one fitting neither int64 nor float64 exactly,
is an
int(or afloatwhen it has a fraction); the encoder sends an integer beyond int64 as text the same way - a dynamically typed value, sent as
[type JSON, value], is its value decoded against that type - lists, sets and tuples are lists, maps and objects dicts; nested blocks follow their nesting
Each client keeps one decoder per schema entry (SchemaTypes.decoder), next to
the implied type it encodes with. Planned states keep their unknown values;
applied, read and imported states never hold one (an unknown value there is a
provider bug, kept as null with a warning, as Terraform keeps it).
import msgpack
from nf.core.providers.provider_value_shaper import SchemaTypes
from nf.core.serialization.cty_msgpack import UNKNOWN
entry = {"attributes": {"bucket": {"type": "string"}, "arn": {"type": "string", "computed": True}}}
types = SchemaTypes(entry) # the operation context keeps one per schema entry: context.resource_types("aws_s3_bucket")
# What a provider planning a bucket that does not exist yet sends: the arn is an unknown value
planned = msgpack.packb({"bucket": "logs", "arn": msgpack.ExtType(0, b"")})
planned_state = types.decoder.decode(planned)
assert planned_state["arn"] is UNKNOWN # a bucket being created: known only after apply
Type Conversions
| Python Type | MessagePack Type | Notes |
|---|---|---|
| str | string | UTF-8 encoded |
| int | integer | 64-bit |
| float | float | Double precision |
| bool | boolean | |
| list | array | |
| dict | map | String keys only |
| None | nil | |
| bytes | binary | For sensitive data |
Provider Registry
The ProviderRegistry manages multiple provider instances:
from nf.core.providers.provider_models import ProviderConfig
from nf.core.providers.provider_registry import ProviderRegistry
class FakeClient:
"""Stands in for a provider process: what the registry asks of a client."""
def __init__(self, config: ProviderConfig) -> None:
self.config = config
self.configured = False
self.running = False
def start_provider(self) -> None:
self.running = True
def configure_provider(self, config: dict) -> None:
self.configured = True
def stop_provider(self) -> None:
self.running = False
with ProviderRegistry(client_factory=FakeClient) as registry:
east = registry.register_provider(ProviderConfig("hashicorp/aws", "5.0.0", {"region": "us-east-1"}), key="aws")
same = registry.register_provider(ProviderConfig("hashicorp/aws", "5.0.0", {"region": "us-east-1"}), key="aws.again")
west = registry.register_provider(ProviderConfig("hashicorp/aws", "5.0.0", {"region": "us-west-2"}), key="aws.west", alias="west")
assert same is east # identical provider, version and settings share one client
assert west is not east
assert registry.get_provider("aws.west") is west
Leaving the with block (or stop_all()) stops every client. Without key=, a client is kept under
<name>:<version>.
Error Handling
Provider Diagnostics
Providers return diagnostics with severity levels:
from types import SimpleNamespace
from nf.core.providers.provider_rpc_support import ProviderRpcSupport
# A response as a provider returns it: severity 1 is an error, 2 a warning
response = SimpleNamespace(
diagnostics=[
SimpleNamespace(severity=1, summary="Invalid bucket name", detail="names are lowercase"),
SimpleNamespace(severity=2, summary="Deprecated argument", detail=""),
]
)
assert ProviderRpcSupport.summary_errors(response) == ["Invalid bucket name: names are lowercase"]
assert ProviderRpcSupport.redacted_errors(response, secrets=("lowercase",)) == ["Invalid bucket name: names are (sensitive value)"]
assert ProviderRpcSupport.detailed_errors(response) == ["Invalid bucket name: names are lowercase"]
A client raises ProviderError for the errors of a call. ProviderRpcSupport.redacted_errors and
ProviderRpcSupport.summary_errors include the attribute path, summary, and detail while scrubbing
registered sensitive values and Bearer tokens; ProviderRpcSupport.apply_errors combines those
redacted diagnostics with categorized hints. A provider's errors that come with the state of the object
it changed are a ProviderApplyError, whose new_state apply records.
Common Error Types
- Configuration Errors: Invalid provider configuration
- Validation Errors: Resource configuration doesn't match schema
- API Errors: Cloud provider API failures
- State Errors: Conflicts or inconsistencies in state
- Permission Errors: Insufficient permissions for operations
Provider Binary Management
Provider Loader
The ProviderLoader handles downloading and caching provider binaries:
import tempfile
from pathlib import Path
from nf.core.providers.provider_loader import ProviderLoader
with tempfile.TemporaryDirectory() as cache:
loader = ProviderLoader(cache_dir=Path(cache))
# Nothing is installed in an empty cache
assert loader.get_provider_path("hashicorp", "aws", "5.0.0") is None
def install(loader: ProviderLoader) -> Path:
"""Resolve a version constraint and install the release if the cache lacks it."""
return loader.download_provider("hashicorp", "aws", "~> 5.0")
ProviderLoader.load_provider(config) does this for a ProviderConfig without a binary_path and
returns the config with it set. The cache is provider_cache_dir (default ~/.nf/providers).
Provider Discovery
The versions of a provider are listed from the Terraform Registry or the mirrors the settings name:
from nf.sdk.provider_versions import fetch_all_versions, fetch_latest_version
def versions() -> tuple[list[str] | None, str | None]:
"""The versions the registry or a mirror offers, and the latest."""
return fetch_all_versions("hashicorp/aws"), fetch_latest_version("hashicorp/aws")
Security Considerations
Provider Isolation
- Providers run as separate processes with limited permissions
- Communication is over local gRPC (no network exposure)
- Each provider has its own process space
Credential Handling
import os
from nf.core.providers.provider_models import ProviderConfig
# Best practices for provider credentials
config = ProviderConfig(
name="hashicorp/aws",
version="5.0.0",
config={
# Use environment variables
"region": os.getenv("AWS_REGION", "us-east-1"),
# Or credential files
"shared_credentials_files": ["~/.aws/credentials"],
# Never hardcode credentials
},
)
Binary Verification
import tempfile
import zipfile
from pathlib import Path
from nf.core.providers.installation.authentication import ArchiveChecksum, zip_hash
from nf.core.providers.installation.errors import AuthenticationFailed
with tempfile.TemporaryDirectory() as directory:
package = Path(directory) / "terraform-provider-aws_5.0.0_linux_amd64.zip"
with zipfile.ZipFile(package, "w") as archive:
archive.writestr("terraform-provider-aws_v5.0.0", b"binary")
# The registry lists the archive's SHA-256; the installer checks the download against it
expected = zip_hash(package).removeprefix("zh:")
result = ArchiveChecksum("hashicorp/aws", expected)(package)
assert result.trust == "verified checksum"
try:
ArchiveChecksum("hashicorp/aws", "0" * 64)(package)
except AuthenticationFailed as error:
print(error)
Installation checks more than the archive: the SHA256SUMS document and its signature, against
HashiCorp's keys (netherframe.core.providers.installation.keys).
Performance Optimization
Connection Pooling
Reuse gRPC connections for multiple operations:
from nf.core.providers.provider_models import ProviderConfig
from nf.core.providers.provider_registry import ProviderRegistry
registry = ProviderRegistry()
def client_for(region: str):
"""Clients are not made per call: a registry returns the one of the same provider, version and settings."""
config = ProviderConfig("hashicorp/aws", "5.0.0", {"region": region})
return registry.register_provider(config, key=f"aws.{region}")
start_all() and stop_all() start and stop every client in parallel, and a configuration is
started and configured once however many threads register it.
Batch Operations
Process multiple resources in parallel:
import anyio
import anyio.to_thread
from nf.core.providers.provider_models import ObjectState, ResourceChange
from nf.core.providers.provider_protocol import ProviderProtocolClient
async def apply_resources_batch(provider: ProviderProtocolClient, changes: list[tuple[ResourceChange, dict]]) -> list[ObjectState | None]:
"""Apply multiple resource changes in parallel: each change with the configuration it was planned from."""
results: list[ObjectState | None] = []
async def run_change(change: ResourceChange, config: dict) -> None:
result = await anyio.to_thread.run_sync(
provider.apply_resource_change,
change.resource_type,
change.prior_state,
change.planned_state,
config,
)
results.append(result)
async with anyio.create_task_group() as tg:
for change, config in changes:
tg.start_soon(run_change, change, config)
return results
An app's apply does this itself, bounded by max_concurrent_resources, in dependency order.
Debugging
Enable gRPC Logging
import logging
import grpc
def enable_grpc_logging() -> None:
# Enable gRPC debug logging
grpc_logger = logging.getLogger("grpc")
grpc_logger.setLevel(logging.DEBUG)
grpc_logger.addHandler(logging.StreamHandler())
Trace Provider Communication
from nf.core.logging import get_logger
from nf.core.providers.provider_protocol import ProviderProtocolClient
logger = get_logger(__name__)
class TracingProviderClient(ProviderProtocolClient):
"""Provider client with request/response tracing."""
def plan_resource_change(self, *args, **kwargs):
logger.debug(f"PlanResourceChange request: {args}, {kwargs}")
result = super().plan_resource_change(*args, **kwargs)
logger.debug(f"PlanResourceChange response: {result}")
return result
Provider Process Monitoring
from nf.core.logging import get_logger
from nf.core.providers.provider_protocol import ProviderProtocolClient
logger = get_logger(__name__)
def monitor_provider_process(client: ProviderProtocolClient) -> None:
"""Report a provider process that has died."""
process = client.provider_process
if process is not None and process.poll() is not None:
logger.error(f"Provider process died with code: {process.returncode}")
Protocol Extensions
Custom RPC Methods
Some providers support additional RPC methods:
from typing import Any
from nf.core.providers.provider_protocol import ProviderProtocolClient
def import_resource(client: ProviderProtocolClient, resource_type: str, resource_id: str) -> dict[str, Any]:
"""Import an existing resource: its state, with the private data and identity the provider returned."""
[imported], _private = client.import_resource_state(resource_type, resource_id)
return imported["state"]
Provider Capabilities
Query provider capabilities:
from typing import Any
from nf.core.providers.provider_protocol import ProviderProtocolClient
def provider_schema(client: ProviderProtocolClient) -> dict[str, Any]:
"""The provider's schema: its own, and that of its resources and data sources, by type name."""
schema = client.get_schema()
return {"provider": schema["provider"], "resources": schema["resources"], "data_sources": schema["data_sources"]}
Future Enhancements
- Provider Protocol v7: Support for the next protocol version
- Streaming Operations: Real-time progress updates during apply
- Provider Caching: Smarter caching of provider responses
- Metrics Collection: Performance metrics for provider operations
- Provider Plugins: Allow custom provider implementations