Skip to content

Terraform

HCP Terraform / Terraform Enterprise runs, workspaces, policies and state as SQL, plus offline tfstate and plan readers

Connector software
Free and open source
Service credentials
Required
Use with an agent

Install the Orchard skill in your project to help your agent find connectors, configure them, and verify SQL results.

npx skills add Query-farm/vgi-skills --skill orchard

Copy this request into your coding agent to get started.

Use https://query.farm/products/orchard/connectors/terraform/index.md to help me query Terraform with DuckDB or Haybarn 2.0.1 and VGI protocol 3.4. Ask only for missing details about the result I need or whether I want local execution, self-hosting or Query Farm hosting. Check the connector's actual hosting availability, credentials and input requirements. Read one format of each needed reference and the exact object declarations before writing SQL. Use a released connector, and distinguish a saved example result from anything you actually execute. If you cannot run the query, tell me what remains to verify.

Resource types in a state file

Uses your connected account. Set up the connector and credentials to run it with your data.

SELECT type, count(*) AS instances
FROM terraform.files.read_state('sample:basic.tfstate')
GROUP BY type
ORDER BY type

Quick start

Choose where to run Terraform, then follow the steps below.

The connector runs alongside DuckDB or Haybarn. No Query Farm account is needed.

1. Install the vgi extension

Run this in your SQL client. On DuckDB, keep FROM query_farm on LOAD in later sessions.

setup.sql
SET allow_extension_repositories = 'allowed';

CREATE EXTENSION REPOSITORY IF NOT EXISTS query_farm
    WITH PREFIX 'https://duckdb-extensions.query.farm';

INSTALL vgi FROM query_farm;
LOAD vgi FROM query_farm;

2. Attach the connector

Attach the release directly

Downloads the latest release for your platform and caches it locally.

ATTACH 'terraform' AS terraform (
  TYPE vgi,
  LOCATION 'github-auto://Query-farm/vgi-terraform'
);

3. Add service credentials

After attaching, create the secret for the service you want to query in the same SQL session. Replace the placeholders with your service settings.

terraform credentials

HCP Terraform or Terraform Enterprise API token (user, team or organization token), the API hostname and the default organization.

Get these credentials →
secret.sql
CREATE SECRET terraform (
    TYPE terraform,
    token        '<TERRAFORM_TOKEN>',  -- secret
    hostname     '<hostname>',
    organization '<organization>',
    base_url     '<base_url>'
);
Credential fields and requirements →

4. Run a query

query.sql
SELECT type, count(*) AS instances
FROM terraform.files.read_state('sample:basic.tfstate')
GROUP BY type
ORDER BY type
More example queries →
Technical details
Verified connector release
v0.2.0
Engine
2.0.1
VGI protocol
3.4.0
Verified on
December 1, 2026
Release notes on GitHub
Pin a version for production

When running the connector yourself, keep a specific release until you’re ready to upgrade. Replace the ATTACH statement above with this one and follow the same extension and credential setup.

Attach the release directly

Uses the verified release each time you attach the connector.

ATTACH 'terraform' AS terraform (
  TYPE vgi,
  LOCATION 'github-auto://Query-farm/[email protected]'
);

Overview

HCP Terraform and Terraform Enterprise workspaces, runs, plans, policy results, state and drift as SQL, plus offline readers for terraform.tfstate files and plan JSON. Read-only.

Catalog

Everything terraform exposes once attached — read straight from the worker's released build.

terraform 3 schemas
files 4 functions

Offline readers for terraform.tfstate files and terraform show -json plans.

Schema examples (6)
Examples (6)

Resource types in a state file

SELECT type, count(*) AS instances
FROM terraform.files.read_state('sample:basic.tfstate')
GROUP BY type
ORDER BY type;

Instances that hold sensitive attributes

SELECT address, sensitive_attributes
FROM terraform.files.read_state('/path/to/terraform.tfstate')
WHERE len(sensitive_attributes) > 0
ORDER BY address;

Non-sensitive outputs

SELECT name, value
FROM terraform.files.state_outputs('sample:basic.tfstate')
WHERE NOT sensitive
ORDER BY name;

What forces each replacement

SELECT address, action_reason, replace_paths
FROM terraform.files.read_plan('sample:change.plan.json')
WHERE action = 'replace'
ORDER BY address;
2 more examples

Count planned actions

SELECT action, count(*) AS resources
FROM terraform.files.read_plan('sample:change.plan.json')
GROUP BY action
ORDER BY action;

Outputs whose value is only known after apply

SELECT name, action
FROM terraform.files.plan_outputs('sample:change.plan.json')
WHERE unknown
ORDER BY name;
Table functions
plan_outputs (path VARCHAR) 2 examples

Output changes of a terraform show -json plan; sensitive values are NULL.

Arguments
path VARCHAR
Path of the document on the worker's filesystem, or sample:<name> for a bundled sample (sample:basic.tfstate, sample:change.plan.json).
Returns columns
name VARCHAR
Output name.
action VARCHAR
create, update, delete or no-op.
sensitive BOOLEAN
Whether the output is sensitive before or after the change.
unknown BOOLEAN
Whether the new value is known only after apply.
before JSON
Value before the change; NULL when sensitive or new.
after JSON
Value after the change; NULL when sensitive, unknown or deleted.
Examples (2)

Outputs whose value is only known after apply

SELECT name, action
FROM terraform.files.plan_outputs('sample:change.plan.json')
WHERE unknown
ORDER BY name;
SELECT name, action, unknown
FROM terraform.files.plan_outputs('sample:change.plan.json')
WHERE action <> 'no-op'
ORDER BY name;
Link
read_plan (path VARCHAR) 3 examples

Resource changes of a terraform show -json plan: action, why, which attributes force replacement, and masked before/after values.

Arguments
path VARCHAR
Path of the document on the worker's filesystem, or sample:<name> for a bundled sample (sample:basic.tfstate, sample:change.plan.json).
Returns columns
address VARCHAR
Instance address, e.g. random_pet.server or module.naming.random_id.suffix.
module_address VARCHAR
Module path; NULL for the root module.
mode VARCHAR
managed or data.
type VARCHAR
Resource type.
name VARCHAR
Resource name.
instance_index VARCHAR
count index or for_each key as text; NULL for a single instance.
provider_name VARCHAR
Provider source address, e.g. registry.terraform.io/hashicorp/aws.
action VARCHAR
One verb: create, update, delete, replace, read or no-op (replace = delete+create in either order).
actions VARCHAR[]
The raw action list, e.g. [delete, create] (destroy-before-create) or [create, delete].
action_reason VARCHAR
Why the action was chosen, e.g. replace_because_cannot_update, replace_because_tainted, delete_because_no_resource_config.
replace_paths VARCHAR[]
Attribute paths that force the replacement, e.g. keepers or tags["Name"].
changed_attributes VARCHAR[]
Top-level attributes whose value changes or becomes unknown until apply.
previous_address VARCHAR
Address before a moved block renamed it.
deposed VARCHAR
Deposed object key the change applies to; NULL for the current object.
before JSON
Attributes before the change (sensitive values masked); NULL on create.
after JSON
Attributes after the change (sensitive values masked; unknown values are absent, see after_unknown); NULL on delete.
after_unknown JSON
Mirror of after marking values known only after apply with true.
terraform_version VARCHAR
Terraform / OpenTofu version that produced the plan.
Examples (3)

What forces each replacement

SELECT address, action_reason, replace_paths
FROM terraform.files.read_plan('sample:change.plan.json')
WHERE action = 'replace'
ORDER BY address;

Count planned actions

SELECT action, count(*) AS resources
FROM terraform.files.read_plan('sample:change.plan.json')
GROUP BY action
ORDER BY action;
SELECT address, replace_paths[1] AS forced_by
FROM terraform.files.read_plan('sample:change.plan.json')
WHERE action = 'replace'
ORDER BY address;
Link
read_state (path VARCHAR) 3 examples

Resource instances of a terraform.tfstate (v4) file with their attributes; sensitive attributes are masked.

Arguments
path VARCHAR
Path of the document on the worker's filesystem, or sample:<name> for a bundled sample (sample:basic.tfstate, sample:change.plan.json).
Returns columns
address VARCHAR
Instance address, e.g. module.naming.random_id.suffix or random_integer.port[0].
module_address VARCHAR
Module path (module.a.module.b); NULL for the root module.
mode VARCHAR
managed (a resource) or data (a data source).
type VARCHAR
Resource type, e.g. aws_instance.
name VARCHAR
Resource name in the configuration.
instance_index VARCHAR
count index or for_each key as text; NULL for a single instance.
provider VARCHAR
Provider configuration address, e.g. provider["registry.terraform.io/hashicorp/aws"].
schema_version BIGINT
Provider schema version of the attributes.
attributes JSON
Instance attributes as JSON, with every sensitive attribute replaced by "(sensitive value)".
sensitive_attributes VARCHAR[]
Paths of the attributes masked as sensitive, e.g. result or tags["secret"].
dependencies VARCHAR[]
Addresses this instance depends on.
tainted BOOLEAN
Whether the instance is tainted (will be replaced on the next apply).
deposed VARCHAR
Deposed object key (a create_before_destroy leftover); NULL for the current object.
create_before_destroy BOOLEAN
Whether the instance is replaced create-before-destroy.
terraform_version VARCHAR
Terraform / OpenTofu version that wrote the state.
serial BIGINT
State serial number.
lineage VARCHAR
State lineage id (shared by every serial of one state).
Examples (3)

Resource types in a state file

SELECT type, count(*) AS instances
FROM terraform.files.read_state('sample:basic.tfstate')
GROUP BY type
ORDER BY type;

Instances that hold sensitive attributes

SELECT address, sensitive_attributes
FROM terraform.files.read_state('/path/to/terraform.tfstate')
WHERE len(sensitive_attributes) > 0
ORDER BY address;
SELECT address, attributes->>'result' AS result
FROM terraform.files.read_state('sample:basic.tfstate')
WHERE type = 'random_password';
Link
state_outputs (path VARCHAR) 2 examples

Root module outputs of a terraform.tfstate (v4) file; sensitive outputs have a NULL value.

Arguments
path VARCHAR
Path of the document on the worker's filesystem, or sample:<name> for a bundled sample (sample:basic.tfstate, sample:change.plan.json).
Returns columns
name VARCHAR
Output name.
sensitive BOOLEAN
Whether the output is marked sensitive.
value JSON
Output value as JSON; NULL when sensitive.
type JSON
Terraform type of the value as JSON, e.g. "string" or ["tuple",["number","number"]].
Examples (2)

Non-sensitive outputs

SELECT name, value
FROM terraform.files.state_outputs('sample:basic.tfstate')
WHERE NOT sensitive
ORDER BY name;
SELECT name, sensitive, value IS NULL AS masked
FROM terraform.files.state_outputs('sample:basic.tfstate')
ORDER BY name;
Link
main 1 table · 22 functions

HCP Terraform / Terraform Enterprise API: workspaces, runs, policies, state, variables, teams, agents and registry.

Schema examples (25)
Examples (25)

Organizations and their default execution mode

SELECT name, default_execution_mode, cost_estimation_enabled
FROM terraform.main.organizations
ORDER BY name;

Projects by workspace count

SELECT name, workspace_count
FROM terraform.main.projects()
ORDER BY workspace_count DESC;

Workspaces whose latest run errored

SELECT name, terraform_version, current_run_id
FROM terraform.main.workspaces()
WHERE current_run_status = 'errored'
ORDER BY name;

Resources under management per project

SELECT project_id, count(*) AS workspaces, sum(resource_count) AS resources
FROM terraform.main.workspaces()
GROUP BY project_id
ORDER BY resources DESC;
21 more examples

Errored runs per workspace

SELECT workspace_name, count(*) AS errored_runs, max(created_at) AS latest
FROM terraform.main.runs()
WHERE status = 'errored'
GROUP BY workspace_name
ORDER BY errored_runs DESC;

Resources destroyed per workspace by applied runs

SELECT workspace_name, sum(resource_destructions) AS destroyed
FROM terraform.main.runs()
WHERE status = 'applied'
GROUP BY workspace_name
ORDER BY destroyed DESC;

Plans that would destroy resources

SELECT workspace_name, run_id, resource_destructions
FROM terraform.main.plans()
WHERE resource_destructions > 0
ORDER BY run_created_at DESC;

Failed applies

SELECT workspace_name, run_id, finished_at
FROM terraform.main.applies()
WHERE status = 'errored'
ORDER BY run_created_at DESC;

Runs that raise monthly cost by more than $100

SELECT workspace_name, run_id, delta_monthly_cost
FROM terraform.main.cost_estimates()
WHERE delta_monthly_cost > 100
ORDER BY delta_monthly_cost DESC;

Hard-failed policies of a run

SELECT id, hard_failed, soft_failed
FROM terraform.main.policy_checks('run-abc123')
WHERE hard_failed > 0;

Blocking OPA evaluations of a run

SELECT stage, status, mandatory_failed
FROM terraform.main.policy_evaluations('run-abc123')
WHERE policy_kind = 'opa' AND mandatory_failed > 0;

State versions written outside of runs

SELECT id, serial, created_at
FROM terraform.main.state_versions('prod-network')
WHERE run_id IS NULL
ORDER BY serial DESC;

Current outputs of a workspace

SELECT name, value
FROM terraform.main.state_version_outputs(workspace_id := 'ws-abc123')
WHERE NOT sensitive
ORDER BY name;

Resource types in a workspace

SELECT provider_type, count(*) AS n
FROM terraform.main.workspace_resources('ws-abc123')
GROUP BY provider_type
ORDER BY n DESC;

Non-sensitive Terraform variables of a workspace

SELECT key, value
FROM terraform.main.variables('ws-abc123')
WHERE category = 'terraform' AND NOT sensitive
ORDER BY key;

Global variable sets

SELECT name, var_count
FROM terraform.main.variable_sets()
WHERE global
ORDER BY name;

Environment variables a variable set injects

SELECT key, sensitive
FROM terraform.main.varset_variables('varset-abc123')
WHERE category = 'env'
ORDER BY key;

Teams that can manage workspaces

SELECT name, users_count
FROM terraform.main.teams()
WHERE organization_access->>'manage-workspaces' = 'true'
ORDER BY name;

Teams with admin access to a workspace

SELECT a.team_id, t.name
FROM terraform.main.team_access('ws-abc123') a
JOIN terraform.main.teams() t ON t.id = a.team_id
WHERE a.access = 'admin';

Agent pools by size

SELECT name, agent_count
FROM terraform.main.agent_pools()
ORDER BY agent_count DESC;

Agents that are not idle or busy

SELECT name, status, last_ping_at
FROM terraform.main.agents('apool-abc123')
WHERE status NOT IN ('idle', 'busy')
ORDER BY name;

Modules with their number of versions

SELECT namespace, name, provider, len(versions) AS version_count
FROM terraform.main.registry_modules()
ORDER BY version_count DESC;

Private providers

SELECT namespace, name
FROM terraform.main.registry_providers()
WHERE registry_name = 'private'
ORDER BY name;

Drifted workspaces

SELECT workspace_name, created_at
FROM terraform.main.assessments()
WHERE drifted
ORDER BY workspace_name;

Enabled destinations notified on drift

SELECT name, destination_type
FROM terraform.main.notification_configurations('ws-abc123')
WHERE enabled AND list_contains(triggers, 'assessment:drifted');
Tables
organizations 1 example10 cols

Organizations the token can see, with plan, execution-mode and security settings.

Columns
namenot null VARCHAR
Organization name (its id).
email VARCHAR
Notification email of the organization.
external_id VARCHAR
Immutable external id (org-...).
plan_identifier VARCHAR
Subscription plan, e.g. free, standard, plus.
default_execution_mode VARCHAR
Default execution mode for new workspaces: remote, local or agent.
cost_estimation_enabled BOOLEAN
Whether cost estimation runs on plans.
assessments_enforced BOOLEAN
Whether health assessments (drift detection) are enforced for every workspace.
saml_enabled BOOLEAN
Whether SAML single sign-on is enabled.
two_factor_conformant BOOLEAN
Whether every member has two-factor authentication enabled.
created_at TIMESTAMP WITH TIME ZONE
When the organization was created.
ConstraintsPRIMARY KEY (name)
Example

Organizations and their default execution mode

SELECT name, default_execution_mode, cost_estimation_enabled
FROM terraform.main.organizations
ORDER BY name;
Link
Table functions
agent_pools (organization := VARCHAR) 1 example

Self-hosted agent pools of an organization with their agent counts.

Named arguments
organization := VARCHAR
Organization name; default the ORGANIZATION of the terraform secret.
Returns columns
id VARCHAR
Agent pool id (apool-...).
name VARCHAR
Pool name.
organization_scoped BOOLEAN
Whether every workspace may use the pool.
agent_count BIGINT
Number of agents in the pool.
created_at TIMESTAMP WITH TIME ZONE
When the pool was created.
organization VARCHAR
Organization name.
Example

Agent pools by size

SELECT name, agent_count
FROM terraform.main.agent_pools()
ORDER BY agent_count DESC;
Link
agents (agent_pool_id VARCHAR) 1 example

Agents registered in one agent pool, with status and last ping time.

Arguments
agent_pool_id VARCHAR
Agent pool id (apool-...); list them with terraform.main.agent_pools().
Returns columns
id VARCHAR
Agent id (agent-...).
agent_pool_id VARCHAR
Agent pool id.
name VARCHAR
Agent name.
status VARCHAR
idle, busy, unknown, exited or errored.
ip_address VARCHAR
IP address the agent connects from.
last_ping_at TIMESTAMP WITH TIME ZONE
When the agent last checked in.
Example

Agents that are not idle or busy

SELECT name, status, last_ping_at
FROM terraform.main.agents('apool-abc123')
WHERE status NOT IN ('idle', 'busy')
ORDER BY name;
Link
applies (workspace_id := VARCHAR, organization := VARCHAR) 1 example

The apply of every run (newest run first): status, timings and the resources it added, changed and destroyed.

Named arguments
workspace_id := VARCHAR
List one workspace's runs (ws-...); default every run of the organization.
organization := VARCHAR
Organization name; default the ORGANIZATION of the terraform secret. Ignored when workspace_id is set.
Returns columns
id VARCHAR
Apply id (apply-...).
run_id VARCHAR
Run id (run-...).
workspace_id VARCHAR
Workspace id.
workspace_name VARCHAR
Workspace name.
run_created_at TIMESTAMP WITH TIME ZONE
When the run was created.
status VARCHAR
pending, managed_queued, queued, running, errored, canceled, finished or unreachable.
resource_additions BIGINT
Resources added.
resource_changes BIGINT
Resources changed.
resource_destructions BIGINT
Resources destroyed.
resource_imports BIGINT
Resources imported.
queued_at TIMESTAMP WITH TIME ZONE
When the apply was queued.
started_at TIMESTAMP WITH TIME ZONE
When the apply started.
finished_at TIMESTAMP WITH TIME ZONE
When the apply finished.
Example

Failed applies

SELECT workspace_name, run_id, finished_at
FROM terraform.main.applies()
WHERE status = 'errored'
ORDER BY run_created_at DESC;
Link
assessments (organization := VARCHAR) 1 example

Latest health assessment (drift detection) result of every workspace that has assessments enabled or a result.

Named arguments
organization := VARCHAR
Organization name; default the ORGANIZATION of the terraform secret.
Returns columns
workspace_id VARCHAR
Workspace id.
workspace_name VARCHAR
Workspace name.
assessments_enabled BOOLEAN
Whether health assessments are enabled on the workspace.
assessment_result_id VARCHAR
Id of the current assessment result (asmtres-...); NULL before the first assessment.
drifted BOOLEAN
Whether resources drifted from state.
succeeded BOOLEAN
Whether the assessment ran successfully.
error_message VARCHAR
Why the assessment failed.
created_at TIMESTAMP WITH TIME ZONE
When the assessment ran.
Example

Drifted workspaces

SELECT workspace_name, created_at
FROM terraform.main.assessments()
WHERE drifted
ORDER BY workspace_name;
Link
cost_estimates (workspace_id := VARCHAR, organization := VARCHAR) 1 example

The cost estimate of every run (newest run first): prior, proposed and delta monthly cost.

Named arguments
workspace_id := VARCHAR
List one workspace's runs (ws-...); default every run of the organization.
organization := VARCHAR
Organization name; default the ORGANIZATION of the terraform secret. Ignored when workspace_id is set.
Returns columns
id VARCHAR
Cost estimate id (ce-...).
run_id VARCHAR
Run id (run-...).
workspace_id VARCHAR
Workspace id.
workspace_name VARCHAR
Workspace name.
run_created_at TIMESTAMP WITH TIME ZONE
When the run was created.
status VARCHAR
pending, queued, finished, errored, canceled or skipped_due_to_targeting.
prior_monthly_cost DOUBLE
Monthly cost before the run (USD).
proposed_monthly_cost DOUBLE
Monthly cost after the run (USD).
delta_monthly_cost DOUBLE
proposed - prior (USD).
resources_count BIGINT
Resources considered.
matched_resources_count BIGINT
Resources with a known price.
unmatched_resources_count BIGINT
Resources without a price.
error_message VARCHAR
Why the estimate failed.
Example

Runs that raise monthly cost by more than $100

SELECT workspace_name, run_id, delta_monthly_cost
FROM terraform.main.cost_estimates()
WHERE delta_monthly_cost > 100
ORDER BY delta_monthly_cost DESC;
Link
notification_configurations (workspace_id VARCHAR) 1 example

Notification destinations of a workspace and the run events that trigger them; no secrets.

Arguments
workspace_id VARCHAR
Workspace id (ws-...); list them with terraform.main.workspaces().
Returns columns
id VARCHAR
Notification configuration id (nc-...).
workspace_id VARCHAR
Workspace id.
name VARCHAR
Name.
destination_type VARCHAR
generic, email, slack or microsoft-teams.
enabled BOOLEAN
Whether notifications are sent.
triggers VARCHAR[]
Events that notify, e.g. run:errored, assessment:drifted.
destination_host VARCHAR
Host of the webhook URL only (the path can hold a secret); NULL for email.
created_at TIMESTAMP WITH TIME ZONE
When it was created.
updated_at TIMESTAMP WITH TIME ZONE
When it last changed.
Example

Enabled destinations notified on drift

SELECT name, destination_type
FROM terraform.main.notification_configurations('ws-abc123')
WHERE enabled AND list_contains(triggers, 'assessment:drifted');
Link
plans (workspace_id := VARCHAR, organization := VARCHAR) 1 example

The plan of every run (newest run first): status, timings and resource add/change/destroy/import counts.

Named arguments
workspace_id := VARCHAR
List one workspace's runs (ws-...); default every run of the organization.
organization := VARCHAR
Organization name; default the ORGANIZATION of the terraform secret. Ignored when workspace_id is set.
Returns columns
id VARCHAR
Plan id (plan-...).
run_id VARCHAR
Run id (run-...).
workspace_id VARCHAR
Workspace id.
workspace_name VARCHAR
Workspace name.
run_created_at TIMESTAMP WITH TIME ZONE
When the run was created.
status VARCHAR
pending, managed_queued, queued, running, errored, canceled, finished or unreachable.
has_changes BOOLEAN
Whether the plan has changes.
resource_additions BIGINT
Resources to add.
resource_changes BIGINT
Resources to change in place.
resource_destructions BIGINT
Resources to destroy.
resource_imports BIGINT
Resources to import.
queued_at TIMESTAMP WITH TIME ZONE
When the plan was queued.
started_at TIMESTAMP WITH TIME ZONE
When the plan started.
finished_at TIMESTAMP WITH TIME ZONE
When the plan finished.
Example

Plans that would destroy resources

SELECT workspace_name, run_id, resource_destructions
FROM terraform.main.plans()
WHERE resource_destructions > 0
ORDER BY run_created_at DESC;
Link
policy_checks (run_id VARCHAR) 1 example

Sentinel policy checks of one run with pass/fail counts by enforcement level.

Arguments
run_id VARCHAR
Run id (run-...); list them with terraform.main.runs().
Returns columns
id VARCHAR
Policy check id (polchk-...).
run_id VARCHAR
Run id.
status VARCHAR
queued, passed, soft_failed, hard_failed, overridden, errored, canceled, unreachable.
scope VARCHAR
organization or workspace.
result BOOLEAN
Whether every policy passed.
passed BIGINT
Policies that passed.
total_failed BIGINT
Policies that failed.
hard_failed BIGINT
Hard-mandatory policies that failed.
soft_failed BIGINT
Soft-mandatory policies that failed.
advisory_failed BIGINT
Advisory policies that failed.
duration_ms BIGINT
Evaluation time in milliseconds.
status_timestamps JSON
When the check entered each status.
Example

Hard-failed policies of a run

SELECT id, hard_failed, soft_failed
FROM terraform.main.policy_checks('run-abc123')
WHERE hard_failed > 0;
Link
policy_evaluations (run_id VARCHAR) 1 example

OPA and Sentinel policy evaluations of one run (from its task stages), with result counts.

Arguments
run_id VARCHAR
Run id (run-...); list them with terraform.main.runs().
Returns columns
id VARCHAR
Policy evaluation id (poleval-...).
run_id VARCHAR
Run id.
task_stage_id VARCHAR
Task stage id (ts-...).
stage VARCHAR
Task stage: pre_plan, post_plan, pre_apply or post_apply.
status VARCHAR
pending, queued, running, passed, failed, errored, canceled, overridden, unreachable.
policy_kind VARCHAR
opa or sentinel.
policy_tool_version VARCHAR
OPA / Sentinel version.
passed BIGINT
Policies that passed.
advisory_failed BIGINT
Advisory policies that failed.
mandatory_failed BIGINT
Mandatory policies that failed.
errored BIGINT
Policies that errored.
created_at TIMESTAMP WITH TIME ZONE
When the evaluation was created.
updated_at TIMESTAMP WITH TIME ZONE
When it last changed.
Example

Blocking OPA evaluations of a run

SELECT stage, status, mandatory_failed
FROM terraform.main.policy_evaluations('run-abc123')
WHERE policy_kind = 'opa' AND mandatory_failed > 0;
Link
projects (organization := VARCHAR) 1 example

Projects of an organization with their workspace and team counts.

Named arguments
organization := VARCHAR
Organization name; default the ORGANIZATION of the terraform secret.
Returns columns
id VARCHAR
Project id (prj-...).
name VARCHAR
Project name.
description VARCHAR
Project description.
workspace_count BIGINT
Number of workspaces in the project.
team_count BIGINT
Number of teams with access to the project.
default_execution_mode VARCHAR
Default execution mode of new workspaces in the project.
organization VARCHAR
Organization name.
Example

Projects by workspace count

SELECT name, workspace_count
FROM terraform.main.projects()
ORDER BY workspace_count DESC;
Link
registry_modules (organization := VARCHAR) 1 example

Modules published in an organization's private registry, with their versions.

Named arguments
organization := VARCHAR
Organization name; default the ORGANIZATION of the terraform secret.
Returns columns
id VARCHAR
Module id (mod-...).
name VARCHAR
Module name.
namespace VARCHAR
Namespace (the organization for private modules).
provider VARCHAR
Provider the module targets, e.g. aws.
registry_name VARCHAR
'private' or 'public'.
status VARCHAR
Publishing status, e.g. setup_complete.
versions VARCHAR[]
Published versions.
created_at TIMESTAMP WITH TIME ZONE
When the module was published.
updated_at TIMESTAMP WITH TIME ZONE
When the module last changed.
Example

Modules with their number of versions

SELECT namespace, name, provider, len(versions) AS version_count
FROM terraform.main.registry_modules()
ORDER BY version_count DESC;
Link
registry_providers (organization := VARCHAR) 1 example

Providers published in an organization's private registry.

Named arguments
organization := VARCHAR
Organization name; default the ORGANIZATION of the terraform secret.
Returns columns
id VARCHAR
Provider id (prov-...).
name VARCHAR
Provider name.
namespace VARCHAR
Namespace.
registry_name VARCHAR
'private' or 'public'.
created_at TIMESTAMP WITH TIME ZONE
When the provider was published.
updated_at TIMESTAMP WITH TIME ZONE
When the provider last changed.
Example

Private providers

SELECT namespace, name
FROM terraform.main.registry_providers()
WHERE registry_name = 'private'
ORDER BY name;
Link
runs (workspace_id := VARCHAR, organization := VARCHAR) 2 examples

Runs of a workspace or a whole organization, newest first, with plan add/change/destroy counts.

Named arguments
workspace_id := VARCHAR
List one workspace's runs (ws-...); default every run of the organization.
organization := VARCHAR
Organization name; default the ORGANIZATION of the terraform secret. Ignored when workspace_id is set.
Returns columns
id VARCHAR
Run id (run-...).
workspace_id VARCHAR
Workspace id (ws-...).
workspace_name VARCHAR
Workspace name.
status VARCHAR
Run status: pending, planning, planned, cost_estimated, policy_checked, applying, applied, planned_and_finished, errored, canceled, discarded, ...
source VARCHAR
What created the run: tfe-ui, tfe-api or tfe-configuration-version (VCS push / CLI upload).
trigger_reason VARCHAR
Why the run started, e.g. manual.
message VARCHAR
Run message.
is_destroy BOOLEAN
Whether the run destroys all resources.
plan_only BOOLEAN
Whether the run is a speculative plan.
refresh_only BOOLEAN
Whether the run only refreshes state.
has_changes BOOLEAN
Whether the plan has changes.
auto_apply BOOLEAN
Whether the run applies automatically.
created_at TIMESTAMP WITH TIME ZONE
When the run was created (queued).
status_timestamps JSON
When the run entered each status, e.g. {"planning-at": ..., "applied-at": ...}.
plan_id VARCHAR
Plan id (plan-...).
apply_id VARCHAR
Apply id (apply-...).
cost_estimate_id VARCHAR
Cost estimate id (ce-...).
resource_additions BIGINT
Resources the plan adds.
resource_changes BIGINT
Resources the plan changes in place.
resource_destructions BIGINT
Resources the plan destroys.
resource_imports BIGINT
Resources the plan imports.
url VARCHAR
Link to the run in the HCP Terraform / TFE UI.
Examples (2)

Errored runs per workspace

SELECT workspace_name, count(*) AS errored_runs, max(created_at) AS latest
FROM terraform.main.runs()
WHERE status = 'errored'
GROUP BY workspace_name
ORDER BY errored_runs DESC;

Resources destroyed per workspace by applied runs

SELECT workspace_name, sum(resource_destructions) AS destroyed
FROM terraform.main.runs()
WHERE status = 'applied'
GROUP BY workspace_name
ORDER BY destroyed DESC;
Link
state_version_outputs (state_version_id := VARCHAR, workspace_id := VARCHAR) 1 example

Outputs of a state version, or of a workspace's current state; sensitive values are always NULL.

Named arguments
state_version_id := VARCHAR
State version id (sv-...) whose outputs to list.
workspace_id := VARCHAR
Workspace id (ws-...): list the outputs of its current state version instead.
Returns columns
id VARCHAR
Output id (wsout-...).
state_version_id VARCHAR
State version id (NULL when read through workspace_id).
workspace_id VARCHAR
Workspace id (NULL when read through state_version_id).
name VARCHAR
Output name.
sensitive BOOLEAN
Whether the output is sensitive.
type VARCHAR
Value type, e.g. string, array, object.
detailed_type JSON
Terraform type constraint as JSON, e.g. ["list","string"].
value JSON
Value as JSON; NULL when sensitive.
Example

Current outputs of a workspace

SELECT name, value
FROM terraform.main.state_version_outputs(workspace_id := 'ws-abc123')
WHERE NOT sensitive
ORDER BY name;
Link
state_versions (workspace_name VARCHAR, organization := VARCHAR) 1 example

Every state version of a workspace, newest first: serial, Terraform version, size and the run that wrote it.

Positional arguments
workspace_name VARCHAR
Workspace name (not id); the API lists state versions by organization and workspace name.
Named arguments
organization := VARCHAR
Organization name; default the ORGANIZATION of the terraform secret.
Returns columns
id VARCHAR
State version id (sv-...).
workspace_name VARCHAR
Workspace name.
serial BIGINT
State serial number.
state_version BIGINT
State file format version (4).
terraform_version VARCHAR
Terraform version that wrote the state.
status VARCHAR
pending, finalized or discarded.
size BIGINT
State size in bytes.
resources_processed BOOLEAN
Whether outputs and resources have been extracted.
vcs_commit_sha VARCHAR
VCS commit of the run's configuration.
run_id VARCHAR
Run that created the version (NULL for uploads).
created_at TIMESTAMP WITH TIME ZONE
When the version was created.
Example

State versions written outside of runs

SELECT id, serial, created_at
FROM terraform.main.state_versions('prod-network')
WHERE run_id IS NULL
ORDER BY serial DESC;
Link
team_access (workspace_id VARCHAR) 1 example

Which teams can access a workspace, and with what permissions.

Arguments
workspace_id VARCHAR
Workspace id (ws-...); list them with terraform.main.workspaces().
Returns columns
id VARCHAR
Team access id (tws-...).
team_id VARCHAR
Team id.
workspace_id VARCHAR
Workspace id.
access VARCHAR
read, plan, write, admin or custom.
runs VARCHAR
Run permission: read, plan or apply.
variables VARCHAR
Variable permission: none, read or write.
state_versions VARCHAR
State permission: none, read-outputs, read or write.
sentinel_mocks VARCHAR
Sentinel mock permission: none or read.
workspace_locking BOOLEAN
Whether the team can lock the workspace.
run_tasks BOOLEAN
Whether the team can manage run tasks.
Example

Teams with admin access to a workspace

SELECT a.team_id, t.name
FROM terraform.main.team_access('ws-abc123') a
JOIN terraform.main.teams() t ON t.id = a.team_id
WHERE a.access = 'admin';
Link
teams (organization := VARCHAR) 1 example

Teams of an organization with member counts and organization-level access flags.

Named arguments
organization := VARCHAR
Organization name; default the ORGANIZATION of the terraform secret.
Returns columns
id VARCHAR
Team id (team-...).
name VARCHAR
Team name.
visibility VARCHAR
'secret' or 'organization'.
users_count BIGINT
Number of members.
sso_team_id VARCHAR
Linked SSO team id.
organization_access JSON
Organization-level permissions as a JSON object of booleans.
organization VARCHAR
Organization name.
Example

Teams that can manage workspaces

SELECT name, users_count
FROM terraform.main.teams()
WHERE organization_access->>'manage-workspaces' = 'true'
ORDER BY name;
Link
variable_sets (organization := VARCHAR) 1 example

Variable sets of an organization with their scope and counts.

Named arguments
organization := VARCHAR
Organization name; default the ORGANIZATION of the terraform secret.
Returns columns
id VARCHAR
Variable set id (varset-...).
name VARCHAR
Variable set name.
description VARCHAR
Description.
global BOOLEAN
Whether it applies to every workspace of the organization.
priority BOOLEAN
Whether its values override workspace variables.
var_count BIGINT
Number of variables in the set.
workspace_count BIGINT
Number of workspaces it is attached to.
project_count BIGINT
Number of projects it is attached to.
updated_at TIMESTAMP WITH TIME ZONE
When the set last changed.
organization VARCHAR
Organization name.
Example

Global variable sets

SELECT name, var_count
FROM terraform.main.variable_sets()
WHERE global
ORDER BY name;
Link
variables (workspace_id VARCHAR) 1 example

Terraform and environment variables set on a workspace; sensitive values are always NULL.

Arguments
workspace_id VARCHAR
Workspace id (ws-...); list them with terraform.main.workspaces().
Returns columns
id VARCHAR
Variable id (var-...).
workspace_id VARCHAR
Workspace id.
key VARCHAR
Variable name.
value VARCHAR
Value; NULL when sensitive.
sensitive BOOLEAN
Whether the value is write-only (never returned).
category VARCHAR
'terraform' (input variable) or 'env' (environment variable).
hcl BOOLEAN
Whether the value is parsed as HCL.
description VARCHAR
Variable description.
version_id VARCHAR
Version id of the variable's current value.
Example

Non-sensitive Terraform variables of a workspace

SELECT key, value
FROM terraform.main.variables('ws-abc123')
WHERE category = 'terraform' AND NOT sensitive
ORDER BY key;
Link
varset_variables (varset_id VARCHAR) 1 example

Variables of one variable set; sensitive values are always NULL.

Arguments
varset_id VARCHAR
Variable set id (varset-...); list them with terraform.main.variable_sets().
Returns columns
id VARCHAR
Variable id (var-...).
varset_id VARCHAR
Variable set id.
key VARCHAR
Variable name.
value VARCHAR
Value; NULL when sensitive.
sensitive BOOLEAN
Whether the value is write-only (never returned).
category VARCHAR
'terraform' or 'env'.
hcl BOOLEAN
Whether the value is parsed as HCL.
description VARCHAR
Variable description.
created_at TIMESTAMP WITH TIME ZONE
When the variable was created.
Example

Environment variables a variable set injects

SELECT key, sensitive
FROM terraform.main.varset_variables('varset-abc123')
WHERE category = 'env'
ORDER BY key;
Link
workspace_resources (workspace_id VARCHAR) 1 example

Resources in a workspace's current state: address, type, module and provider.

Arguments
workspace_id VARCHAR
Workspace id (ws-...); list them with terraform.main.workspaces().
Returns columns
id VARCHAR
Resource id (wsr-...).
workspace_id VARCHAR
Workspace id.
address VARCHAR
Resource address, e.g. module.vpc.aws_subnet.private.
name VARCHAR
Resource name.
provider_type VARCHAR
Resource type, e.g. aws_instance.
provider VARCHAR
Provider address, e.g. hashicorp/aws.
module VARCHAR
Module path, 'root' for the root module.
name_index VARCHAR
count / for_each key, if any.
modified_by_state_version_id VARCHAR
State version that last changed the resource.
created_at TIMESTAMP WITH TIME ZONE
When the resource was first seen.
updated_at TIMESTAMP WITH TIME ZONE
When it last changed.
Example

Resource types in a workspace

SELECT provider_type, count(*) AS n
FROM terraform.main.workspace_resources('ws-abc123')
GROUP BY provider_type
ORDER BY n DESC;
Link
workspaces (organization := VARCHAR, tags := VARCHAR) 2 examples

Workspaces of an organization: project, Terraform version, execution mode, resource count, tags and current run status.

Named arguments
organization := VARCHAR
Organization name; default the ORGANIZATION of the terraform secret.
tags := VARCHAR
Comma-separated tag names a workspace must all carry (sent as search[tags]).
Returns columns
id VARCHAR
Workspace id (ws-...).
name VARCHAR
Workspace name.
organization VARCHAR
Organization name.
project_id VARCHAR
Project id (prj-...).
description VARCHAR
Workspace description.
terraform_version VARCHAR
Terraform version (or constraint) the workspace runs.
execution_mode VARCHAR
remote, local or agent.
resource_count BIGINT
Resources in the current state.
locked BOOLEAN
Whether the workspace is locked.
auto_apply BOOLEAN
Whether successful plans apply automatically.
assessments_enabled BOOLEAN
Whether health assessments (drift detection) run.
tag_names VARCHAR[]
Workspace tags.
working_directory VARCHAR
Directory Terraform runs in, relative to the configuration root.
vcs_repo_identifier VARCHAR
VCS repository (owner/repo) the workspace is connected to.
source VARCHAR
How the workspace was created, e.g. tfe-ui, tfe-api, terraform.
current_run_id VARCHAR
Id of the latest run (run-...).
current_run_status VARCHAR
Status of the latest run: applied, errored, planned, planned_and_finished, canceled, ...
current_state_version_id VARCHAR
Id of the current state version (sv-...).
current_assessment_result_id VARCHAR
Id of the latest health assessment result.
run_failures BIGINT
Number of failed runs.
policy_check_failures BIGINT
Number of failed policy checks.
plan_duration_average_seconds DOUBLE
Average plan duration in seconds.
apply_duration_average_seconds DOUBLE
Average apply duration in seconds.
latest_change_at TIMESTAMP WITH TIME ZONE
When the workspace's state last changed.
last_assessment_result_at TIMESTAMP WITH TIME ZONE
When the last health assessment finished.
created_at TIMESTAMP WITH TIME ZONE
When the workspace was created.
updated_at TIMESTAMP WITH TIME ZONE
When the workspace settings last changed.
url VARCHAR
Link to the workspace in the HCP Terraform / TFE UI.
Examples (2)

Workspaces whose latest run errored

SELECT name, terraform_version, current_run_id
FROM terraform.main.workspaces()
WHERE current_run_status = 'errored'
ORDER BY name;

Resources under management per project

SELECT project_id, count(*) AS workspaces, sum(resource_count) AS resources
FROM terraform.main.workspaces()
GROUP BY project_id
ORDER BY resources DESC;
Link
unified 2 tables

runs and task_runs in the shape shared by every orchestrator worker.

Schema examples (2)
Examples (2)

Failed deployments per workspace

SELECT pipeline, count(*) AS failures
FROM terraform.unified.runs
WHERE status = 'failed'
GROUP BY pipeline
ORDER BY failures DESC;

Average plan and apply duration

SELECT task_name, avg(duration_seconds) AS avg_seconds
FROM terraform.unified.task_runs
WHERE status = 'success'
GROUP BY task_name
ORDER BY task_name;
Tables
runs 1 example11 cols

HCP Terraform runs (infrastructure deployments) of the secret's organization in the shared orchestrator run shape.

Columns
orchestrator VARCHAR
Always 'terraform'.
run_idnot null VARCHAR
Run id (run-...).
pipeline VARCHAR
Workspace name.
status VARCHAR
queued, running, success, failed or cancelled.
raw_status VARCHAR
HCP Terraform run status, e.g. applied, errored, planned_and_finished.
trigger VARCHAR
manual (UI), api, event (VCS push or CLI upload) or other.
queued_at TIMESTAMP WITH TIME ZONE
When the run was created.
started_at TIMESTAMP WITH TIME ZONE
When the plan was queued or started.
ended_at TIMESTAMP WITH TIME ZONE
When the run reached a final status; NULL while active.
duration_seconds DOUBLE
Seconds from started_at (or queued_at) to ended_at.
url VARCHAR
Link to the run in the HCP Terraform / TFE UI.
ConstraintsPRIMARY KEY (run_id)
Example

Failed deployments per workspace

SELECT pipeline, count(*) AS failures
FROM terraform.unified.runs
WHERE status = 'failed'
GROUP BY pipeline
ORDER BY failures DESC;
Link
task_runs 1 example11 cols

The plan and apply phases of every HCP Terraform run in the shared orchestrator task-run shape.

Columns
orchestrator VARCHAR
Always 'terraform'.
run_id VARCHAR
Run id (run-...).
task_run_idnot null VARCHAR
Plan id (plan-...) or apply id (apply-...).
task_name VARCHAR
'plan' or 'apply'.
status VARCHAR
queued, running, success, failed, cancelled or skipped.
raw_status VARCHAR
Plan / apply status: pending, queued, running, finished, errored, canceled, unreachable.
attempt INTEGER
Always 1: a Terraform run phase is not retried in place.
started_at TIMESTAMP WITH TIME ZONE
When the phase started.
ended_at TIMESTAMP WITH TIME ZONE
When the phase finished, errored or was canceled.
duration_seconds DOUBLE
Seconds from started_at to ended_at.
url VARCHAR
Link to the run in the HCP Terraform / TFE UI.
ConstraintsPRIMARY KEY (task_run_id) · FOREIGN KEY (run_id) REFERENCES runs(run_id)
Example

Average plan and apply duration

SELECT task_name, avg(duration_seconds) AS avg_seconds
FROM terraform.unified.task_runs
WHERE status = 'success'
GROUP BY task_name
ORDER BY task_name;
Link

Credentials

The secret type terraform declares, as reported by the worker itself.

terraform

How to get these credentials

HCP Terraform or Terraform Enterprise API token (user, team or organization token), the API hostname and the default organization.

secret.sql
CREATE SECRET terraform (
    TYPE terraform,
    token        '<TERRAFORM_TOKEN>',  -- secret
    hostname     '<hostname>',
    organization '<organization>',
    base_url     '<base_url>'
);
Key Type Required Description
token secret VARCHAR — API token: a user, team or organization token from HCP Terraform / Terraform Enterprise, sent as 'Authorization: Bearer <token>'. Required. Read-only use: the worker only sends GET requests.
hostname VARCHAR — API hostname, default app.terraform.io (HCP Terraform). Set it to your Terraform Enterprise host, e.g. tfe.example.com.
organization VARCHAR — Organization used when a function's organization := argument is omitted, and by the unified tables.
base_url VARCHAR — Full base URL overriding HOSTNAME, e.g. http://127.0.0.1:8080 for a local mirror or a TFE instance on a non-standard port. The API path /api/v2 is appended.

The worker doesn't mark which keys are required.

Needed by agent_poolsagentsappliesassessmentscost_estimatesnotification_configurationsplanspolicy_checkspolicy_evaluationsprojectsregistry_modulesregistry_providers and 10 more functions

Create the secret in the same session, after attaching terraform — the worker registers its secret types at ATTACH. Keys marked secret are masked in duckdb_secrets(); angle-bracket values are placeholders. Read credentials from your environment or secret store in your application and pass them through your SQL client’s parameter bindings. Keep real values out of saved SQL and history. Native DuckDB and Haybarn do not provide a SQL getenv() function.

Try these queries

Instances that hold sensitive attributes

SELECT address, sensitive_attributes
FROM terraform.files.read_state('/path/to/terraform.tfstate')
WHERE len(sensitive_attributes) > 0
ORDER BY address

Uses read_state

Non-sensitive outputs

SELECT name, value
FROM terraform.files.state_outputs('sample:basic.tfstate')
WHERE NOT sensitive
ORDER BY name

Uses state_outputs

What forces each replacement

SELECT address, action_reason, replace_paths
FROM terraform.files.read_plan('sample:change.plan.json')
WHERE action = 'replace'
ORDER BY address

Uses read_plan

Outputs whose value is only known after apply

SELECT name, action
FROM terraform.files.plan_outputs('sample:change.plan.json')
WHERE unknown
ORDER BY name

Uses plan_outputs

Organizations and their default execution mode

SELECT name, default_execution_mode, cost_estimation_enabled
FROM terraform.main.organizations
ORDER BY name

Uses organizations

Projects by workspace count

SELECT name, workspace_count
FROM terraform.main.projects()
ORDER BY workspace_count DESC

Uses projects

30 more examples in the Catalog, each listed under the table or function it uses.

Questions it can answer

Plain-English questions from the worker's agent test tasks. An AI agent with this catalog attached should answer each one with SQL.

  • Using the Terraform worker's bundled sample plan sample:change.plan.json, which resources will be replaced, and which attribute forces each replacement?
  • In the bundled sample plan sample:change.plan.json, how many resource instances are planned for each action?
  • Which resource addresses does the bundled sample plan sample:change.plan.json delete without recreating them?
  • How many resource instances of each resource type are in the bundled sample state sample:basic.tfstate?
  • Which outputs of the bundled sample state sample:basic.tfstate are sensitive?
  • In the bundled sample state sample:basic.tfstate, which resource instances depend on random_pet.server?

Terraform is an independent open-source connector from Query.Farm. It is not affiliated with, endorsed by or sponsored by the services, projects or organisations it works with. Product names, logos and trademarks belong to their respective owners.