Authoring an SC cloud plugin
An SC cloud plugin is a separate executable sc downloads and talks to over
a local gRPC bus. Plugins own:
- a cloud's config-tier types (auth, registrar, template, resource, VM
driver) — SC core parses
server.yamlthrough them; - the provisioning logic behind those types — the plugin registers Pulumi resources against the engine SC core already set up.
Eight plugins ship today (as of 2026-11-13) — sc-plugin-aws,
sc-plugin-cloudflare, sc-plugin-cloudru, sc-plugin-gcp,
sc-plugin-mongodb, sc-plugin-mws, sc-plugin-yandex, plus
sc-plugin-echo as the template. The still-planned clouds in
the original seed list are selectel, vkcs, timeweb, and
k8s (Kubernetes stays in-tree pending its own extraction slice).
The template every new plugin starts from is
simple-container-com/sc-plugin-echo.
What this page is not
This is the author guide. If you're an operator pinning a plugin, read Upgrading to Plugins.
If you're authoring an SC Component — a managed service SC deploys onto
a compute target the operator picks with deployTo: — this page still
applies (a Component ships as a plugin), but the Component-specific
contract lives in Authoring an SC Component:
Schema opt-ins, component_defaults, the dispatch sequence.
1. Clone the template
gh repo create <org>/sc-plugin-<cloud> --template simple-container-com/sc-plugin-echo --public
cd sc-plugin-<cloud>
Rename the module paths and the plugin's own name:
# Module paths in both go.mod files
sed -i 's|sc-plugin-echo|sc-plugin-<cloud>|g' api/go.mod plugin/go.mod
# Package name throughout the sources — this is the one you'll do by hand too
grep -rlE 'echo|Echo' api/ plugin/ --include='*.go' \
| xargs sed -i -e 's/\becho\b/<cloud>/g' -e 's/\bEcho\b/<Cloud>/g'
# Binary name in the release workflow + imports in main.go
sed -i 's|sc-plugin-echo|sc-plugin-<cloud>|g' .github/workflows/release.yml README.md CLAUDE.md
Verify the template still passes untouched before you change anything of substance:
Both must print ok. If they don't, the rename is incomplete — grep for
echo and Echo and finish the sweep.
2. Author the config tier (/api)
The /api module is published as its own Go module. SC core imports it;
your plugin binary (/plugin) imports it. Everything here is parse-time
only — no cloud SDK is linked in, no network calls, no Pulumi.
2.1 Define the token constants
Replace api/init.go's const block with your cloud's tokens:
const ProviderType = "<cloud>"
const (
AuthTypeAccessKey = "<cloud>-access-key"
RegistrarTypeDns = "<cloud>-dns"
TemplateTypeFunction = "<cloud>-function"
ResourceTypeBucket = "<cloud>-bucket"
DriverVm = "<cloud>-vm"
StateStorageTypeBucket = "<cloud>-state-bucket"
SecretsProviderTypeKms = "<cloud>-kms"
)
A token's string value is the public contract — renaming it turns an
existing operator's server.yaml into "unknown type". Treat them as frozen
once published.
2.2 Author the auth type
Replace EchoAccountConfig in api/auth.go with your cloud's credential
shape. The shape must implement api.AuthConfig plus
ProviderType() string, CredentialsValue() string,
ProjectIdValue() string, and Validate() error:
CredentialsValuereturns the opaque blob for${auth:<name>}interpolation. The template's fallback (api.AuthToString(r)whenr.Credentials.Credentials == "") is what you want: it preserves the operator's choice of inline fields vs an external secret.ProjectIdValueis what${auth:<name>.projectId}resolves to. Return the k8s-style"n/a"for a cloud without a project id notion.Validatemust refuse at parse time what the first API call would otherwise return as a cloud-specific 401/403. Name the missing field.
2.3 Author the registrar + template configs
Same shape as the account config, but with cloud-specific fields
(zone id, bucket region, timeout, memory). Each needs a
Read<Type>Config(*api.Config) (api.Config, error) reader that calls
api.ConvertConfig.
2.4 Register everything in init()
Both halves — the config readers and the fool-protection declaration —
MUST list every token your plugin owns. Missing one in OwnedTypes is
a silent gap: an operator who only uses the un-listed token gets no
auto-inject from SC core's parse-time validator, and the deploy fails
later with "unknown resource type". The template's init_test.go guards
this via reflection.
api.RegisterProviderConfig(api.ConfigRegisterMap{
AuthTypeAccessKey: ReadAuthAccessKeyConfig,
RegistrarTypeDns: ReadDnsRegistrarConfig,
TemplateTypeFunction: ReadFunctionTemplateConfig,
})
api.RegisterPluginRequirement(api.PluginRequirement{
PluginName: "<cloud>",
OwnedTypes: []string{
ProviderType, AuthTypeAccessKey, RegistrarTypeDns,
TemplateTypeFunction, ResourceTypeBucket, DriverVm,
StateStorageTypeBucket, SecretsProviderTypeKms,
},
DefaultSource: api.PluginSource{
Type: "github-release",
Repository: "<org>/sc-plugin-<cloud>",
},
})
3. Author the provisioning tier (/plugin/internal)
The handler scaffolding that used to be copy-pasted into every plugin's
main.go now lives in api/pkg/plugin/runtime.
Import it, don't re-copy it — rolling your own re-earns the bugs it was built
to prevent. See pkg/plugin/runtime/wait.go
for the package doc.
The five helpers every production plugin uses:
runtime.NewContext(stdctx, req.GetHeader(), opts...)— opens onesdk.Contextper RPC.WithLocalEngineFallback(publisher)keeps backgroundctx.Logcalls from panicking when the header carries no engine address.runtime.Settle[T](rctx, &resp, &err)—deferred at the top of every handler. Drains pendingRegisterResourcegoroutines viago:linknameinto(*Context).wait, closes the context, folds any wait-error into the handler's named return. Without this, a handler that returns before its registrations resolve lets Pulumi's teardown drop them silently, and SC core plans a destroy of every state entry on the next apply (playbook trap 7).runtime.HarvestExports(stdctx, pctx)— reads everypctx.Export(k, v)made during the handler, awaits eachsdk.Output, and converts intomap[string]*scpluginv1.InputValue. Preserves the Secret flag — the live-caught regression it exists to prevent (playbook trap 11) landed access keys and RDS passwords plaintext in the parent stack root.runtime.ParentInfoFromRequest(req)+runtime.ResourceInputForComputeProcess(req, parent, cfg)— ComputeProcess helpers. The latter swaps the child env for the parent's whenParentInfo.ParentEnvis non-empty, so parent-stack lookup keys resolve correctly on isolated stacks (playbook trap 12).runtime.DecodeInputs[T](req.GetInputs(), &target)— unmarshals the plugin's typed input map into your config struct viascPlugin.InputsToPlain+ yaml round-trip. Handles nested maps and lists correctly, which the earlier scalar-only variants in aws/mongodb/cloudru lost (playbook trap 14).
Two things that stay per-plugin:
LogStream— drains the plugin's progress Publisher onto the gRPC stream. Skip this and the plugin is silent for the whole of a multi-step RPC chain. The template wires it correctly; don't touch it.strVal(v *scpluginv1.InputValue) stringand small input accessors — one-liners that read scalar fields offInputValue. Keep them local.
Idiomatic handler skeleton:
func (p *myPlugin) Provision(stdctx context.Context, req *scpluginv1.ProvisionRequest) (resp *scpluginv1.ProvisionResponse, err error) {
rctx, err := runtime.NewContext(stdctx, req.GetHeader(), runtime.WithLocalEngineFallback(p.progress))
if err != nil {
return nil, err
}
defer runtime.Settle(rctx, &resp, &err)
var cfg MyCloudBucketConfig
if err := runtime.DecodeInputs(req.GetInputs(), &cfg); err != nil {
return nil, errors.Wrap(err, "decode bucket inputs")
}
// register cloud resources against rctx.Pulumi; rctx.Pulumi.Export(key, out)
// every value a consumer might want.
outputs, err := runtime.HarvestExports(stdctx, rctx.Pulumi)
if err != nil {
return nil, err
}
return &scpluginv1.ProvisionResponse{Urn: urn, Outputs: outputs}, nil
}
What you change:
3.1 Schema() — advertise everything you own
return &scpluginv1.SchemaResponse{
PluginVersion: "<cloud>-0.0.1",
ProviderTypes: []string{echoApi.ProviderType},
RegistrarTypes: []string{echoApi.RegistrarTypeDns},
ResourceTypes: []string{echoApi.ResourceTypeBucket},
ComputeProcessorTypes: []string{echoApi.ResourceTypeBucket},
StateStoreTypes: []string{echoApi.StateStorageTypeBucket},
SecretsProviderTypes: []string{echoApi.SecretsProviderTypeKms},
PulumiPlugins: []*scpluginv1.PulumiPluginRequirement{
{Package: "<cloud>", Version: "X.Y.Z"}, // github.com/pulumi/pulumi-<cloud>/sdk
},
VmDrivers: []*scpluginv1.VmDriverSpec{
vm.Drivers[vm.Driver<Cloud>].ToProto(vm.Driver<Cloud>),
},
}, nil
Keep Schema() in sync with /api/init.go's OwnedTypes list — the
two must agree. The init_test.go reflection test catches gaps in the
OwnedTypes half; a Schema() that omits a token is caught at the
next conformance run.
3.2 Replace the RPC bodies
Each echo RPC in plugin/internal/ registers a logical ComponentResource
with no cloud side-effects. For each one you own, replace the body with
real cloud-driven work:
- Construct a
pulumi.ProviderResourcewith your cloud SDK'sNewProvider. - Register cloud resources (
cloudflare.NewRecord,yandex.NewDnsRecordSet, …). - For DNS registrars, honour the deploying stack's
baseDnsZonefrom the request — NOT your configuredzoneName, which is only a default. See §6. - For VM drivers, construct a
tls.PrivateKeydeploy key, then compose the host viaplugin.BuildVmHosts(plugin.NewVmHost(ctx, name). AddressOf(fip, "externalIpv4Address").PrivateKeyOf(key, "privateKeyOpenssh").HostKeyOf(key, "publicKeyOpenssh"). DependsOn(instance, fip)). Seeapi/pkg/plugin/vmhosts.gofor the full builder surface.
3.1 ComputeProcessor — env vars and template extensions for consumers
A ComputeProcessor runs for every dependency resource a consuming stack
declares (a compose service pointing at a MongoDB cluster, a Lambda
pointing at an S3 bucket). The plugin translates the resource's
provisioning outputs into:
- env vars the consumer runs with (
MONGO_URI,DATABASE_URL), optionally secret-flagged; - template extensions — maps the consumer's config reads to resolve
${resource:<name>.<key>}and${dependency:<name>.<resName>.<key>}.
Use plugin.NewComputeResult() from
api/pkg/plugin/compute.go:
import scPlugin "github.com/simple-container-com/api/pkg/plugin"
func (p *myPlugin) ComputeProcess(ctx context.Context, req *scpluginv1.ComputeProcessRequest) (*scpluginv1.ComputeProcessResponse, error) {
return scPlugin.NewComputeResult().
Urn(fmt.Sprintf("<cloud>-compute:%s:%s", req.GetResourceType(), req.GetResourceName())).
SecretEnvVar("MONGO_URI", mongoUri, req.GetResourceType(), req.GetResourceName(), req.GetHeader().GetStackName()).
EnvVar("MONGO_DB", dbName, req.GetResourceType(), req.GetResourceName(), req.GetHeader().GetStackName()).
ResourceTplExtension(req.GetResourceName(), map[string]string{
"connectionString": connStr,
"database": dbName,
}).
Build()
}
Open a StackReference against the parent to pull previously-exported
outputs. The parent-stack reference string rides in
req.ParentInfoJson — JSON of
pApi.ParentInfo
with FullReference, UsesResource, DependsOnResource,
ResourceEnv, StackName:
var parent pApi.ParentInfo
if raw := req.GetParentInfoJson(); len(raw) > 0 {
if err := json.Unmarshal(raw, &parent); err != nil { return nil, err }
}
ref, _ := sdk.NewStackReference(pctx, parent.FullReference, nil)
projectId := ref.GetOutput(sdk.String(parent.StackName + "-project-id"))
What does NOT cross the bus
pApi.ComputeContextCollector has methods for AddDependency(sdk.Resource),
AddOutput(sdk.Output), AddPreProcessor, AddPostProcessor. Pulumi
resource handles and Go closures are not serialisable, so the sidecar's
response-handling only reaches the env vars + tpl extensions. Apply resource
handles against the plugin's own sdk.Context BEFORE returning from Build.
AddPreProcessor, AddPostProcessor and AddDependency are the
exception, and only between the two RPCs of one deploy. A dependency's
ComputeProcess and the consuming template's Provision run in the same plugin
process, so runtime.Collector parks the closure (or the resource) keyed by
the stack name both headers carry, and the template takes it back out:
RunPreProcessors / RunPostProcessors (which kubernetes.NewSimpleContainer
calls on its container args, before the Deployment and once the
SimpleContainer exists) and Dependencies() (which the Deployment waits on).
That is how the Cloud SQL proxy becomes a sidecar of the app using the
database (pre-processor), how its init proxy and db-user-init Job get
created (post-processor), and how the Deployment waits for the proxy's
service account and credentials Secret (dependencies). Consequences for the
closure:
- It runs with the
sdk.Contextand providers it captured in ComputeProcess, so that RPC's context is NOT drained when the handler returns, and it is kept alive past the request's own cancellation; the template'sruntime.Settledrains it. A handler that does not useruntime.Settleloses this. - It still cannot reach anything the template builds in its own RPC except
through the argument it is given (
NamespaceNameOutputandNamespaceon the container args are how it learns the namespace).
Before this, all three were empty functions: a stack deployed with no proxy sidecar and no init Job, and the deploy stayed green.
Reference: sc-plugin-echo/plugin/internal/compute.go
— minimal stub exercising every builder method.
3.2 PreDestroy — cleanup before Pulumi destroys
A PreDestroy hook runs cloud-specific cleanup before Pulumi's destroy
phase: mongodb drops databases named in service-user outputs, aws might
drain an SQS queue. Three fields SC core packs on the request (Phase 1e):
req.StackOutputs—map<string, bytes>, each value is JSON ofauto.OutputValue({"value": …, "secret": bool}). Enumerate without decoding each one; filter by key suffix (mongodb matches-service-user) before unmarshalling.req.ClientDescriptorJson— JSON ofapi.StackClientDescriptorforstack.Client.Stacks[env]. Hooks readcloudExtrasoff this.req.DestroyParamsJson— JSON ofapi.DestroyParams. Carries env name- dry-run flags.
func (p *myPlugin) PreDestroy(ctx context.Context, req *scpluginv1.PreDestroyRequest) (*scpluginv1.PreDestroyResponse, error) {
// Decide whether to run from cloudExtras.
var desc api.StackClientDescriptor
if raw := req.GetClientDescriptorJson(); len(raw) > 0 {
_ = json.Unmarshal(raw, &desc)
}
// Enumerate stack outputs by suffix.
for key, raw := range req.GetStackOutputs() {
if !strings.HasSuffix(key, "-service-user") { continue }
var ov auto.OutputValue
if err := json.Unmarshal(raw, &ov); err == nil {
dropDatabase(ov.Value)
}
}
return &scpluginv1.PreDestroyResponse{}, nil
}
SC core is fire-and-forget on PreDestroy
The sidecar does not block the destroy on your response. Return
{} even on partial-failure paths; log the failure through your
progress Publisher so the operator sees it, but let the destroy
proceed. If your cleanup is critical to data integrity, it belongs
in the resource's own destroy script (pulumi-command Delete), not
in PreDestroy.
Reference: sc-plugin-echo/plugin/internal/pre_destroy.go.
3.3 Composite plugins — PeerInvoke (D8)
A composite plugin needs cloud resources another plugin owns —
sc-plugin-mongodb's PrivateLink needs an AWS SecurityGroup + VpcEndpoint;
sc-plugin-k3s wants both AWS and GCP. Decision D8 of
06-decisions.md
rejects a direct plugin-to-plugin connection and the Go-module-import
alternative: SC core brokers, exposed via the SCCore callback RPC
PeerInvoke.
The plugin side dials via a go-plugin broker stream SC core served specifically for this plugin:
import scPlugin "github.com/simple-container-com/api/pkg/plugin"
peer, err := scPlugin.NewPeerClient(ctx, broker, req.GetHeader())
if err != nil { return nil, err }
defer peer.Close()
awsResp, err := peer.Provision(ctx, "sc-plugin-aws", &scpluginv1.ProvisionRequest{
Header: req.GetHeader(),
ResourceType: "aws-security-group",
ResourceName: "mongodb-privatelink-sg",
// ... inputs ...
})
The broker arrives at your plugin's GRPCServer method (hashicorp/go-plugin
hands it there). Your Impl struct must capture it so handlers can dial
back later:
type myPlugin struct {
scpluginv1.UnimplementedSCCloudPluginServer
broker *hplugin.GRPCBroker // captured; nil until GRPCServer runs
// ...
}
BrokerAware is live (api #514). pkg/plugin/goplugin.go's
scCloudPlugin.GRPCServer type-asserts the Impl against the one-method
interface type BrokerAware interface { SetBroker(*hplugin.GRPCBroker) }
and calls SetBroker when it exists; NewPeerClient dials through it.
Used in production today by sc-plugin-aws, which delegates
NewDnsRecord / ProvisionDomainForEndpoint / NewOverrideHeaderRule
to the operator-configured registrar (typically cloudflare).
Dead-strip the ApplyT around PeerInvoke — the 2026-11-01 trap
If your bridge method returns a *api.ResourceOutput{Ref: urnOut}
where urnOut is an ApplyT chain containing the PeerInvoke call,
and the caller discards the ResourceOutput, Pulumi's SDK dead-strips
the orphan Output and the PeerInvoke RPC never fires — the deploy
reads green with the DNS record silently never registered. Fix:
ctx.Export(unique-key, urnOut) inside the bridge method before
returning, as a forcing function. Keys must be unique per
(stack, resource/endpoint/rule) so stacks with multiple records
don't collide. Live-caught on forge-notifier run 41339900839; fixed
in sc-plugin-aws v2026.11.01-e377550. See
playbook trap 15.
Rules of the road (D8):
- A composite plugin NEVER imports a peer plugin's SDK as a Go module.
The plugin bus is the only cross-plugin contract.
- A composite plugin NEVER maintains its own list of "which peer owns
which type". Call PeerInvoke with the operator-configured peer name
(from the plugin's own config), and let SC core refuse unknown peers.
References:
- api/pkg/plugin/peer.go — plugin-side helper.
- api/pkg/plugin/callback_server.go — core-side server (also carries the ResolveSecret/ResolveCredential stubs — Vault pattern, Addendum R work).
- Design: 03-architecture.md §9.
4. Test — the trap-free pattern
The template's plugin/internal/urn_contract_test.go uses
pulumi.NewContext + RunInfo.Mocks directly, not
pulumi.RunErr(..., WithMocks). This matters:
The test-harness trap
pulumi.RunErr ends in the context's internal wait(), which drains
the engine's RPC queue. Any registration stranded on an unresolved
input is silently completed by the harness itself on the test's behalf.
That hid the entire 2026-10-28 await-returns bug class behind a
green suite (Addendum R §R3 of
04-no-destroy-invariant.md). Open the context by hand so
assertions land on your handler's RETURN rather than the harness's
drain:
pctx, err := pulumi.NewContext(context.Background(), pulumi.RunInfo{
Project: "test-project",
Stack: "test-stack",
Mocks: mocks,
})
defer pctx.Close() // no-op under mocks
If your handler returns before awaiting a registration, the mock captures no call and the URN assertion fails — exactly what you want.
Every URN your plugin produces for a Pulumi resource embeds a resource
name. Pulumi state keys off that name. If a future refactor changes
one, every operator's sc deploy under the previous plugin version will
replace+create (and in the DNS record case, actively delete live DNS).
The URN contract test freezes those names.
Add one test per Pulumi type:name your plugin registers. Pattern:
m := &captureMocks{}
withTrapFreeContext(t, m, func(ctx *pulumi.Context) error {
_, err := NewRegistrar(ctx, "stack.example.com", "configured.example.com")
// ... exercise the handler ...
return err
})
Expect(m.namesByType("<cloud>:dns:Record")).To(Equal([]string{"www-A"}))
5. Release
Push to main triggers the release workflow in
.github/workflows/release.yml:
- CalVer tag
vYYYY.MM.DD-<short-sha>. - Three binaries (linux/amd64, linux/arm64, darwin/arm64).
- Consolidated
sha256sums.txt. - GitHub Release with auto-generated notes.
Keep the OOM pins
The workflow's GOMAXPROCS=1, GOMEMLIMIT=6GiB, and
go build -p 1 are not stylistic. Default parallelism OOMs the
standard 7 GB GHA runner on a plugin importing a big cloud SDK
(pulumi-yandex is ~2 GB of generated types; pulumi-sbercloud is
similar). Four of six existing SC plugin repos learned this on their
first release run. Keep the pins even for a plugin whose SDK is
small today — the cost is ~2 minutes of wall time and the saving is
an avoidable round trip.
Manually-pushed v* tags produce named releases for pinning or rollback.
6. The gotchas
Each cost a round trip at least once. Keep them in mind as you author. The canonical trap-by-trap catalogue (fifteen entries as of 2026-11-01) lives at forge/docs/design/2026-11-01/plugin-extraction-playbook/ — the subset below is the ones you will hit as an author rather than as the operator picking up a bad release.
6.1 Zone-vs-baseDnsZone — the 2026-10-28 incident
A DNS registrar's zoneName config is a default. The deploying
stack's baseDnsZone is what MUST drive the actual zone lookup. SC core
sends it in ProvisionRegistrarRequest.BaseDnsZone (api v2026.10.37
and later). Writing a record into the wrong zone with
create-before-delete semantics deletes the live record from the right
one. See Addendum R of 04-no-destroy-invariant.md.
pref := &pApi.DnsPreference{BaseZone: req.GetBaseDnsZone()}
if pref.BaseZone == "" {
pref = nil // older core, or stack with no preference
}
6.2 Drain before you return
Pulumi fires RegisterResource from a goroutine. A handler that returns
before those registrations finish lets pctx.Close() tear the engine
connection down mid-flight. SC core sees no registrations for the handler's
run, concludes "those resources no longer exist in the program", and plans a
destroy of each state entry on the next apply. See the wait.go package doc
of pkg/plugin/runtime
for the Pulumi-SDK linkname that runtime.Settle uses to drain.
Don't skip the defer runtime.Settle(rctx, &resp, &err) line. The
template wires it correctly out of the box; rolling your own with
pctx.Close() instead is the shape that cost every pre-cascade plugin
version one round trip.
6.3 go.mod replace directives don't resolve on CI
Local development with
replace github.com/simple-container-com/api => /tmp/path resolves on
your laptop and nowhere else. For a not-yet-merged API change, run
go get github.com/simple-container-com/api@<branch> to pin a
pseudo-version against the SHA, and go mod tidy to lock it. Commit
the resulting go.sum.
The /plugin module's replace github.com/.../sc-plugin-<cloud>/api => ../api
IS fine — that's a sibling module in the same repo and CI checks it
out together.
6.4 Operator-named resources need a stable URN separate from the export key
When you honour an operator's name: override (atlasCfg.ClusterName, a
bucket's explicit bucketName), use it ONLY for the resource's cloud-side
name and for export keys consumer stacks will read. The Pulumi URN that
anchors state must stay stable — derive it from the stack's identity, not
from a knob the operator can change. If you let the operator rename a cluster
and that rename flows into the Pulumi logical name, every orphan output under
the old name reads as "no longer in program" and gets destroyed on the next
apply — including the operator-owned Secret the parent exported.
Pattern:
pulumiResourceName := toClusterName(stack.Name, input) // stable, used in URNs
exportClusterName := pulumiResourceName
if cfg.ClusterName != "" {
exportClusterName = cfg.ClusterName // operator-visible
}
cluster, _ := mongodbatlas.NewCluster(ctx,
fmt.Sprintf("%s-cluster", pulumiResourceName), // URN-anchored
&mongodbatlas.ClusterArgs{Name: sdk.StringPtr(exportClusterName)})
ctx.Export(toClusterIdExport(exportClusterName), cluster.ClusterId)
Live-caught on forge-notifier run 41330569069 (2026-11-01) — the mongodb
plugin coupled URN naming to the operator's custom cluster name and renaming
the cluster deleted the CNAME and MONGO_PASSWORD secret. Fixed in
sc-plugin-mongodb v2026.11.01-c9f5514. See playbook trap 13.
6.5 Collector helpers that distinguish incoming vs outgoing env vars
A plugin that runs both Provision (reads INCOMING env vars from the consumer
stack's uses: resources) and ComputeProcess (produces OUTGOING env
vars from this plugin's own resources) needs two separate pools in its
ComputeContextCollector. A single-pool implementation that returns nil
from EnvVariables() / SecretEnvVariables() silently drops the consumer's
MONGO_PASSWORD / bucket env / anything else their parent exported. The
deploy reads green; the deployed container boots with the env unset.
Pattern: seed the INCOMING pool from req.GetComputeEnvVars() in your
newProvisionCollector; expose EnvVariables() / SecretEnvVariables() as
reads of that pool. The OUTGOING pool is what AddEnvVariableIfNotExist /
AddSecretEnvVariableIfNotExist write into during ComputeProcess, and what
ToResponse() ships back in ComputeProcessResponse.EnvVars.
Live-caught on forge-notifier run 41336224941 (2026-11-01). Fixed in
sc-plugin-aws v2026.11.01-91284ba. See
playbook trap 14.
6.6 gci section lists are per-repo
Each SC repo has its own .golangci.yml with a linters-settings.gci.sections
list. Copy the one from the repo you're linting, not the one you
remember. Running gci with the wrong section list is a lint-only diff —
gofmt doesn't catch it — and it fails CI from an operator-invisible place.
6.7 Never test an Output's zero-ness via its value methods
pulumi.StringOutput is a struct with a single embedded pointer field —
struct { *OutputState }. ElementType() is a value method that
returns a package-level reflect.Type constant — the full citation is
pulumi/sdk/v3@v3.245.0/go/pulumi/types_builtins.go:9471:
So out.ElementType() != nil is a constant true for every
StringOutput in existence, including var o sdk.StringOutput. The
method answers identically on a zero-value struct and a fully-
resolved one, because the method can't see whether the embedded
pointer was ever assigned. Any value method on a struct-with-
embedded-pointer has this property, so the rule that catches the
whole class is:
The only field that distinguishes a zero Output is the embedded pointer. Test
out.OutputState != nil, never a method.
The anti-pattern — don't:
// isPulumiOutputSet tests a value method that returns a constant for ALL instances of
// the type — zero-value or populated. The predicate reads correctly but is
// unconditionally true, and the "set" branch always wins.
func isPulumiOutputSet(out pulumi.StringOutput) bool {
return out.ElementType() != nil
}
The correct shape — test the embedded pointer:
// out.OutputState is the only field that distinguishes a zero Output
// from a populated one. The zero value is `pulumi.StringOutput{}` with
// *OutputState == nil.
func isOutputSet(out pulumi.StringOutput) bool {
return out.OutputState != nil
}
The sharper framing: check the source, not the output. When the value comes from a plain string you already hold in scope, the predicate on the source is always clearer and never has this failure mode:
// Preferred: predicate on the source string, not on an Output derived from it.
// Use this when the source value is in scope at the call site.
var valueOut pulumi.StringOutput = record.ValueOut
if record.Value != "" {
valueOut = pulumi.String(record.Value).ToStringOutput()
}
Live-caught (api ee4afc84, 2026-11-08): a kubernetes-caddy driver's
isXSet-over-output predicate was unconditionally true, so the
GKE-only branch always won and caddyfilePrefix + trustedProxies
were accepted, validated and silently discarded on every non-GKE
cluster. The fleet-wide lesson is the first framing above — the second
form (check the source) is the preferred shape at every call site
where the source is in scope.
Why this is invisible in preview. A zero-value sdk.StringOutput
doesn't await as the empty string — it awaits as UNKNOWN. Probed live
against the shipped SDK (pulumi/sdk/v3@v3.245.0):
So the downstream failure modes differ by who consumes the zero
Output: a predicate-reader gets the wrong branch selected (the
caddyfilePrefix discard above); an awaiter gets UNKNOWN forever,
which lands on the wire as an unresolved placeholder — a Caddy pod
handed CADDYFILE_PREFIX=<unresolved> never comes up. Previews don't
distinguish "will resolve to known" from "will never resolve", so
neither shape surfaces until apply-time, which is why these bugs can
live for a year before anyone measures.
6.8 A helper that bypasses the framework gives up the resource graph
The sibling trap to §6.7: a surface that looks like it carries
ordering intent (Opts []sdk.ResourceOption) but never reaches the
Pulumi engine silently discards sdk.DependsOn, sdk.Provider, every
other ResourceOption the caller passed. Ordering becomes fiction —
the code reads correctly, a reviewer sees sdk.DependsOn([]sdk.Resource{x})
and infers "waits for x", but at runtime the apply fires whenever its
own inputs resolve, in whatever order the engine happens to schedule.
The root cause is architectural: only a RegisterResource call
attaches a resource (and its ResourceOptions) to the Pulumi graph.
A helper that mutates state inside a bare sdk.All(...).ApplyT(...)
side effect — no RegisterResource — is OUTSIDE the graph. Any
ResourceOption the helper accepts goes nowhere.
The two-second check: grep -n '<field>' <file> returning only the
declaration. If the only occurrence of Opts in a helper's file is
the struct field definition, the helper never used it — the
ResourceOptions travelled from the call site to a dead end.
The anti-pattern — don't:
// DeploymentPatchArgs carries options the caller believes order the patch.
// The helper below does not call RegisterResource; the Opts never leave
// this struct. DependsOn here is a documentation-only annotation.
type DeploymentPatchArgs struct {
...
Opts []sdk.ResourceOption
}
func PatchDeployment(ctx *sdk.Context, args DeploymentPatchArgs) error {
return sdk.All(args.Service.Metadata).ApplyTWithContext(
ctx.Context(),
func(_ context.Context, all []any) error {
// mutate k8s state here; no RegisterResource call → outside the graph
return doPatch(all[0].(metav1.ObjectMeta))
},
).(sdk.AnyOutput).Result()
}
// Call site — the DependsOn is a lie.
err := PatchDeployment(ctx, DeploymentPatchArgs{
Opts: []sdk.ResourceOption{sdk.DependsOn([]sdk.Resource{svc})},
...
})
The correct shape depends on what the helper is actually doing:
- If the helper registers a resource: pass
Optsthrough toRegisterResource(or to a pulumi SDK call that does). This is the common case — most helpers should register resources, andOptsreaches the engine naturally. - If the helper is a bare
ApplyTside effect (like a patch computed from another resource's applied state): drop theResourceOptionfield entirely and order the apply via its input outputs.sdk.ToStringMapOutputand similar*Outputtypes preserve the source's output dependencies — anApplyTon an output cannot run until the source has resolved, which is the only ordering mechanism an apply-driven helper has.
Live-caught (Caddy-edge batch commits 1-2, 2026-11-08): PatchDeployment
(pkg/clouds/pulumi/kubernetes/deployment_patch.go) carried an unused
Opts []sdk.ResourceOption for over a year. Two call sites
(kube_run.go, gcp/gke_autopilot_stack.go) passed
sdk.DependsOn([]sdk.Resource{sc.Service}) through it. The ordering
never fired: a Caddy pod rolled 9s before the Service annotation it
was rolled for became visible (pod template 16:16:30, annotation
16:16:39). Fix was to compute the pod-template hash from the Service's
applied annotation — sdk.ToStringMapOutput preserves the
annotation's output dependency, so the patch's apply blocks on it.
Dead Opts field removed; PatchDeployment's doc comment now states
that DependsOn cannot order it and what to do instead.
Generalisable rule: a helper that doesn't call RegisterResource
cannot order work via ResourceOptions. Order via output
dependencies on its inputs, or make the helper register a resource.
6.9 A fmt.Sprintf-built shell string executes as a shell
Sibling trap to §6.7 and §6.8, in the shell domain. A plugin that
generates a remote script — an init container, a sh -c Job, a
cloud-init payload, a psql -c wrapping an identifier — is building
a program that will be interpreted by a shell (and sometimes a
second interpreter inside it, like psql or bash). Every character
operator-controlled values pass through is live in that interpreter's
grammar, not just the ones you were thinking about.
Two concrete shapes that pass sh -n and every substring assertion
yet execute unsafely:
(a) A backtick inside a double-quoted sh string is command substitution. Writing:
— means echo fires docker network create <netName> BEFORE
printing the message. Found live inside an error-handling path (the
message existed because the command had already failed), so running
it a second time compounded the state problem the operator had.
(b) Operator-supplied values reaching prose, not just command
arguments. Shell-quoting an argument for sudo doesn't help if
the same value is also interpolated raw into an echo message:
— the first line is safe (single-quoted argument, operator can't
escape), the second is not ("..." keeps $ and backtick live).
A user name like foo$(rm -rf /) runs the subcommand on the second
line.
Rules:
- Treat EVERY interpolation point as a shell injection. Not just
the ones that reach
execorsudo—echo,printf, SQL identifiers, container names, labels.$and backtick are live in more places than a reader expects. - For prose messages, use
printfwith the message as a format string argument, not interpolation into the string itself.printf '%s\n' "$MSG"is the shape; the message's$s and backticks are now data, not code. - Shell-quote at the boundary. Go's standard library has no
single-source-of-truth shell quoter, but
"'" + strings.ReplaceAll(v, "'",'\'') + "'"is the inline form for POSIX sh; wrap this in a helper and use it on every operator-controlled interpolation.
How to test it: don't assert on the generated script text —
sh -n catches syntax errors, substring matches catch presence,
and neither catches a hostile value being substituted correctly or
incorrectly. Execute the generated script against stubbed binaries
on an empty PATH. The stubs record their invocations; the test
asserts on those recordings. A value that escapes correctly reaches
the stub as one argument; a value that escapes incorrectly reaches
as two, or triggers a subcommand that the stub doesn't exist to
answer, or fires an unrelated stub earlier in the script than
intended. Only a shell can distinguish those; only the recording
sees the difference.
The reference pattern lives on feat/caddy-edge-batch in
pkg/clouds/pulumi/vm/compose_scripts_test.go (runEnsureNetwork)
and pkg/clouds/vm/cloudinit_test.go (runByoDockerInstall). SHAs
may move under rebase; the branch name is the stable citation. The
shape in both: PATH=<stub-dir-only> sh -c <generated-script> with
stubs that log $0 $* to a file.
Live-caught during the Caddy-edge batch (2026-11-08): both shapes
shipped in the same commit, both caught by the executing tests
before merge. The backtick-in-echo was an error-hint message that
would have fired the failing command a second time; the
raw-operator-value-in-echo was a useradd login whose name was
quoted correctly for the sudo lines but interpolated bare into
two echo lines. The executing test caught both.
6.10 Write PR numbers, not per-commit SHAs, into roadmap items
Two separate traps combine to make per-commit SHAs an unreliable "did this ship" handle in this repo.
Trap 1: committing onto an already-merged branch is completely
silent. git push reports success, the branch exists on origin,
the GitHub UI shows no open PR to notice. If the PR was merged while
you were writing the commit, your work exists on the branch alone,
reachable from origin/<branch> and nowhere else — in particular,
not from origin/main.
Found live 2026-11-08: ee4afc84, the isPulumiOutputSet fix
recorded as "merged with api#563", was committed onto
feat/vm-multi-host-roles 13 minutes AFTER #563 merged. No open PR,
no visible failure, correct-looking SHA in the roadmap row.
Discovered only because an independent re-derivation of the same
fix hit a reviewer and the two attributions contradicted each
other.
Trap 2: api squash-merges. A multi-commit PR lands as one new
commit on main with subject (#NNN) — the pre-merge per-commit SHAs
you recorded (either pre-rebase or post-rebase) are unreachable from
main the moment it merges. Verified empirically 2026-11-08:
gh pr view 573 --json commits,mergeCommit returned 5 commits in
commits[] and a single mergeCommit.oid, with git log --graph
origin/main showing a linear history of (#NNN) subjects. A
nine-commit PR lands as one commit.
The two traps answer the same question with opposite semantics.
git merge-base --is-ancestor <sha> origin/main says "no" for both
a stranded commit (ee4afc84 — the trap) and a squashed-merged commit
(any pre-merge SHA, including ones that shipped perfectly). The
check tells you the SHA is useless, not whether the code is there.
The durable handle is the PR number.
The two-second check:
state: MERGED+ a non-nullmergeCommit.oid→ the work shipped, and the squash-merge SHA is the one and only commit on main that carries it.state: OPEN→ not shipped yet; a per-commit SHA on the branch may be real work-in-progress but won't survive the eventual merge.state: CLOSEDwithout a mergeCommit → the PR was closed without merging. Any commits on that branch are unreachable from main.
If you only have a SHA, not a PR number, don't reach for
gh pr list --search <sha> — that command searches PR text
(title, description, comments), so it matches whichever PR
mentioned the SHA in a comment, not necessarily the one that
contained it. Verified empirically 2026-11-08: searching three
different SHAs returned the same PR number for all three because
that PR's description happened to reference them.
The correct lookup is:
It returns the PR that actually contained the commit even after the
squash. One alarming-looking detail that isn't a bug: this endpoint
reports a merged PR as state: closed. The GitHub API doesn't have
a merged state; it's state: closed + merged: true + a non-null
merged_at. Read those together.
Run the check before writing "merged" or a SHA into:
- a roadmap item's
## Statusor## Historysection, - a commit message that references another commit as shipped,
- any SendMessage or peer coordination that cites a SHA.
Write the PR number in the item (PR #573 merged), not the SHA. If
you need to cite a specific change, cite it by PR + subject (`PR
573's LoadForBackend variant`) rather than SHA. The PR number
survives rebase, squash-merge, and the entire failure surface above.
Why git merge-base --is-ancestor still has a use. For your
own in-flight commits on a branch whose PR is still open, the
check answers "did my latest work reach my own branch on origin".
That's the gh pr list --head <branch> --state open equivalent —
useful for "did I remember to push". Just don't confuse "reachable
from origin/
The failure mode that justifies the two seconds. Every other
section in this chapter says "live-caught git merge-base. A future reader cross-references those SHAs and
sees "not found on main" for a legitimate merge, concludes the fix
was reverted, and re-derives it — the same failure mode the
ee4afc84 discovery caught, but from the opposite direction.
6.11 A plugin's api.Stack has only a name: ask for what the template reads
In-tree, a template received the whole api.Stack. A plugin builds its own from
RequestHeader.stack_name alone, so stack.Client, stack.Server and
stack.Secrets are empty. Anything a template body reads off them silently
takes its zero value, and nothing fails.
The one that bit a fleet (2026-11-13): docker.BuildAndPushImage reads
stack.Client.Security to decide whether to scan, sign, attach an SBOM and
attest provenance. In a plugin it was always nil, so a plugin-owned template
planned every one of those command:local:Command resources as deleted and
would have deployed every image unsigned, with a green deploy.
ProvisionRequest.client_config_json carries the part of the client descriptor
the image build reads (security, imageBuild). Rebuild it before calling a
helper that takes a Stack:
client, err := api.ClientDescriptorFromPluginConfig(req.GetClientConfigJson())
if err != nil {
return nil, errors.Wrap(err, "decode client config")
}
stack := api.Stack{Name: req.GetHeader().GetStackName(), Client: client}
An older core sends the field empty, which gives the zero descriptor: the
behaviour before the field existed. If your template reads another part of
stack.Client, stack.Server or stack.Secrets, it needs its own field; check
by grepping the in-tree body you lifted for stack.Client, stack.Server and
stack.Secrets.
7. Prior art
Five plugin repos live today, each highlighting a different pattern:
sc-plugin-cloudflare— registrar-only. Simplest handler surface; cleanest reference for theProvisionRegistrar/NewDnsRecord/NewOverrideHeaderRule/ProvisionDomainForEndpointRPCs. Pages Direct Upload for static sites.sc-plugin-yandex— full provider + resource + state-store + secrets-provider surface. Origin of the release-workflow OOM pins and thesettle()/finishPulumiContext()pattern now packaged inpkg/plugin/runtime. Multi-registrar slice + longest-zone picker; composite-output resolution for YC objects with multi-field IDs.sc-plugin-cloudru— dual-mode binary (plugin + lifted cobra CLI). The pattern for clouds with no Pulumi provider at all: resources becomepulumi-commandlocal.Commands shelling to the plugin binary by absolute path from the plugin cache. VM driver + customcloudru-evolution-vmplus theVmHostsRPC flow.sc-plugin-mongodb— the first ComputeProcess-heavy plugin.uses:fan-out producesMONGO_URI/MONGO_USER/MONGO_PASSWORDenv vars with secret flags preserved.PreDestroywith a database-drop hook. Also the origin of the URN-vs-export-key split for operator-named clusters (see §6.5).sc-plugin-aws— the biggest surface by far: provider + state-store (s3-bucket) + secrets-provider (aws-kms) + templates (aws-lambda,ecs-fargate,aws-static-website) + resources (s3-bucket,ecr-repository,aws-rds-postgres,aws-rds-mysql,aws-cloudtrail-security-alerts)- the
cloud-helpersLambda. Also the first plugin to use theBrokerAware→PeerInvokepath to delegate DNS registration to cloudflare without a Go-module import (D8).
The template at
sc-plugin-echo
is lifted from these five — cloudflare's RPC shape, yandex's release
workflow, cloudru's init() + RegisterPluginRequirement pattern,
mongodb's ComputeProcess + PreDestroy shape, aws's PeerInvoke bridge.
8. The acceptance test
A new team member clones the template, implements a driver, cuts a
release, sc loads it — without reading SC core. If you got this far,
you did.