Configuration System¶
Functualize uses a layered TOML-based configuration system that resolves values from multiple sources with a clear priority order. This guide covers how config files are discovered, how values are resolved, how to use per-job configuration sections with Pydantic models, and how to declare a credential.
Overview¶
The configuration system provides:
- Preset factory functions — named configuration strategies (
classic,twelve_factor,env_only,remote_first) - Upward directory search for config files starting from the current working directory
- Base + environment overlay pattern using TOML files
- Environment variable precedence over file-based config
- Per-job sections that map directly to
JobConfigPydantic models - Tracking of which settings were accessed and where values came from
- Credentials declared with
Secret[str], masked on every surface that renders configuration - Remote configuration — scoped
[[vault_secret]]declarations synced into an encrypted local vault
Framework settings and job configuration are separate¶
The config.base.toml and environment overlays below feed a job's
ResolutionChain. Framework settings such as [shell] program, [plugins]
strict, and [cli] output belong instead in .functualize.toml,
pyproject.toml under [tool.functualize], or the global functualize
config.toml. For those settings, the nearest project file wins, root = true
stops the upward walk, and CLI flags and FUNCTUALIZE_* variables outrank
files. Use func builtin config path to see the participating files and any
unknown keys; func builtin info --json exposes the same findings in
config.unknown_keys. Their complete key and environment-name reference is
in the CLI configuration guide.
Configuration Presets¶
Functualize provides preset factory functions that return a ConfigSources instance configured for common deployment scenarios:
from functualize.app import FunctualizeApp, JobSources, classic, twelve_factor, env_only, remote_first
# Classic: CLI → Env → Files (upward search) → Defaults (the default behavior)
app = FunctualizeApp(name="myapp", config_sources=classic())
# Twelve-factor: CLI → Env → Defaults (no file discovery)
app = FunctualizeApp(name="myapp", config_sources=twelve_factor())
# Env-only: CLI → Env → Defaults (minimal, with optional dotenv)
app = FunctualizeApp(name="myapp", config_sources=env_only(dotenv=True))
# Remote-first: CLI → Vault → Env → Files → Defaults
app = FunctualizeApp(name="myapp", config_sources=remote_first())
remote_first() requires a provider plugin
It resolves scoped [[vault_secret]] declarations from the project's
encrypted local vault, which func builtin vault sync fills. Selecting it
with no remote provider registered raises at construction rather than
quietly resolving from local files. See
Remote Configuration.
Before 0.2.4 this preset silently was classic(): it returned
config_resolution_chain=None and no boot path built a remote source, so
an operator choosing it for AWS Secrets Manager got local files and
environment variables with no warning.
When no config_sources is specified, the default behavior is identical to classic().
You can also create custom presets — any function returning a ConfigSources instance works:
from functualize.app import ConfigSources
def my_custom_preset(**kwargs) -> ConfigSources:
return ConfigSources(dotenv=True, file_pattern=r"^app_config\.(\w+)\.toml$")
Config Directory Discovery¶
When a FunctualizeApp is instantiated, it discovers the config directory by searching upward from the current working directory for files matching a regex pattern.
from functualize.app import FunctualizeApp, JobSources
app = FunctualizeApp(
name="myapp",
job_sources=JobSources(directories=["jobs"]),
)
The name parameter serves as the fallback identifier. If no config files are found during the upward search, Functualize falls back to ~/.config/<name>/ (for example ~/.config/myapp/). This XDG-style path is used on every platform — discover_config_path returns Path.home() / ".config" / name directly, without any OS-specific branch.
Upward Directory Walk¶
The discovery algorithm works as follows:
- Start at the current working directory (
os.getcwd()) - List files in the current directory and match against the config file regex
- If matches are found, use that directory as the config path
- If no matches, move to the parent directory and repeat
- Stop at the nearest directory whose project config declares
root = true(inclusive), the user's home directory (~), or the filesystem root (/), whichever is reached first — see Project boundaries androot = true - If no matches are found anywhere, fall back to
~/.config/<name>/
flowchart TD
A[Start at CWD] --> B{Files match config regex?}
B -->|Yes| C[Use this directory as config path]
B -->|No| D{Reached home dir or root?}
D -->|No| E[Move to parent directory]
E --> B
D -->|Yes| F[Fall back to ~/.config/name]
CLI Override
The --config-directory global CLI option overrides the discovered config path entirely. When provided, no upward search is performed.
Project boundaries and root = true¶
Functualize finds "the project" by walking upward from the current directory. A project config file that sets root = true says my project ends here; nothing above me is part of it. Every upward search stops at that directory, inclusive, so a nested project that declares a root sees only its own sources, settings, job configuration and state. Without the marker a nested project inherits from its ancestors, exactly as before — inheritance is the reason to leave it out.
# outer/nested/.functualize.toml (or [tool.functualize] in pyproject.toml,
# or .functualize/.functualize.toml)
root = true
Only the boolean true stops a walk; root = "true" is a string and does not.
Where project configuration is declared¶
| # | Declaration | Example | Found by | Above a root = true |
|---|---|---|---|---|
| 1 | pyproject.toml table [tool.functualize] |
[tool.functualize] root = true |
Walk A, first choice in its directory. A pyproject.toml without the table is not a project file |
not read |
| 2 | .functualize.toml |
jobs_directories = ["jobs"] |
Walk A, second choice | not read |
| 3 | .functualize/.functualize.toml |
root = true |
Walk A, third choice | not read |
| 4 | The .functualize/ folder and its jobs/, lib/, plugins/ |
.functualize/jobs/deploy.py |
jobs/, lib/: every walk-A layer; plugins/ and the folder itself: walk C |
not used |
| 5 | Directory keys in 1–3: jobs_directories, import_libs, plugins_directories, extra_directories, exclude_patterns |
plugins_directories = ["../team_plugins"] |
Walk A; relative paths resolve against the declaring file | not read; an explicit path in the root's own file may point anywhere |
| 6 | root = true in 1–3 |
root = true |
Every walk | — |
| 7 | User-wide ~/.config/functualize/config.toml |
[cli] output = "json" |
Read directly, not by a walk | still applies |
| 8 | Environment variables FUNCTUALIZE_<SECTION>_<KEY> and CLI flags |
FUNCTUALIZE_CLI_OUTPUT=json |
The invocation | still applies, highest priority |
| 9 | Job config files config.base.toml, config.<env>.toml |
[greeter.greet] greeting = "hi" |
Walk B | not read, even for a key the nested file omits |
| 10 | Python API: JobSources, ConfigSources, a supplied resolution chain |
JobSources(children={...}) |
Code | unchanged: explicit |
| 11 | Single-file mode func file.py job |
func deploy.py run |
The named file | no project involved |
The four walks, and where each stops¶
| Walk | Looks for | Stops at | Decides |
|---|---|---|---|
| A — project config files | In each directory, the first of declarations 1–3 | the first layer with root = true, else the filesystem root; then the user-wide file |
func's own settings, the job, library, plugin and extra directories, func builtin config path |
| Settings list | Walk A's files, kept apart | as walk A | the TUI settings panel's layers and save targets, cli.* / tui.* resolution |
| B — job config directory | config.base.toml / config.<env>.toml |
the nearest root marker or ~, whichever comes first — both for finding the directory and for layering the files above it. --config-directory layers from the chosen directory up to the nearest root marker at or above it |
each job's own settings |
C — the .functualize/ folder |
the nearest .functualize/ |
the root marker's directory, inclusive | Mode: project vs standalone, where runs, scopes, freshness, the discovery cache and the vault live, the convention plugins |
The project's identity — the key for its state, cache and vault — is the directory holding its .functualize/; with none, the directory that declares root = true, so the root and every subfolder of it are one project; with neither, the current directory, as before.
Before and after¶
Tree: outer/ has a .functualize.toml, a .functualize/ folder and job outer-only; outer/nested/.functualize.toml says root = true and has job nested-only. Run from outer/nested.
| Case | Before | After |
|---|---|---|
Nested root with its own .functualize/ |
outer-only is listed and runs; the ancestor's lib/ is importable; the ancestor's declared jobs_directories / extra_directories are listed |
nested-only only; func outer-only → Unknown command, exit 1 |
Nested root with no .functualize/ |
the ancestor's plugin runs; Mode: project names outer/.functualize; runs, scopes and the vault are the ancestor's |
the ancestor's plugin does not load; Mode: standalone; state and vault are keyed by outer/nested, the same from any subfolder; the ancestor's files are untouched |
Ancestor [cli] show_timing = true |
the TUI settings resolve true; func builtin config show says the default |
both say the default |
Ancestor config.base.toml with [greeter.greet] greeting = "ANCESTOR" |
the nested job reads ANCESTOR, even under a nested config.base.toml that omits the key |
the nested job reads its own, environment, user-global or default value |
func builtin config path from outer/nested/sub (root in .functualize/.functualize.toml) |
sub/pyproject.toml ✗ and sub/.functualize.toml ✗, the root's file not listed |
the root's .functualize/.functualize.toml ○ found (it declares only the marker), the subfolder's expected locations ✗, and no line for outer/'s own .functualize.toml |
No root = true anywhere |
ancestor sources inherited | unchanged |
Migrating¶
You relied on an ancestor's jobs, libraries, plugins or job configuration under root = true. That configuration contradicts itself: root = true is the declaration that nothing above applies. Either delete root = true to inherit again, or keep the stop and declare the shared path explicitly in the root's own file:
Your nested root had no .functualize/ and used its ancestor's. Its runs, workflow scopes and vault were the ancestor's. After upgrading the root starts empty, and nothing is moved or deleted: the ancestor's folder and vault stay as they are. To keep records in the repository, run from the root:
mkdir .functualize
cp ../.functualize/runs.json ../.functualize/scopes.json .functualize/ # only the files you want
func builtin data clear # fresh.json and cache.json are derived; let them rebuild
func builtin vault put --job deploy --field api_token --stdin # once per secret you need here
The vault key is per machine, not per project, so no key moves; the secrets do not either. Put each one you need again, or run func builtin vault sync for the ones declared with [[vault_secret]]. An ancestor secret enters the nested vault only if you put it there. func builtin data show then reports Mode: project (.functualize/ found at <root>/.functualize) with the copied run and scope counts, from the root and from every subfolder, and func builtin vault list lists only what you put.
Config File Pattern¶
By default, Functualize looks for files matching the regex pattern:
This matches filenames like config.base.toml, config.dev.toml, config.prod.toml, etc.
Custom Regex Pattern¶
You can customize the pattern via the file_pattern in ConfigSources:
from functualize.app import FunctualizeApp, JobSources, ConfigSources
app = FunctualizeApp(
name="myapp",
job_sources=JobSources(directories=["jobs"]),
config_sources=ConfigSources(file_pattern=r"^settings\.(\w+)\.toml$"), # matches settings.base.toml, etc.
)
The regex is applied to filenames (not full paths), both when anchoring the config directory during the upward walk and when the file source selects which files to parse. Files still need an extension that a registered format provider handles — .toml alone by default. A plugin can register more by calling app.config_registry.register_format_provider(...), or a package can declare one in the functualize.format_providers entry-point group.
Base Config and Environment Overlays¶
Functualize loads configuration in two layers:
- Base config —
config.base.toml(always loaded first) - Environment overlay —
config.{env}.toml(merged on top of base)
The environment name comes from the first of these that is set to a valid name, defaulting to "DEV":
FUNCTUALIZE_ENVENVIRONMENTENV
A value that is blank, or that isn't a valid filename segment ([A-Za-z0-9_-]+), is skipped rather than being an error — the next variable is tried. This matters for ENV in particular: POSIX sh/ksh set it to the path of a startup file, which is not an environment name.
Matching is case-insensitive, comparing the environment name against the file's slot. The filename is not lowercased, so config.Prod.toml is selectable too.
| Environment value | Overlay file loaded |
|---|---|
| (not set) | config.dev.toml |
DEV |
config.dev.toml |
PROD |
config.prod.toml |
STAGING |
config.staging.toml |
A file naming any other environment is discovered but never merged. func's inline TUI lists it as ○ inactive, so a file that plainly exists but isn't taking effect is visible rather than mysterious.
Note
The overlay is deep-merged on top of the base config through the file's registered FormatProvider — the mechanism is format-agnostic rather than tied to any one parser, so a format a plugin registers behaves the same way. Keys in the overlay override the same keys in the base file; keys only present in the base file are preserved.
Precedence across directories
When config files exist in several directories (project, parents, global), the nearest directory wins overall, and within a single directory the overlay beats that directory's base. A project's config.base.toml therefore still outranks a global config.prod.toml — the ladder is about whose config it is, not which environment it names.
Resolution Priority¶
Configuration values are resolved with the following priority (highest to lowest):
flowchart TD
A[Request config value] --> B{Environment variable set?}
B -->|Yes| C[Use env var value]
B -->|No| D{Key in env-specific config?}
D -->|Yes| E[Use env config value]
D -->|No| F{Key in base config?}
F -->|Yes| G[Use base config value]
F -->|No| H{Default provided?}
H -->|Yes| I[Use default value]
H -->|No| J[Return None or raise error]
Environment Variable Convention¶
Environment variables follow the SECTION_KEY naming convention — both the section name and key name are uppercased and joined with an underscore.
| Section | Key | Environment Variable |
|---|---|---|
server |
api_url |
SERVER_API_URL |
database |
host |
DATABASE_HOST |
general |
debug |
GENERAL_DEBUG |
When the section is an empty string, only the key name (uppercased) is used as the environment variable name.
Environment Variables and .env Files¶
Functualize resolves environment variables from os.environ at config resolution time. A .env file can populate os.environ with additional values in two ways: the --dotenv-file CLI flag, or the app's ConfigSources.dotenv / dotenv_path settings, which boot honors before building the resolution chain.
How .env Loading Works¶
# Explicit: load .env before config resolution runs
myapp --dotenv-file .env data-sync run
# No flag: loading depends on the app's ConfigSources (see below)
myapp data-sync run
When --dotenv-file is passed, the CLI adapter calls python-dotenv's load_dotenv() in the root group callback — before any subcommand executes and before config resolution runs. This means .env values are available in os.environ by the time the resolution chain reads them.
Independently of the flag, application boot loads a .env file when ConfigSources.dotenv is true (the dataclass default) or ConfigSources.dotenv_path names a file — at the very start of both boot paths, so EnvSource sees the values. Loading always uses override=False: values already in the environment win.
from functualize.app import FunctualizeApp, ConfigSources
from functualize.app.presets import env_only, twelve_factor
app = FunctualizeApp("myapp") # dotenv=True default: loads ./.env if present
app = FunctualizeApp("myapp", config_sources=ConfigSources(dotenv=False)) # never loads
app = FunctualizeApp("myapp", config_sources=env_only(dotenv_path=".env.local")) # explicit path
app = FunctualizeApp("myapp", config_sources=twelve_factor()) # dotenv=False default: pure 12-factor
How .env Affects Config File Selection¶
Because .env is loaded into os.environ before boot runs, it can influence which config files get loaded. The ENVIRONMENT variable (read from os.environ during boot) controls the environment overlay:
# This loads .env → sets ENVIRONMENT=prod → boot loads config.base.toml + config.prod.toml
myapp --dotenv-file .env data-sync run
Without --dotenv-file, the ENVIRONMENT variable must be set in the shell:
In both cases, the config system loads config.base.toml first, then merges config.prod.toml on top (values in the overlay override the base).
Precedence: Shell vs .env¶
Python-dotenv does not override existing shell environment variables by default. This means:
| Source | Priority | Example |
|---|---|---|
| CLI flags | Highest | --batch-size 2000 |
| Shell environment variables | High | export DATA_SYNC_BATCH_SIZE=500 |
.env file values (via --dotenv-file) |
Medium | DATA_SYNC_BATCH_SIZE=100 in .env |
| Config files (TOML) | Low | batch_size = 50 in config.base.toml |
| Pydantic model defaults | Lowest | Field(default=25) |
If DATA_SYNC_BATCH_SIZE=500 is already set in your shell, a .env file containing DATA_SYNC_BATCH_SIZE=100 will not override it. The shell value wins.
This applies to the ENVIRONMENT variable too — if your shell has export ENVIRONMENT=staging and your .env has ENVIRONMENT=prod, the staging overlay is used because shell takes precedence.
Boot-Time .env Loading Rules¶
Boot's .env handling is driven entirely by ConfigSources:
dotenv=True(theConfigSourcesdefault and theenv_only()preset default): boot loads./.envfrom the current working directory if it exists — missing file is not an error.dotenv_path="...": boot loads that specific file; a missing file logs a warning and skips.dotenv=False(thetwelve_factor()preset default): boot never callsload_dotenv().- Loading happens at the very start of boot (both the standard and static paths), before the resolution chain is built.
- Only the current directory is checked — there is no upward directory scan, so a
.envforgotten in a parent directory is never silently picked up.
For the func CLI, the resolved CLI config (dotenv / dotenv_path from pyproject.toml [tool.functualize], FUNCTUALIZE_DOTENV, FUNCTUALIZE_DOTENV_PATH) controls loading, with --dotenv-file / --no-dotenv as overrides. The CLI default is dotenv = false — opt in per project.
Disabling for reproducibility
Automatic .env loading can cause differences between environments. For CI or production, use twelve_factor() (or ConfigSources(dotenv=False), or --no-dotenv on the CLI) so environment variables come only from the orchestrator.
Practical Patterns¶
Local development with .env:
# Create a .env for local secrets
echo "DATA_SYNC_API_KEY=dev-secret-123" > .env
echo "DATA_SYNC_API_URL=http://localhost:8080" >> .env
# Run with dotenv
myapp --dotenv-file .env data-sync run
CI/Docker (no .env needed):
# Real env vars are set by the orchestrator
export DATA_SYNC_API_KEY=$VAULT_SECRET
export DATA_SYNC_API_URL=https://api.prod.example.com
myapp data-sync run
Verifying what's loaded:
# builtin info displays whether a dotenv file was loaded and its contents
myapp --dotenv-file .env builtin info all
Introspection with builtin info¶
The builtin info command reports the current dotenv status:
- If
--dotenv-filewas passed, it displays the file path and its key-value contents - If no dotenv file was loaded, it prints a notice: "No dotenv file loaded"
- Use
--show-env-varsto see the fullos.environsnapshot (including any values injected from.env)
Per-Job Config Sections¶
Each job can have its own config section where the section name matches the JOB_GROUP value defined in the job module. When a job uses a JobConfig Pydantic model, fields are resolved from the matching section.
# config.base.toml
[general]
debug = false
log_format = "json"
[data_sync]
api_url = "https://api.example.com"
batch_size = 100
timeout = 30
[report_gen]
output_dir = "./reports"
format = "pdf"
In this example, a job with JOB_GROUP = "data_sync" reads from the [data_sync] section.
JobConfig Field Resolution¶
When a job function declares a JobConfig Pydantic model parameter, each field is resolved with this precedence:
- Runtime override — a value deposited by
rc.config.set("batch_size", 200)during the run - CLI argument — explicitly passed via the command line (e.g.,
--batch-size 200) - Vault — a stored value for a secret-marked job config field
- Environment variable —
JOBNAME_FIELDNAMEuppercased (e.g.,DATA_SYNC_BATCH_SIZE) - Config file section — the
[job_name]section in the loaded config files - Model default — the default value defined on the Pydantic field
An override outranks the command line: it is written after the command line was read, and it is what the rest of the run reads back.
flowchart TD
A[Resolve JobConfig field] --> B{CLI argument provided?}
B -->|Yes| C[Use CLI value]
B -->|No| V{Scoped vault entry stored?}
V -->|Yes| W[Use readable vault value]
V -->|No| D{Env var JOBNAME_FIELDNAME set?}
D -->|Yes| E[Use env var value]
D -->|No| F{Key in config section?}
F -->|Yes| G[Use config file value]
F -->|No| H{Field has default?}
H -->|Yes| I[Use model default]
H -->|No| J[Pydantic ValidationError]
Warning
If a required field (no default value) has no value from any source, an interactive surface asks for it. Off one — CI, a pipe, a cron job — Pydantic's ValidationError is reported with field-level details, the config files that were actually read, and the environment variable that would set the field.
Credentials¶
A credential is an ordinary config field that you mark as secret. Nothing else about it changes: it resolves through the same ladder, in the same section, under the same environment variable name.
from pydantic import BaseModel, Field
from functualize.job import RunContext
from functualize.types import Secret
class SyncConfig(BaseModel):
api_url: str = Field(default="https://api.example.com")
credential: Secret[str] = Field(description="API token")
def sync(config: SyncConfig, rc: RunContext) -> None:
rc.log(f"connecting to {config.api_url}")
client.authenticate(config.credential.get_secret_value())
Secret[str] is the declaration. It is a real type: it validates from a plain
string, refuses to render its value in str(), repr() or a log line, serializes
to the mask in JSON (model_dump_json(), model_dump(mode="json")), and yields
the real value only through .get_secret_value().
A plain model_dump() returns the Secret object itself rather than the mask.
That is deliberate: the framework passes config models between jobs by dumping
and rebuilding them — rc.invoke(child, config=…) is the common case — and
flattening the wrapper there would hand the child ••• instead of the
credential, silently. The object still masks itself wherever it is rendered, so
nothing leaks by keeping it.
A field that must stay a plain str for some other reason can carry the marker
instead, and is treated identically everywhere:
Both markers answer one question — is this field a secret? — asked in one
place. Every surface that renders configuration asks it: func builtin info
--job, func builtin env, the inline TUI's config table and source-chain
view, and the bar while you type into the field. None of them will show you the
value.
Detection is by declaration, never by name
A field called sort_key is not a secret, and a field called x is one if
you declared it so. Name matching was tried and removed: it masked the wrong
fields and, far worse, left real credentials in cleartext whenever the name
did not match a pattern.
Finding out what a job needs¶
$ SYNC_CREDENTIAL=hunter2-real func builtin env sync
export SYNC_API_URL=https://api.example.com # source: file
export SYNC_CREDENTIAL='•••' # source: env
The comment names the kind of source a value came from — file, env, cli,
default — not the particular file. A plain value is printed unquoted; the mask
is quoted because it is not a value you could paste back.
Unset fields come back commented, so the output doubles as a .env skeleton and
"is the credential configured?" has a visible answer:
func builtin env <job> -- <command> runs a command with the resolved values in
its environment instead of printing them. Secret fields are masked in the
print form and omitted from the exec environment unless you pass
--include-secrets, so the default output is safe to paste into a bug report
while the exec form never puts a credential in a child process it did not ask
for.
Where credentials come from¶
Set them in the environment, or in a .env file that is not committed — or
name a remote secret store in a [[vault_secret]] block, covered in
Remote Configuration.
A ${env:VAR} interpolation syntax was considered and rejected, and that
decision stands. It reads as indirection but resolves to the same environment
variable the field would have read anyway — so it adds a syntax, a parse step
and a failure mode, and buys nothing except the appearance of a secrets
feature. That appearance is the danger: it invites putting the real value there
"just for now". A field that resolves from the environment does so because that
is the ladder, not because a config file pointed at it.
A provider source is a different thing: aws-sm://prod/db-password names a
location the config file could not otherwise reach. Put that source in an
explicit [[vault_secret]] block with a group or job and a secret-marked
field. The ordinary config section may still hold a literal fallback value;
an inline provider URI there is rejected with replacement guidance.
A secret of your own¶
The vault started as a cache for values fetched from AWS Secrets Manager or Bitwarden. It is also, and more simply, somewhere to put one secret you have — no provider, no account, no preset:
$ func builtin vault init # once per machine
$ func builtin vault put --job deploy --field api_token # masked prompt
$ func deploy # the job receives it
The identity is a scope, target, field, and environment. Use --group for
a group's subject address, --job for an ungrouped leaf job, or both flags for
a grouped job: --group deploy --job web --field token. A dotted
--job deploy.web is refused; split it into the two flags. A function
parameter is an invocation input and cannot be a vault target. The identity
is checked against the live schema before the value is read, so a typo costs
you nothing you have already typed. The active environment is selected by
FUNCTUALIZE_ENV, ENVIRONMENT, or ENV (default dev); there is no vault
environment flag. list and inspect show the stored or resolved environment
and never print the secret.
For a group address such as deploy.web, resolution tries the active
environment at deploy.web, then deploy, followed by shared (base) entries
at deploy.web, then deploy. A job entry is exact, with active before shared.
An existing three-part key remains a readable shared entry. If the first
present entry cannot be opened, the run stops; it does not try another entry
or a plaintext source. remove deletes the exact active-environment key, so
inspect or list is useful before deleting an older shared entry.
The stored value resolves through the ordinary configuration chain, above the environment and config files and below an explicit argument:
Nothing changes for a project that has never used the vault.
In CI, and without a keyring¶
Neither init nor a keyring is required. The store is created by the first
write, so the whole recipe is:
export FUNCTUALIZE_VAULT_KEY="$CI_VAULT_KEY"
func builtin vault init --key-source env # optional: fail fast if unset
echo "$TOKEN" | func builtin vault put --job deploy --field api_token --stdin
func deploy
put never prompts when it has no terminal — it refuses and tells you to pass
--stdin or --file, because a pipeline that blocks on input nobody is sending
never reports anything at all.
Remote Configuration¶
A [[vault_secret]] block names where one secret-marked group option or
job config field gets a value. It is separate from ordinary config sections:
[data-sync]
region = "eu-west-1" # an ordinary value, untouched
docs_url = "https://docs.example.com" # an ordinary URL, untouched
[[vault_secret]]
job = "data-sync"
field = "password"
source = "aws-sm://prod/db-password"
[[vault_secret]]
group = "deploy"
field = "token"
source = "aws-ssm:///platform/deploy-token"
Each block names group, a leaf job, or both, plus field and source.
For example, group = "deploy" with job = "web" addresses the grouped
job deploy.web. A dotted job value is refused with the split spelling.
The target and field must exist and be marked secret. config.base.toml
declarations are shared (base); config.prod.toml declarations belong to
prod. Sync reads base and the selected overlay and never fetches another
environment's provider. Duplicate identities within the same environment,
including across files, fail before a provider is contacted. The source is
a location, never the credential value.
The old inline form, such as password = "aws-sm://prod/db-password", is no
longer a vault declaration. A secret-marked field using it fails with guidance
to move the reference into [[vault_secret]]. Ordinary URLs in non-secret
fields remain strings.
The vault, and why reads never hit the network¶
Values are fetched by func builtin vault sync and written to a per-project
encrypted store. A job run reads that store and never the network.
That is a deliberate trade (ADR-016). Resolving provider references live would put a network round-trip and a 30-second timeout between the operator and every job run, including runs of jobs that use no secret at all — and it would stop you working offline. Here the network is touched when you sync.
flowchart LR
sync["func builtin vault sync"] -->|"fetch"| remote["AWS / Bitwarden / ..."]
sync -->|"encrypt + store"| vault[("local vault")]
run["func data-sync"] -->|"read"| vault
run -.->|"never"| remote
Only the value is encrypted. The scoped identity, source, provider and
synced_at are stored in clear on purpose, so vault list can report what is
held and how fresh it is on a machine that cannot open the store. None of them
is the secret: knowing that job data-sync field password came from
aws-sm://prod/db-password reveals nothing the config file did not already say
out loud.
Each project gets its own vault, keyed the same way the discovery cache is. A repository you cloned to look at cannot read the secrets of a project you actually work on.
Getting started¶
# 1. Install a provider plugin.
pip install functualize-secrets-aws # aws-sm, aws-ssm (opt-in)
pip install functualize-secrets-bitwarden # bws, bwpm (separate: its SDK has no musl build)
# If using the standalone binary, add AWS to its bundled Python instead:
func builtin plugin install functualize-secrets-aws
# 2. Create a vault key and keep it somewhere your shell can read.
export FUNCTUALIZE_VAULT_KEY=$(func builtin vault keygen)
# 3. Declare [[vault_secret]] blocks in your config file, then fill the vault.
func builtin vault sync
# 4. Run jobs as usual. Nothing else contacts the network.
func data-sync
Select the preset in your main.py:
from functualize.app import FunctualizeApp, JobSources, remote_first
app = FunctualizeApp(
name="my-platform",
job_sources=JobSources(directories=["my_platform.jobs"]),
config_sources=remote_first(),
)
Where the vault sits in the chain¶
remote_first() builds CLI → Vault → Env → Files → Defaults. A runtime
override sits above the chain. The same order applies to group options and
job config fields. A synced secret outranks the environment and the config
file; an explicit CLI argument still wins.
Note what that means in practice: once job data-sync field password is in the vault, an
environment variable no longer overrides it. That is the preset's whole
proposition — the value comes from the store you named — but it is a change
from classic() worth knowing before you switch.
Reading a group's secret from a job¶
Config fields reach a job because the job declared them. Sometimes the job only
learns which target it is working on while it runs — one of several
environments, one subject of many — and needs that target's credential. Ask the
injected Vault capability for it:
from functualize.app.vault import VaultEntryMissingError
from functualize.job import Log, Vault
from functualize.types import Secret
def deploy_target(vault: Vault, log: Log) -> None:
target = "cloudflare_dev.d1.main" # decided at run time
try:
token: Secret[str] = vault.read(target, "api_token")
except VaultEntryMissingError:
log(f"no credential provisioned for {target}; skipping it")
return
publish(target, token) # unwrap only inside the trusted call
vault is supplied by the framework, never by the caller: it is not a CLI flag,
an MCP argument or a TUI field. read(group, field) takes the group path (or a
subject address) and the field, and nothing else — no environment, no source.
Which entry it returns. The same group lookup config resolution uses, and nothing past it:
- the active environment's entry for the exact group, then its nearest
ancestors —
cloudflare_dev.d1.main,cloudflare_dev.d1,cloudflare_dev; - then the shared slot, in the same order.
The first entry that is stored wins, whether you typed it with vault put or
vault sync wrote it. So an active-environment ancestor beats a shared entry for
the exact group. Job-scope entries and other named environments are never
candidates, and the environment is the one the app already selected for the run
(FUNCTUALIZE_ENV, see above).
What can go wrong, and how to tell.
| Situation | You get |
|---|---|
| Nothing stored at any candidate, or the project has no vault yet | VaultEntryMissingError |
| The first stored candidate cannot be opened (no key, wrong key) | VaultEntryUnreadableError |
| The first stored candidate will not authenticate | VaultDecryptionError |
All three are importable from functualize.app.vault and are VaultErrors. A
missing entry is the one to decide on. The other two mean something was
provisioned and this machine cannot read it, so the read stops there: it does not
try an ancestor or the shared slot, because running on a different credential
than the one you stored would look like success.
Unlike a config field, read never falls back to an environment variable, a
config file or a default. A config field whose vault entry is absent still
resolves from the next source exactly as before; only this explicit read reports
the absence.
Local only, and masked. read opens the local vault and never contacts a
provider — refresh it with func builtin vault sync. The value arrives as
Secret[str], which renders as ••• in an f-string, a log line, a repr or a
traceback; get_secret_value() is for the call that actually needs it. Neither
the call nor its errors print the value, and vault list / vault inspect
remain metadata-only.
The key¶
The vault key is resolved by a VaultKeyProvider:
| Provider | Source | Needs a terminal | Installed by default |
|---|---|---|---|
env |
$FUNCTUALIZE_VAULT_KEY (64 hex characters) |
no | yes |
keychain |
the OS keyring | no | no — functualize[keychain] |
The environment wins when set: nothing else is touched, so an automated run is deterministic and never waits on anything. In CI, Lambda or a container, export it.
Otherwise the OS keyring is read whether or not stdout is a terminal — a pipe, an agent's shell tool and a stdio MCP job read it exactly as a terminal does — and it is read silently. Unlock your keyring once (your desktop session usually does it at login) and every run reads the key for as long as the keyring stays unlocked; the keyring's own policy decides how long that is. functualize keeps no copy of the key and runs no timer of its own.
The key is read only when it is needed. A run asks for it the first time it
opens a stored vault entry. A job whose config never reads a stored secret —
and func --help, completions and builtin info — never touches the keyring
at all, even in a project that has a vault.
A run never asks the keyring to unlock. If the keyring is locked, a run that needs a stored secret is refused at once — no dialog, no wait. This is deliberate: a run that raised an unlock prompt and then went away (a timeout, Ctrl-C, an agent stopping its child process) can crash the keyring service on some desktops and lock every keyring you have. So unlock first, then run:
in a terminal. It is the only command that asks the keyring to unlock — even
vault init refuses a locked keyring and sends you here. It waits
— with no deadline — for you to answer or cancel the keyring's own dialog, says
whether the keyring was already unlocked or has just been unlocked, and never
prints the key. Interrupt it once and it keeps waiting (answer or cancel the
dialog instead); interrupt it twice to stop. Then rerun the job; nothing needs
reconfiguring. Before you start agents or scheduled jobs that need stored
secrets, unlock the keyring — they cannot answer a dialog, so they are
refused while it is locked.
func builtin vault status and the inline TUI's status bar show whether a run
would get the key right now — unlocked, locked, unknown or no keyring
— without ever opening the keyring. Python code asks the same question with
functualize.app.vault.vault_key_state().
A keyring backend that does not answer at all is bounded by a func setting, so a dead service costs a known wait rather than a hang:
# .functualize.toml (this project) or ~/.config/functualize/config.toml (you)
[vault]
keyring_timeout = "30s"
$FUNCTUALIZE_VAULT_KEYRING_TIMEOUT overrides both, with the usual precedence
(default < global < nearest project < env). Durations are spelled as for
max_age below; a bare number or 0s is refused with a warning and the
default is used. It never applies to a locked keyring — that is refused at
once — only to one that does not answer. The setting reaches every app func
builds; a FunctualizeApp you construct yourself gets the env var and the
default, or the value you pass as ConfigSources(vault_keyring_timeout="10s").
Platforms. The keyring is read through a small adapter per platform:
| Platform | Keyring | Status |
|---|---|---|
| Linux (and other desktops speaking the freedesktop Secret Service API) | the session keyring | verified on a real desktop, and checked in CI against a private gnome-keyring |
| macOS | the login keychain, read with user interaction disabled | checked in CI on a real macOS runner (a locked keychain answers without a dialog); not yet confirmed on a user's Mac |
| Windows | Credential Manager, which has no locked state | checked in CI on a real Windows runner; not yet confirmed on a user's machine |
any other keyring backend |
— | not read by a run, because it cannot be proven silent; set $FUNCTUALIZE_VAULT_KEY |
A provider that needs a person at this terminal — none ships — is still skipped unless stdin and stdout are both terminals, and is asked only after every provider that cannot prompt.
One key, every project. Both shipped providers are user-scoped: the same key opens every project's vault on this machine. The vaults stay separate — one encrypted file each — so isolation comes from the files, not from the keys. A third-party provider may still hold one key per project; scope is the provider's choice.
With no key the vault does not open, and there is no plaintext fallback. What happens next depends on whether anything is actually stored for the key being resolved:
the vault holds nothing for this key -> resolution continues to the next
source, and says so
the vault HOLDS a value for this key -> the run refuses
The second case is the one worth understanding. A stored value is the one you
provisioned; continuing past it to an environment variable would hand the job a
different secret while the run reported success. The refusal (exit code 3)
says what happened, and the next step:
| Outcome | What the refusal tells you to do |
|---|---|
| the keyring is locked | unlock it with your system's keyring manager, or run func builtin vault unlock, or set $FUNCTUALIZE_VAULT_KEY; then retry |
the keyring did not answer within the keyring_timeout |
check that it is running, or set $FUNCTUALIZE_VAULT_KEY; then retry |
| no keyring is reachable here | export $FUNCTUALIZE_VAULT_KEY, or install functualize[keychain] |
| this keyring backend cannot be read without a possible prompt | set $FUNCTUALIZE_VAULT_KEY for runs without a terminal |
| a keyring answered and holds no vault key | func builtin vault init, or export $FUNCTUALIZE_VAULT_KEY |
| a key was found and does not open this vault | supply the key it was written with |
In the first four the key may well still exist, so the message never suggests
deleting anything. Where the key really is gone the last resort is
func builtin vault sync for a provider entry, and — saying that they destroy
the stored value, which for an entry typed in with vault put is the only
copy — func builtin vault remove --group <address> --job <leaf> --field <name>
(or either target flag alone) and
func builtin vault clear, which need no key.
Three things that warn rather than fail¶
Offline work has to keep working, so none of these stops a run.
A key declared remotely with nothing synced for it. Resolution continues to the next source, and the warning names the scoped identity, which source answered instead, and the fix:
Config key 'data-sync.password' has a [[vault_secret]] declaration, but the vault
holds no synced value for it. It resolved from file
(/srv/my-platform/config.base.toml) instead. Run `func builtin vault sync` to
fill the vault.
That is also what a first run looks like — a key exported and vault sync
not yet run. It warns per declared key rather than once, because unlike a
missing key it has a one-command fix the message can name. With no key,
declared values fall back to local sources and that is said once per run, at
the first declared value that needed the key — not at start-up, because a run
that never needs the key never asks for it.
Once per key per run, not once per access.
A stale vault. Past max_age (default 24h, judged on the oldest entry)
the first vault read of a run warns once and the run continues:
$FUNCTUALIZE_VAULT_MAX_AGE overrides that. Durations are
<number><unit> terms — 30s, 45m, 24h, 7d, 2w, or 1d12h. A bare
number is refused rather than guessed, and so is 1M: a month has no fixed
length, and reading it as minutes would be wrong by a factor of 43,200.
A declaration whose plugin is not installed. aws-sm://prod/db with
functualize-secrets-aws absent is reported by vault sync rather than passed over,
because the declared secret would otherwise remain unsynced.
The builtin vault commands¶
func builtin vault init # ensure this machine has a key -- never prints it
func builtin vault put --job deploy --field api_token # masked prompt
func builtin vault put --group deploy --job web --field token # grouped job
func builtin vault inspect --group deploy --field token # metadata only
func builtin vault remove --group deploy --job web --field token # exact active key; no vault key
func builtin vault sync # fetch explicit declarations, write the vault
func builtin vault list # names, origins, timestamps -- never values
func builtin vault status # key provider and key state, age, entry counts
func builtin vault unlock # the one command that asks the keyring to unlock
func builtin vault clear # delete this project's vault, needs no key
func builtin vault keygen # print a fresh 32-byte key, hex-encoded
func builtin vault share --entry group=deploy # one-time link for a teammate
func builtin vault redeem <link> # store a shared link's entries
func builtin vault show <link> # preview a link; never uses it
All of them take --json. share, redeem and show are described in
Vault Sharing.
The JSON refusal envelope includes a stable reason. In particular,
scope_required means the command needs --group, --job, or both;
dotted_job means to split a dotted job path between the two flags;
unknown_group means the named group has no declared options; and
vault_format_unsupported means an old-format vault must be cleared before
scoped secrets can be used.
This is a breaking change for existing local stores: no identity migration is
performed. Run func builtin vault clear --yes in that project, then provision
direct entries again and run func builtin vault sync for provider entries.
clear needs no vault key. The old positional put / inspect / remove
form and inline provider references in secret config fields are no longer
accepted.
The first four are the local lifecycle: they need no remote provider and no
cloud account. See A secret of your own above. sync is the remote one, and
the only thing here that touches the network.
put stores what you type; sync stores what a provider answered. Entries
remember which, because they recover differently — a synced value comes back on
the next sync, a typed-in one has no upstream copy at all. Neither silently
replaces the other: a sync that finds a typed-in value at its key reports the
conflict rather than overwriting it, and put refuses a path a provider owns.
list and status need no key — they read the cleartext metadata columns,
which is what makes them useful on the machine where something is wrong.
status also never prompts and never waits on a keyring: it asks the keyring
whether it is locked and reports Key state: available, locked or unknown
(the last where the backend cannot say without risking a prompt — macOS and
Windows today), so it is safe in a script.
$ func builtin vault status
Path: ~/.local/share/functualize/vaults/0f8c5900f3b1/vault.db
Exists: yes
Entries: 3 (1 direct, 2 synced)
Key provider: env
Key state: available
Last synced: 4d 2h ago ← stale
Max age: 1d
Providers: aws-sm, aws-ssm, bws
Run `func builtin vault sync` to refresh it.
sync collects failures rather than stopping at the first: one unreachable
provider must not abandon the other twelve secrets. It exits non-zero when
anything declared did not land, so a pipeline still notices.
Only config files provide [[vault_secret]] declarations. Environment
variables remain ordinary runtime sources below the vault.
Fallback chains¶
A declaration's source may name more than one provider, tried in order:
[[vault_secret]]
job = "data-sync"
field = "password"
source = "aws-sm://prod/db-password | bws://DB_PASSWORD"
Up to five entries. Each keeps its own provider-specific options, and sync
reports every entry's reason when the whole chain is exhausted.
Provider-specific references¶
Everything after :// is opaque to functualize and is handed to the provider
whole, which is what lets a provider define its own options:
[[vault_secret]]
job = "data-sync"
field = "password"
source = "aws-sm://prod/db-password?profile=prod-admin"
See each plugin's README for the options it honours. Both shipped plugins refuse an unknown option rather than ignoring it.
Complete Example¶
Here's a full example showing a base config, environment overlay, and a JobConfig model that reads from the config system.
Base Config¶
[general]
debug = false
environment = "development"
[data_sync]
api_url = "https://api.example.com"
batch_size = 50
timeout = 30
retry_enabled = true
Environment Overlay¶
[general]
debug = false
environment = "production"
[data_sync]
api_url = "https://api.prod.example.com"
batch_size = 500
timeout = 60
JobConfig Model and Job Function¶
from pydantic import BaseModel, Field
from functualize.job import RunContext
JOB_GROUP = "data_sync"
class SyncConfig(BaseModel):
"""Configuration for the data sync job."""
api_url: str = Field(description="Target API endpoint URL")
batch_size: int = Field(default=100, description="Number of records per batch")
timeout: int = Field(default=30, description="Request timeout in seconds")
retry_enabled: bool = Field(default=True, description="Enable automatic retries")
def sync(rc: RunContext, config: SyncConfig) -> None:
"""Synchronize data from the configured API endpoint."""
rc.log(f"Connecting to {config.api_url}", level="info")
rc.log(f"Batch size: {config.batch_size}, timeout: {config.timeout}s", level="info")
if config.retry_enabled:
rc.log("Retries enabled", level="debug")
# ... sync logic here
Runtime Resolution¶
With ENVIRONMENT=PROD, running the job resolves values as:
| Field | Resolved Value | Source |
|---|---|---|
api_url |
https://api.prod.example.com |
config.prod.toml (overrides base) |
batch_size |
500 |
config.prod.toml (overrides base) |
timeout |
60 |
config.prod.toml (overrides base) |
retry_enabled |
true |
config.base.toml (not overridden in prod) |
Override any value with an environment variable:
Or via CLI:
Application Setup¶
from functualize.app import FunctualizeApp, JobSources
app = FunctualizeApp(
name="myapp",
job_sources=JobSources(directories=["jobs"]),
)
if __name__ == "__main__":
app.run()
Using the JobConfigView Class Directly¶
For advanced use cases, you can use the JobConfigView class directly (requires a ResolutionChain instance):
from functualize.job import JobConfigView
# JobConfigView is available as rc.config inside job functions
# For advanced use, you can access it directly:
config_view = rc.config
# Get a value with fallback
debug = config_view.get("debug", default="false", section="general")
Introspection with builtin info¶
Use the built-in builtin info command to inspect resolved configuration at runtime:
# Show general config info and loaded files
myapp builtin info all
# Show resolved JobConfig for a specific job
myapp builtin info --job data_sync
# Show all environment variables
myapp builtin info --show-env-vars
This displays which config files were loaded, their interpolated values, and the source of each resolved field (env var, config file, or model default).