Provider Configuration
HashiCorpOfficialPublished by HashiCorp
- Skill
- Guidelines
- Cloud and DevOps
- MPL-2.0
- No issues found
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
This skill provides a standardized pattern for implementing authentication in Terraform providers. It focuses on creating a predictable, secure credential resolution chain that respects precedence (static config, environment variables, shared files, and platform identity). By using a consistent interface for credential retrieval, providers can offer better user experiences, clearer diagnostic messages, and improved security through secret redaction and eager validation.
What it does
- Defines a structured credential provider chain with clear precedence rules.
- Implements unknown-value guards to prevent authentication failures during plan operations.
- Provides a pattern for secret redaction in logs and diagnostic messages.
- Enables eager credential validation during the Configure phase.
- Standardizes diagnostic error messages to help users debug authentication issues.
- Supports unit testing of credential resolution logic without requiring Terraform machinery.
When to use it
- When building a new Terraform provider that requires authentication.
- When refactoring an existing provider's authentication to improve reliability.
- When debugging 'no valid credential sources' or missing-credential errors.
- When adding support for multiple authentication methods like API keys, profiles, or workload identity.
Advantages
- Improves user experience by providing actionable error messages.
- Enhances security by ensuring secrets are never logged or hardcoded.
- Reduces debugging time by clearly identifying which credential source was used.
- Ensures consistent behavior across different environments (local, CI, cloud).
- Facilitates easier maintenance through a modular, testable architecture.
Usage examples
- “How do I implement a credential chain for my Terraform provider?”
- The agent provides the interface and implementation patterns for a chain that checks static config, environment variables, and shared files in order, including the necessary error handling.
- “How can I prevent my provider from leaking secrets in logs?”
- The agent explains how to implement custom String() and GoString() methods on your Credentials struct to ensure secret fields are always redacted.
- “Why is my provider failing with unknown values during plan?”
- The agent guides you through adding IsUnknown() guards in the Configure method to catch dependencies that are not yet resolved.
Install
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/hashicorp/provider-configuration/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip provider-configuration.zip -d .agents/skills
Documentation by HashiCorp
Terraform Provider Configuration and Authentication
How a provider accepts connection settings and resolves credentials. Poor
authentication UX is the first thing every user of a provider hits; a
well-designed credential provider chain is what separates a production-grade
provider from a demo. The examples use a fictional examplecloud provider
and the Plugin Framework.
References (load when needed):
references/credential-chain.md— complete, compilable credential chain implementation (providers, chain, file profiles, Configure wiring, tests)references/case-studies.md— how the AWS provider (aws-sdk-go-base) and smaller providers structure real credential chains
Provider Schema for Authentication
Every authentication attribute must be Optional, never Required — a
Required attribute forces users to put credentials in configuration and
makes environment-variable and credentials-file resolution impossible. Mark
secrets Sensitive so Terraform redacts them in plan output, and state the
environment-variable fallback in each description so tfplugindocs publishes
the resolution rules.
func (p *examplecloudProvider) Schema(ctx context.Context, req provider.SchemaRequest, resp *provider.SchemaResponse) {
resp.Schema = schema.Schema{
Attributes: map[string]schema.Attribute{
"endpoint": schema.StringAttribute{
Optional: true,
MarkdownDescription: "API endpoint. May also be set via the `EXAMPLECLOUD_ENDPOINT` environment variable.",
},
"api_key": schema.StringAttribute{
Optional: true,
MarkdownDescription: "API key. May also be set via the `EXAMPLECLOUD_API_KEY` environment variable, or in a shared credentials file.",
},
"api_secret": schema.StringAttribute{
Optional: true,
Sensitive: true,
MarkdownDescription: "API secret. May also be set via the `EXAMPLECLOUD_API_SECRET` environment variable, or in a shared credentials file.",
},
"profile": schema.StringAttribute{
Optional: true,
MarkdownDescription: "Named profile in the shared credentials file. May also be set via the `EXAMPLECLOUD_PROFILE` environment variable. Defaults to `default`.",
},
"skip_credentials_validation": schema.BoolAttribute{
Optional: true,
MarkdownDescription: "Skip the identity check normally performed during provider configuration.",
},
},
}
}Never add a Default to a credential attribute, and never hardcode a
credential anywhere in the provider. Defaults belong in the resolution logic
(where environment variables and files can override them), not in the schema.
The Credential Provider Chain
Resolve credentials by consulting an ordered list of sources and taking the
first one that produces a complete set. This is the pattern the AWS
provider uses via aws-sdk-go-base,
and it generalizes to any provider. The canonical precedence, highest first:
Static configuration — values set directly in the
providerblock. Explicit always wins.Environment variables —
EXAMPLECLOUD_API_KEY, etc. The CI-friendly path.Shared credentials file — named profiles in
~/.examplecloud/credentials, for humans with multiple accounts.Platform identity — instance metadata, workload identity, or OIDC token exchange, where the platform offers it. Credentials nobody has to store.
Two rules make the chain predictable:
Resolve secrets as a set, not field-by-field. If the environment supplies an API key but no secret, that source offers nothing — fall through to the next source for both values. Mixing an env-var key with a file-profile secret produces authentication failures that are nearly impossible for users to debug.
Resolve non-secret connection settings field-by-field.
endpoint,profile, orinsecurecan each independently follow config > env > file > default, because a mismatch there is visible and harmless.
The core abstraction is a single-method interface with a sentinel error that distinguishes "this source has nothing to offer" (fall through) from "this source is misconfigured" (surface it):
// ErrNoCredentials signals a source had nothing to offer. The chain falls
// through to the next source. Any other error means the source was
// configured but unusable (e.g. malformed credentials file) and is
// preserved so the final diagnostics can surface it.
var ErrNoCredentials = errors.New("no credentials found")
type Credentials struct {
APIKey string
APISecret string
Source string // which provider supplied them, for logging
}
func (c Credentials) Complete() bool {
return c.APIKey != "" && c.APISecret != ""
}
type Provider interface {
Retrieve(ctx context.Context) (Credentials, error)
Name() string
}A Chain (itself a Provider, so chains compose) walks the providers in
order and returns the first complete set of credentials. Every skipped
source is recorded into an aggregate ChainError whose Error() lists each
source with the reason it was skipped, and whose Is method makes
errors.Is(err, ErrNoCredentials) true only when every source fell through
cleanly — so Configure can tell "nothing supplied" from "something
supplied but broken" with one check. The full implementation — the chain
loop, the static, environment, and file providers, and the
NewDefaultChain constructor that owns the canonical order — lives in
references/credential-chain.md.
Wiring the Chain into Configure
Configure runs once per Terraform operation, before any resource CRUD.
The shape:
func (p *examplecloudProvider) Configure(ctx context.Context, req provider.ConfigureRequest, resp *provider.ConfigureResponse) {
var config examplecloudProviderModel
resp.Diagnostics.Append(req.Config.Get(ctx, &config)...)
if resp.Diagnostics.HasError() {
return
}
// 1. Guard against unknown values (e.g. api_key = some_resource.output).
if config.APIKey.IsUnknown() {
resp.Diagnostics.AddAttributeError(
path.Root("api_key"),
"Unknown API Key",
"The provider cannot connect because api_key depends on a value known only after apply. "+
"Set a static value, or use the EXAMPLECLOUD_API_KEY environment variable.",
)
}
// ... repeat for each auth attribute, then:
if resp.Diagnostics.HasError() {
return
}
// 2. Resolve credentials through the chain.
chain := credentials.NewDefaultChain(
config.APIKey.ValueString(),
config.APISecret.ValueString(),
credentials.Options{Profile: config.Profile.ValueString()},
)
creds, err := chain.Retrieve(ctx)
if err != nil {
if errors.Is(err, credentials.ErrNoCredentials) {
resp.Diagnostics.AddError(
"No Valid Credential Sources Found",
"No examplecloud credentials were found. Sources tried, in order:\n\n"+err.Error()+
"\n\nSet api_key and api_secret in the provider block, export "+
"EXAMPLECLOUD_API_KEY and EXAMPLECLOUD_API_SECRET, or add a profile to "+
"~/.examplecloud/credentials. See https://example.com/docs/auth.",
)
} else {
resp.Diagnostics.AddError("Failed to Resolve Credentials", err.Error())
}
return
}
tflog.Debug(ctx, "resolved credentials", map[string]any{"source": creds.Source})
// 3. Build the client once; share it with every resource and data source.
client := examplecloud.NewClient(endpoint, creds.APIKey, creds.APISecret)
resp.DataSourceData = client
resp.ResourceData = client
}Why each step matters:
Unknown-value guards. During planning, an attribute wired to another resource's output is unknown, not null. Without the guard the provider silently treats it as empty, falls through the chain, and authenticates as the wrong identity — or fails with a misleading "missing credentials" error. Name the environment-variable workaround in the guard message.
The sentinel check picks the right message. "You gave me nothing" (actionable list of options) is a different failure from "you gave me something broken" (show the parse error). Collapsing them into one message is how providers end up with users pasting secrets into config to debug.
Log the source, never the secret. Knowing which source won is the single most useful debugging fact and costs nothing to log.
Diagnostics That Unblock Users
An authentication error message is the provider's most-read documentation. Every credential failure diagnostic should name:
Every source tried, in order, with why it was skipped — the
ChainErrorprovides this.aws-sdk-go-basedoes the same with itsNoValidCredentialSourcesError.The exact environment variable names and the credentials file path and profile that were consulted — not "set the appropriate environment variables".
A documentation URL for the provider's authentication guide.
Use warnings (not errors) for conditions that are suspicious but not fatal,
naming what took precedence: a profile set while environment credentials
are also present (which wins?), or a credentials file with group/world-read
permissions (suggest chmod 0600).
Secret Hygiene
Give the
CredentialstypeString()andGoString()methods that redact secret fields, so a stray%v,%+v, or error wrap can never leak a secret into logs or diagnostics.Never include credential values in diagnostics, log lines, or wrapped errors — log the source name and non-secret identifiers only.
Warn when a credentials file is readable by other users (
info.Mode().Perm()&0o077 != 0); skip this check on Windows, where POSIX permission bits are not meaningful.
Configure-Time Validation
Resolve the chain eagerly in Configure — never lazily on first resource
use — so a credentials problem fails one time, at plan, with a good message,
instead of failing in the middle of an apply. If the API has a cheap
identity endpoint (the equivalent of AWS sts:GetCallerIdentity or a
/whoami), call it after resolving credentials so invalid (not just
missing) credentials also fail at configure time. Gate it behind a
skip_credentials_validation attribute for air-gapped or stubbed
environments.
Unit Testing the Chain
The chain is pure logic — test it with unit tests (Test prefix, no
TF_ACC), not acceptance tests. Make the environment injectable (a
getenv func(string) string field defaulting to os.Getenv, or use
t.Setenv) and point the file provider at t.TempDir() fixtures. The
tests that matter:
Per-source: each provider returns its credentials when set and
ErrNoCredentialswhen incomplete (a key with no secret is incomplete).Precedence: static beats env; env beats file; chain falls through to the file when nothing above supplies a complete set.
Failure aggregation: with all sources empty,
errors.Is(err, ErrNoCredentials)is true and the message names every source.Hard errors: a malformed credentials file or an explicitly requested profile that does not exist surfaces a descriptive error rather than silently falling through (a merely defaulted profile falls through).
Redaction:
fmt.Sprintf("%v")and%+vof aCredentialsvalue never contain the secret.
Full test examples are in references/credential-chain.md.
Checklist
[ ] All auth attributes
Optional; secrets markedSensitive: true[ ] Attribute descriptions name their environment-variable fallbacks
[ ] Unknown-value guards on every auth attribute in
Configure[ ] Chain precedence: static config > env vars > credentials file > platform identity
[ ] Secrets resolved as a complete set; non-secret settings field-by-field
[ ] Sentinel
ErrNoCredentialsdistinguishes fall-through from hard failure[ ] Missing-credentials diagnostic lists every source tried + docs URL
[ ]
Credentialstype redacts secrets inString()/GoString()[ ] Credentials-file permission warning (non-Windows)
[ ] Eager resolution in
Configure; optional identity check withskip_credentials_validation[ ] Unit tests cover per-source behavior, precedence, aggregation, redaction
[ ] No credential value ever logged or embedded in an error
Related Skills
Use the new-terraform-provider skill (if available) to scaffold the
provider this configuration lives in, and the provider-resources skill for
consuming the configured client from resources and data sources.
Files
- ATTRIBUTION.mdAdded by AutoGineer877 B
- LICENSELicence file added by AutoGineer16.3 KiB
- SKILL.md13.8 KiB
- references/case-studies.md6.1 KiB
- references/credential-chain.md17.7 KiB
references/case-studies.md
Credential Chain Case Studies
Two production designs at opposite ends of the complexity scale. Read these
to calibrate how much chain your provider actually needs — then implement
with the generic pattern in credential-chain.md.
Case study 1: The AWS provider (aws-sdk-go-base)
The Terraform AWS provider, the AWSCC provider, and the S3 backend all
resolve credentials through one shared library,
hashicorp/aws-sdk-go-base
(MPL-2.0). Its entry point GetAwsConfig(ctx, *Config) is the most
battle-tested credential chain in the Terraform ecosystem.
Resolution order
Static credentials short-circuit. If the provider config carries any of access key / secret key / token, it builds a static credentials provider immediately and skips the rest of the chain. Explicit config always wins, and partial static credentials fail loudly rather than falling through — a deliberate choice for secrets.
The SDK default chain, with the profile pinned first when the provider config sets one. The AWS SDK then resolves, in order: environment variables → shared credentials/config files (including SSO, web-identity, and source-profile assume-role directives declared inside those files) → container credentials → EC2 instance metadata (IMDS).
Explicit web identity override. An
assume_role_with_web_identityblock replaces whatever the default chain produced with an STS web-identity provider (validated: role ARN required, exactly one token source).Assume-role wrapping.
assume_roleis a list; each entry wraps the previously resolved credentials in an STS assume-role provider, enabling role chaining (credentials → role A → role B). Each hop carries its own session name, external ID, policy, tags, and duration, wrapped in a credentials cache.
Techniques worth copying regardless of scale
Eager verification. The resolved provider's
Retrieve()is called during configuration, and — unlessskip_credentials_validationis set — ansts:GetCallerIdentitycall proves the credentials actually work. Failures surface at plan time with configuration-shaped errors instead of mid-apply with API-shaped ones.NoValidCredentialSourcesError. The missing-credentials diagnostic embeds a caller-supplied documentation URL (CallerDocumentationURL) and the underlying error. Every downstream product (provider, backend) points users at its own auth docs through the same error type.Conflict warnings. If both a
profileand static env-var credentials are present, it emits a "configuration conflict" warning explaining which source took precedence — and if resolution then fails, the error is annotated with that context.Endpoint injection for the chain itself. Custom STS/SSO/IAM endpoints are threaded into the chain's own calls, so air-gapped and government-partition deployments can authenticate at all. If your platform has regional or private auth endpoints, the chain must honor them too.
Legacy env-var migration. Deprecated variables (e.g.
AWS_METADATA_URL) are still read, with a warning naming the replacement. Renaming an env var without a migration warning breaks users silently.
What this scale of chain costs
Config carries dozens of fields (proxies, CA bundles, retry modes, IMDS
toggles, account-ID allow/deny lists), and the behavioral spec lives in a
very large test suite exercising every precedence branch. Do not start
here — grow toward it.
Case study 2: A hand-rolled chain in a small provider
A recently built provider for an appliance-style API (IBM Power HMC) needed
exactly three sources — provider block, environment variables, and a YAML
credentials file with named profiles — and implemented the chain by hand in
a self-contained internal/credentials package, the same shape as
credential-chain.md. Its design choices, generalized:
A one-method
Providerinterface + sentinel error.Retrieve(ctx)returns the credentials orErrNoCredentialsto mean "fall through". An aggregateChainErrorrecords every source tried and implementsIs(ErrNoCredentials)so the provider'sConfigurecan pick between "here is how to supply credentials" and "your file is broken" with a singleerrors.Is.Secrets as a set; connection settings field-by-field. Username and password resolve together through the chain, while
hostandinsecureeach independently follow config > env > file profile > default. A profile can therefore hold only connection settings while credentials come from the environment.Redaction at the type level. The credentials struct's
String()/GoString()print***REDACTED***for the secret, making the value log-safe by construction.File semantics tuned for humans. A missing file or profile that was merely defaulted falls through silently; a missing file at an explicitly configured path, an explicitly requested profile that does not exist, or a malformed file are hard errors — each one is a user mistake worth reporting precisely.
Warnings for the almost-right. Group/world-readable credentials files produce a
chmod 0600warning; disabling TLS verification produces a warning naming the risk.Hermetic unit tests. An injectable
getenvfunction and temp-dir credential files make precedence tests (StaticWins,EnvBeatsFile,FallsThroughToFile), aggregate-error tests, and redaction tests run without touching the real environment.
Choosing your chain
| Your situation | Chain to build |
|---|---|
| Single API token, no files | Static + env. Two providers, still worth the chain for its error aggregation |
| Human operators, multiple accounts | Add a credentials file with profiles (case study 2) |
| Runs inside the platform it manages | Add a platform-identity source (metadata/OIDC) at the end |
| Delegation/role semantics in the API | Add assume-role wrapping on top of the chain (case study 1) |
Whatever the size: keep the order in one constructor, aggregate every
skipped source into the failure message, and validate eagerly in
Configure.
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Needs an API key
Security
No issues found by our static scan· No issues found
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Published by
- HashiCorp
- Publisher
- HashiCorp (Official)
- Source
- hashicorp/agent-skills · plugins/terraform/skills/provider-configuration · commit 5e30fa5
- Licence
- Mozilla Public License 2.0 (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by HashiCorp.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download provider-configuration.zip