# Manage Ledger Configuration as Code

Source: https://docs.formance.com/v4.0/modules/ledger/operations/configuration-as-code

Stack: v4.0

Use `ledgerctl ledgers configuration` to keep the editable business configuration of a ledger in version control. The workflow reads the live state, exports an apply-compatible JSON or YAML document, computes a diff, and submits the required Ledger mutations after review.

This is a ledger-level workflow. It does not configure Kubernetes resources, voter topology, storage, server flags, authentication, TLS, event sinks, or backup infrastructure.

## Know what the file owns

The exported document includes:

| Section                  | Managed state                                                                                                                                                                       |
| ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `defaultEnforcementMode` | Default account-type enforcement mode.                                                                                                                                              |
| `accountTypes`           | Account patterns and persistence modes.                                                                                                                                             |
| `metadataSchema`         | Ledger, account, and transaction field declarations and their index intent.                                                                                                         |
| `indexes`                | Editable built-in transaction indexes.                                                                                                                                              |
| `preparedQueries`        | Query name, target, and filter.                                                                                                                                                     |
| `numscripts`             | Program name, content, and version. A content change requires a new, strictly greater canonical semver (`1.2.0`, not `1.2`); editing content under an existing version is rejected. |

Read-only state such as creation time and index build status is not exported. Inspect it separately with `ledgerctl ledgers get`, index commands, and the owning workflow.

Treat the exported file as complete desired state, not as a partial patch. Removing an account type, index, or prepared query from the file can plan its removal from Ledger. Always start from a fresh export and review every delete in the dry-run output.

An omitted section is read as empty, not as unmanaged. A file with no `indexes:` key plans a drop of every built-in transaction index.

The Numscript library is the exception, because it is append-only. Dropping a program from the file does not plan its removal: the diff fails with `the append-only library does not support removal`, and because one failing section aborts the whole diff, no plan is produced for any section.

The file contains program and query definitions but no credentials. Do not add tokens, signing seeds, TLS private keys, database DSNs, or other secrets to it.

## Export the current state

The examples use a ledger named `payments`. Replace that name with the ledger you intend to manage.

### Precheck

1. Confirm that your `ledgerctl` profile targets the intended environment.
2. Confirm that the caller can read every managed section and is allowed to apply the intended mutations.
3. Check for active maintenance or another configuration deployment.
4. Choose one owner for this state. Do not run a CLI reconciler and an Operator reconciler against the same objects.
5. Create or select a reviewed repository path that contains no secrets.

Inspect the human-readable summary first:

```bash
ledgerctl ledgers configuration payments --expand
```

Export YAML for review:

```bash
test ! -e payments.before.yaml || {
  printf 'refusing to overwrite rollback candidate: payments.before.yaml\n' >&2
  exit 1
}
ledgerctl ledgers configuration export payments --yaml > payments.before.yaml
cp payments.before.yaml payments.ledger.yaml
```

Keep `payments.before.yaml` unchanged as the rollback candidate, and edit only `payments.ledger.yaml`. A Numscript change is the exception to that rollback plan: it cannot be reversed by re-applying the previous file. The export command defaults to JSON when neither `--yaml` nor `--json` is provided. Commit the generated document with the Stack and Ledger versions against which it was exported.

## Edit and review

Make one business change per review when possible. The reviewer should answer:

- Does a new or changed account type still accept existing valid addresses?
- Does an `AUDIT` to `STRICT` change have evidence that unmatched traffic is zero?
- Does each declared metadata type match existing values and application expectations?
- Does a new query have every required index?
- Will dropping an index break a deployed filter or prepared query?
- Does the required Numscript version bump preserve callers that pin an older version?
- Is any delete intentional, owned, and recoverable?

Index builds can continue after the configuration mutation commits. Metadata schema changes declare how Ledger interprets and validates fields; they do not convert or rewrite historical values. The apply command confirms that Ledger accepted the declarations and other changes, not that every asynchronous index result is ready.

## Preview the live diff

Run the dry-run against the target environment immediately before approval:

```bash
ledgerctl ledgers configuration apply payments \
  --file payments.ledger.yaml \
  --dry-run
```

The command fetches the current live configuration and prints the planned add, update, and remove actions without applying them.

Review the plan for:

- unexpected deletes;
- a default enforcement change;
- metadata type changes;
- index removal or creation;
- prepared-query replacement;
- a Numscript version change.

The dry-run does not reserve the state. Another writer can change the ledger before the real apply, so run it again when the approval or deployment queue introduces a delay.

## Apply the configuration

Apply interactively after reviewing the current diff:

```bash
ledgerctl ledgers configuration apply payments \
  --file payments.ledger.yaml
```

The prompt defaults to no. For an approved non-interactive deployment, use `--yes` and preserve the dry-run and approval as CI artifacts:

```bash
ledgerctl ledgers configuration apply payments \
  --file payments.ledger.yaml \
  --yes
```

If Ledger requires request signing, provide both the approved signing key and its registered key ID through the secure CLI profile or the global `--signing-key` and `--signing-key-id` options. This configuration apply command submits its complete change set through the signed `Apply` path, including prepared-query changes that the direct `ledgerctl queries` commands cannot sign in the current preview. Never place the seed in the desired-state file or CI log.

## Verify independently

Export the result again:

```bash
ledgerctl ledgers configuration export payments --yaml > payments.actual.yaml
diff -u payments.ledger.yaml payments.actual.yaml
```

Then verify each affected behavior:

1. List account types and confirm the expected default enforcement mode.
2. Confirm the metadata schema declaration and test representative current and historical values against the intended type.
3. Wait for each required index to become ready on every serving replica.
4. Execute each changed prepared query with representative parameters.
5. Execute each changed Numscript program with test variables and verify the resulting postings.
6. Test one expected rejection as well as one accepted request when enforcement changed.
7. Confirm that request errors, index lag, and latency remain within the deployment thresholds.

The change succeeds when the exported live desired state matches the reviewed file and every asynchronous or business check has reached its expected result.

## Roll back

Before applying a change, preserve the previous export as the rollback candidate. Preview it against the current ledger before applying it:

If the change published a new Numscript version, the previous export can no longer be applied at all. The diff requires a version strictly greater than the greatest one stored, so a file naming the older version fails before any request is built, and that one failure aborts the diff for every other section too. Rolling a program back means publishing a higher version whose content matches the old one. Plan that forward correction before you apply a Numscript change, not after.

```bash
ledgerctl ledgers configuration apply payments \
  --file payments.before.yaml \
  --dry-run
```

Apply it only after reviewing the new rollback plan. Reapplying the previous file can restore declarations, but it does not automatically reverse all consequences:

- an index may need to rebuild;
- restoring a previous metadata type declaration does not rewrite values accepted under the newer declaration, so validate their compatibility first;
- a removed prepared query or program may have interrupted callers;
- switching to `STRICT` may already have rejected requests;
- removing configuration does not delete or rewrite historical transactions.

When rollback would remove newly accepted business state or when the previous declaration no longer validates, stop automated reconciliation and use a forward correction. Keep the pre-change export, dry-run, apply result, post-change export, and verification evidence with the deployment record.
