# Native IaC (Preview)

> Converge, preview, apply, destroy and recover cloud deployments from a desired-state resource specification with SQL statements on the stackql_preview.iac relations, a preview feature of StackQL.

Source: https://stackql.io/getting-started/native-iac

See also:  
[[ Transactions ]](/language-spec/transactions) [[ Provider Sessions and Secrets ]](/getting-started/provider-sessions) [[` mcp `]](/command-line-usage/mcp) [[ Global Flags ]](/command-line-usage/global-flags)

StackQL exposes a desired-state engine as SQL relations under `stackql_preview.iac`.  A named collection of resources, declared in a JSON resource specification or rendered from a built-in blueprint, is converged with `INSERT`, previewed with `SELECT`, destroyed with `DELETE` and recovered with `UPDATE`.  StackQL records which resources it manages, with their identities and dependencies, in a local ledger, and later runs against the same collection use that ledger to update or remove the same resources.  The ledger holds ownership and progress, not a copy of resource attributes: desired state is compared with the live provider state on every run.

:::caution[Preview]

Native IaC is a preview feature: behaviour, syntax and output may change between releases without notice, so do not rely on it in production.  The SQL verbs described here are available in StackQL releases from `v1.1.975`.  Releases from `v1.0` to `v1.1.959` used `SELECT` on `stackql_preview.iac.run` and `stackql_preview.iac.destroy` instead; neither form is accepted any more.

:::

Native IaC is separate from [stackql-deploy](https://stackql-deploy.io/), the StackQL deployment framework, which runs ordinary StackQL queries from a manifest and keeps no state of its own.

## Enabling native IaC

The relations exist only when StackQL is started with the preview opt-in.  Without it, a statement fails with `could not locate table`:

```bash
stackql shell --preview '{"unstable":true}'
```

The same flag works with `exec`, `srv` and `mcp`.  The `iacStateRoot` key of `--preview` moves the ledger from its default location under the application root (see [Ledger and state location](#ledger-and-state-location)):

```bash
stackql shell --preview '{"unstable":true,"iacStateRoot":"/srv/stackql/iac"}'
```

Converge, preview and destroy also need credentials for the providers in the specification, resolved as for any other query.

## Relations and verbs

| Statement | Effect |
|--|--|
| `INSERT INTO stackql_preview.iac.run` | Converges a collection to the desired state: creates, updates or leaves each resource unchanged. |
| `DELETE FROM stackql_preview.iac.run` | Destroys the collection's resources, using the identities and dependencies in the ledger.  Dependents are deleted first. |
| `SELECT ... FROM stackql_preview.iac.plan` | Previews a converge: one row per resource with its planned action and a change set.  Reads the ledger and provider state; sends no mutations and writes nothing. |
| `INSERT INTO stackql_preview.iac.plan` | Applies a change set returned by a preview. |
| `UPDATE stackql_preview.iac.recover` | Records an operator-verified outcome for a pending ledger entry.  Local ledger only; no provider calls. |
| `SELECT ... FROM stackql_preview.iac.ledger` | Reads resource identities and phases.  No locks, journals or provider calls. |
| `INSERT INTO stackql_preview.iac.run (blueprint, ...)` | Converges a built-in blueprint such as `aws_vpc_subnet`. |

Any other verb is refused with a message naming the statement to use, for example `SELECT` from `run`:

```sql
/*
SELECT * FROM stackql_preview.iac.run WHERE collection = 'demo';
-- FAILS with use INSERT INTO stackql_preview.iac.run to converge or DELETE FROM stackql_preview.iac.run to destroy
*/
```

### Discovery

`SHOW` and `DESCRIBE` list the relations and what they accept, need no collection and make no provider calls:

```sql
SHOW RESOURCES IN stackql_preview.iac;
```

```
|----------------|------------------------------------|
|      name      |                 id                 |
|----------------|------------------------------------|
| run            | stackql_preview.iac.run            |
|----------------|------------------------------------|
| recover        | stackql_preview.iac.recover        |
|----------------|------------------------------------|
| ledger         | stackql_preview.iac.ledger         |
|----------------|------------------------------------|
| plan           | stackql_preview.iac.plan           |
|----------------|------------------------------------|
| aws_vpc_subnet | stackql_preview.iac.aws_vpc_subnet |
|----------------|------------------------------------|
```

`SHOW METHODS` gives the verbs and required inputs of a relation:

```sql
SHOW METHODS IN stackql_preview.iac.run;
```

```
|------------|------------------------------------|---------|
| MethodName |           RequiredParams           | SQLVerb |
|------------|------------------------------------|---------|
| run        | collection, one of                 | INSERT  |
|            | blueprint/resources/resources_file |         |
|------------|------------------------------------|---------|
| destroy    | collection                         | DELETE  |
|------------|------------------------------------|---------|
```

`SHOW METHODS IN stackql_preview.iac.plan` lists `preview` (`SELECT`, requiring `collection` and `resources`) and `apply` (`INSERT`, requiring `collection` and `change_set`).  `DESCRIBE stackql_preview.iac.plan` lists the five preview columns, and `DESCRIBE EXTENDED stackql_preview.iac.aws_vpc_subnet` lists a blueprint's inputs.  `DESCRIBE` on `run`, `ledger` or `recover` answers that the relation takes a specification rather than columns.

## Statement rules

- Always use the fully qualified name `stackql_preview.iac.<relation>`.
- An `INSERT` needs a column list and exactly one `VALUES` row.
- Every value is a string or numeric literal; expressions such as `concat(...)` are refused.  JSON goes in a SQL string literal.  [Session variables](/getting-started/session-variables) (`$name`) are resolved to literals first and are accepted.
- `WHERE` accepts only `column = literal` predicates joined by `AND`; `LIKE`, `>`, `OR` and `ORDER BY` are refused.
- With `RETURNING *` a statement returns its result rows.  Without it, a converge or destroy still runs to completion, returns no rows, and fails if any resource failed or is outstanding.
- A failed, errored or outstanding resource makes the statement fail, and `stackql exec` exits with status `1`; the diagnostic rows are still returned with `RETURNING *`.

## Parameters

| Parameter | Used by | Rule |
|--|--|--|
| `collection` | every statement | Required.  The ledger key prefix, the lease scope and how later runs address the same resources. |
| `resources` | `run` `INSERT`, `plan` `SELECT` | An inline JSON [resource specification](#resource-specification).  The only source a preview accepts. |
| `resources_file` | `run` `INSERT` | Path to a JSON specification file, read by the StackQL process. |
| `blueprint` | `run` `INSERT` | A [blueprint](#blueprints) handle, for example `aws_vpc_subnet`; its inputs are further columns. |
| `inputs` | `run` `INSERT`, `plan` | One JSON object of binding inputs.  JSON numbers keep their precision; strings are literal values, not SQL or templates. |
| `inputs_file` | `run` `INSERT`, `plan` | Path to a file holding the same object.  Supply `inputs` or `inputs_file`, not both. |
| `state` | every statement | Optional directory name, relative to and inside the IaC state root.  Default: the root itself. |
| `region` and any other column | `run`, `plan` | Not consumed by StackQL: passed through as the run's execution scope (provider parameters).  Rejected by `ledger` and `recover`. |
| `run_id` | `run` | Optional.  StackQL stamps each execution with a unique `<UTC timestamp>-<random>` ID when omitted; an explicit ID must be unique within the state directory. |
| `change_set` | `plan` `INSERT` | Required.  The `change_set` string from a preview row. |
| `keys` | `run` `DELETE` | Optional.  A non-empty JSON array of resource keys for a partial destroy, for example `'["aws/ec2/subnet"]'`. |
| `resource_key` | `ledger`, `recover` | Optional filter on `ledger`; required on `recover`. |
| `version`, `outcome`, `identity` | `recover` | See [Recovery](#recovery). |

`INSERT INTO stackql_preview.iac.run` needs exactly one of `blueprint`, `resources` or `resources_file`.  `SELECT FROM stackql_preview.iac.plan` requires `collection` and `resources`.  `ledger` accepts only `collection`, `state` and `resource_key`.  `recover` accepts `collection`, `state`, `resource_key` and `version` in `WHERE`, and only `outcome` and `identity` in `SET`.

## Resource specification

A specification is a JSON list of resources, or an object whose `resources` member is that list.  Resource keys must be unique.  Each resource names its provider, the `service.resource` address it is created through, the response field holding its identity and the request parameter that addresses it by that identity, together with its desired properties and its dependencies on other resources.  The following specification, from the [omnisdk examples](https://github.com/stackql-labs/omnisdk/tree/main/cicd/examples/aws-vpc-subnet), declares an AWS VPC and a subnet that depends on it:

```json
{
  "resources": [
    {
      "key": "aws/ec2/vpc",
      "provider": "aws",
      "address": "ec2.vpcs",
      "identity": "line_items.VpcId",
      "addressed_by": "VpcId",
      "write_once": {
        "TagSpecification.1.ResourceType": "vpc",
        "TagSpecification.1.Tag.1.Key": "resource-key"
      },
      "desired": {
        "CidrBlock": "10.42.0.0/16",
        "TagSpecification.1.Tag.1.Value": {"from": "self", "attribute": "key"}
      }
    },
    {
      "key": "aws/ec2/subnet",
      "provider": "aws",
      "address": "ec2.subnets",
      "identity": "line_items.SubnetId",
      "addressed_by": "SubnetId",
      "write_once": {
        "TagSpecification.1.ResourceType": "subnet",
        "TagSpecification.1.Tag.1.Key": "resource-key",
        "TagSpecification.1.Tag.1.Value": {"from": "self", "attribute": "key"}
      },
      "desired": {"CidrBlock": "10.42.1.0/24"},
      "inbound": [{"from": "aws/ec2/vpc", "as": "VpcId"}]
    }
  ]
}
```

| Field | Meaning |
|--|--|
| `key` | Unique resource key within the collection. |
| `provider`, `address` | The provider and the `service.resource` the resource is created through. |
| `identity` | The response field holding the resource's ID. |
| `addressed_by` | The request parameter that takes that ID for reads, updates and deletes. |
| `write_once` | Request inputs sent only when the resource is created. |
| `desired` | Properties maintained on every converge.  A value can be a typed binding such as `{"from": "self", "attribute": "key"}`, an input, an environment value or another resource's attribute. |
| `inbound` | Dependencies: `[{"from": "<key>", "as": "<parameter>"}]` passes the identity of resource `<key>` as `<parameter>`, and orders the resources for create and destroy. |

The retired `params` and `correlationParam` fields are rejected.  The full format is defined by [omnisdk](https://github.com/stackql-labs/omnisdk).

## Converge

An `INSERT` into `stackql_preview.iac.run` with a specification file, the collection name and the execution scope converges the collection:

```sql
INSERT INTO stackql_preview.iac.run (resources_file, collection, state, region)
VALUES ('/path/to/resources.json', 'my-collection', 'demo', 'ap-southeast-2')
RETURNING *;
```

Result rows have `key` (`<collection>/<resource_key>`), `status` and `identity`.  Running the same statement again checks idempotence: the identities must not change and nothing is duplicated.  `status = 'applied'` is also reported for a resource that needed no change.  Keep converging with the latest desired-state document: reapplying an older document is a change, and can request removal of fields the older document does not declare.

### Blueprints

A blueprint renders a specification from a few inputs.  `aws_vpc_subnet` is a VPC and a subnet in it; `region`, `vpc_cidr` and `subnet_cidr` are required, and `vpc_tags` and `subnet_tags` are JSON objects.  Its CIDR blocks are immutable, so a change to them is refused rather than replacing the resources, and tags are applied at create and not converged:

```sql
INSERT INTO stackql_preview.iac.run (blueprint, collection, region, vpc_cidr, subnet_cidr)
VALUES ('aws_vpc_subnet', 'my-vpc', 'ap-southeast-2', '10.42.0.0/16', '10.42.1.0/24')
RETURNING *;
```

A missing input fails before anything is sent, for example `omnisdk: vpc_cidr is required`.

## Preview and apply

A `SELECT` on `stackql_preview.iac.plan` with an inline specification previews the converge without changing anything:

```sql
SELECT resource_key, action, reason, depends_on, change_set
FROM stackql_preview.iac.plan
WHERE collection = 'my-collection' AND resources = '<inline JSON specification>';
```

`action` is `create`, `update`, `replace`, `no-op` or `unknown` (reported, for example, for a resource that depends on one not yet created).  `depends_on` is a JSON array.  Every row carries the same `change_set`, which an `INSERT` into the same relation applies:

```sql
INSERT INTO stackql_preview.iac.plan (collection, change_set)
VALUES ('my-collection', '<change_set>')
RETURNING status;
```

- Use the same `collection`, `state`, scope columns and inputs as the preview.
- The apply rechecks the plan under the collection's lease and is refused as stale if the state changed since the preview; preview again.
- The change set is JSON inside a SQL string literal, so every `'` and every `\` in it must be doubled.

## Destroy

A `DELETE` from `stackql_preview.iac.run` with the same collection, state and scope as the converge destroys the collection, dependents first:

```sql
DELETE FROM stackql_preview.iac.run
WHERE collection = 'my-collection' AND state = 'demo' AND region = 'ap-southeast-2'
RETURNING *;
```

Result rows have `key`, `status` and, when a resource was not destroyed, `reason`.  A row with `status = 'outstanding'` means the resource remains, and the statement fails with `IaC operation did not complete successfully for key <key> (status outstanding); inspect the journal`.

Adding `keys` destroys only the named resources.  An empty selection is an error, and a resource that retained resources depend on is not deleted:

```sql
DELETE FROM stackql_preview.iac.run
WHERE collection = 'my-collection' AND state = 'demo' AND region = 'ap-southeast-2'
  AND keys = '["aws/ec2/subnet"]'
RETURNING *;
```

After a partial destroy, remove the deleted declarations from the specification before converging again: omitting a resource does not delete it, and reapplying its declaration recreates it.

## Ledger and state location

The state root is `<approot>/iac`, where the application root defaults to `.stackql` under the StackQL process's working directory (or the [`--approot`](/command-line-usage/global-flags) value); `iacStateRoot` in `--preview` overrides it.  The ledger is kept in `<root>/ledger/<collection>/` and run journals in `<root>/journal/`; with `state = 'demo'` they move to `<root>/demo/ledger/<collection>/` and `<root>/demo/journal/`.  A `state` value must be a relative name inside the root.  With [access management](/command-line-usage/access-management) enabled, the root is further partitioned by the caller's `tenant` attribute or principal ID.  File paths (`resources_file`, `inputs_file`, `@file` overlays) refer to the StackQL process's file system, which for an MCP or PostgreSQL wire server is the server host.

The following query reads the identity and phase of every resource in a collection:

```sql
SELECT resource_key, identity, phase, version
FROM stackql_preview.iac.ledger
WHERE collection = 'my-collection' AND state = 'demo';
```

Ledger columns are `address`, `addressed_by`, `collection`, `depends_on`, `identity`, `key`, `phase` (`live` or `pending`), `provider`, `resource_key` and `version`.  A `pending` row's `identity` is the previous committed identity, not proof that the pending operation happened.

Keep `collection`, `state`, the scope columns, the state root and any [document overlay](#provider-overlays) the same for every run of a deployment: a different ledger location can create duplicate resources.  Never delete, move or edit the ledger or journals to get past an error, and never switch to a new collection name to bypass one; inspect the returned rows and the journal first.

## Recovery

An interrupted or failed operation can leave a ledger entry `pending`, for example a create whose outcome is unknown or a delete the provider did not complete.  While an entry is pending, a destroy fails with `<key> has unresolved intent; recover its outcome before destroying this collection`, and a preview that includes the key fails with `<key> has unresolved intent; recover it before planning`.  Nothing is replayed automatically.

1. Read the entry and note its `version`:

   ```sql
   SELECT resource_key, identity, phase, version
   FROM stackql_preview.iac.ledger
   WHERE collection = 'my-collection' AND resource_key = 'aws/ec2/subnet';
   ```

2. Establish the real outcome at the provider and confirm the operation is no longer in flight.  Verify completion and readiness, not only existence; tags are not evidence.

3. Record the outcome with the version from step 1 (and `state` if the deployment uses one).  `absent` clears an unresolved first create:

   ```sql
   UPDATE stackql_preview.iac.recover SET outcome = 'absent'
   WHERE collection = 'my-collection' AND resource_key = 'aws/ec2/subnet' AND version = '1'
   RETURNING *;
   ```

   `applied` records a completed operation with its verified identity:

   ```sql
   UPDATE stackql_preview.iac.recover SET outcome = 'applied', identity = 'subnet-0123456789abcdef0'
   WHERE collection = 'my-collection' AND resource_key = 'aws/ec2/subnet' AND version = '3'
   RETURNING *;
   ```

4. Run the original converge again with the same collection, state, inputs and specification.

`absent` is refused unless the entry is a first create with no prior identity and no dependents.  `applied` needs `identity` and cannot replace a prior identity.  Result rows have `key`, `identity` and `status` (`recovered_absent` or `recovered_applied`).  A stale version is refused (`ledger: version conflict: recovery observed 2, current 1`), as is an entry that is not pending (`<collection>/<key> is not pending`).  Each recovery writes a durable assertion to the journal.

## Provider overlays

A deployment that needs provider document changes, such as an update route the published provider lacks, can apply an overlay to the session's view of the provider documents with [`SET "$.document_merge"`](/getting-started/provider-sessions#document-merge) before converging:

```sql
SET "$.document_merge" = '@/absolute/path/merge.json';

INSERT INTO stackql_preview.iac.run (collection, region, resources_file, inputs_file)
VALUES ('my-collection', 'ap-southeast-2', '/path/to/resources.json', '/path/to/inputs.json')
RETURNING *;

UNSET "$.document_merge";
```

The overlay is session scoped, so a reopened shell needs the `SET` again before continuing the deployment.

## Through the MCP server

Start the [MCP server](/command-line-usage/mcp) with the preview opt-in, for example `stackql mcp --mcp.server.type=stdio --preview '{"unstable":true}'`.  [`run_select_query`](/mcp/run_select_query) runs `SELECT` on `plan` and `ledger`, `SHOW` and `DESCRIBE`; [`run_mutation_query`](/mcp/run_mutation_query) runs the `INSERT`, `DELETE` and `UPDATE` statements.  Each tool call is a fresh session, so put a `SET "$.document_merge" = ...;` and the statement that needs it in the same `sql` batch.  The server mode decides each call:

| Statement | Class | `read_only` | `safe` (default) | `delete_safe` | `full_access` |
|--|--|--|--|--|--|
| `SELECT` on `plan` or `ledger`, `SHOW`, `DESCRIBE` | `select` | allow | allow | allow | allow |
| `INSERT INTO` `run` or `plan`, `UPDATE` `recover` | `mutation_create` | refuse | approval | allow | allow |
| `DELETE FROM` `run` | `mutation_delete` | refuse | approval | approval | allow |
| A batch containing `SET` or `UNSET` | `unknown` | refuse | approval | approval | allow |

Converge and destroy can take longer than the server's `request_timeout`.  With the [tasks extension](/command-line-usage/mcp#tasks) enabled on the server and declared by the client, a single `INSERT` or `DELETE` on `stackql_preview.iac.run` or `INSERT` on `stackql_preview.iac.plan` runs as a task with its own timeout (default 30 minutes); a batch that also carries `SET` runs synchronously.  A converge or destroy that timed out may already have changed resources, so read the ledger before retrying.  With the [skills extension](/command-line-usage/mcp#skills) enabled, the server also serves a `stackql-iac` skill describing these statements to the agent.

## Permissions

With [access management](/command-line-usage/access-management) enabled, a converge requires `execute` on `host/sql/insert` and `host/iac/run`, a destroy `host/sql/delete` and `host/iac/destroy`, and a recovery `host/sql/update` and `host/iac/recover`, in addition to the provider operation and credential grants the resources need.

## Troubleshooting

- `'state' must name a directory inside the iac state root`: use a relative name without `..`.
- `ledger accepts collection, state and optional resource_key predicates`: remove `region` and other scope columns from ledger reads.
- Credential errors on destroy: the `--auth` configuration is passed only for the provider of the first resource in a converge or preview.  A destroy, and providers after the first, resolve credentials from the provider document's own settings and environment variables.
- A failed run that reports its resources compensated and none outstanding leaves tombstones for those keys in the ledger.  Verify the old resources are gone at the provider before converging again.
