terraform query command
The terraform query command queries existing infrastructure for resources according to the tfquery.hcl file so that you can import them into your Terraform workspace.
Usage
$ terraform query [flags] [options]
Description
When you run the terraform query command, Terraform checks the current configuration directory for files with a .tfquery.hcl extension. Then, Terraform queries remote infrastructure for resources that match the list blocks defined in the query file and prints the results to the terminal. You can also add the -generate-config-out flag to generate configuration that you can use to import the resources. Refer to Import resources in bulk for more information.
Policy evaluation with terraform query requires Terraform v1.17.0 or later.
When you run queries remotely in HCP Terraform, HCP Terraform can evaluate policies against configuration generated from the discovered resources. Configure a Terraform policy set to apply to your workspace, or specify policy directories with the -policies flag.
HCP Terraform needs full resource data to generate policy input. Set include_resource = true in your list blocks to supply that data without writing a .tf file. Alternatively, use -generate-config-out to request full resource data and write generated resource and import blocks to your workstation. For queries started in the UI, select Generate starter configuration. The additional resource reads can increase query duration.
The -policies flag alone does not request resource data or enable configuration generation. Resource identities alone are insufficient policy input. Refer to Evaluate policies for setup and examples.
Flags
-policies=<PATH>: Selects an existing policy-set directory in the uploaded configuration for HCP Terraform to evaluate against discovered resources. Repeat this flag to include multiple directories.--policies=<PATH>is an equivalent spelling. HCP Terraform automatically evaluates applicable workspace policy sets even when you omit this flag.- Data type: Path
- Example: Evaluate policies
-var '<INPUT-VARIABLE>=<VALUE>': Specifies a key-value pair that sets an input variable defined in thetfquery.hclconfiguration. You can use this flag more than once to set additional input variables.- Data type: String.
- Example: Set input variables
-var-file=<FILENAME>: Specifies a file containing input variable values, in addition to the defaultterraform.tfvarsand*.auto.tfvarsfiles.- Data type: Filename
- Example: Set input variables
Options
-generate-config-out=<PATH/TO/OUTPUT>: Instructs Terraform to generateimportandresourceblocks for results so that you can import them. Terraform writes the configuration to a new file. The file must not already exist. When used with the-jsonoption, Terraform generates the configuration as part of the JSON output instead of writing it to a file.- Data type: Path
- Example: Generate import configuration
-json: Instructs Terraform to print results to the console in JSON format.- Data type: Boolean
- Example: Generate import configuration
-no-color: Terraform prints monochrome results.- Data type: Boolean
Examples
The following examples show how to use the command for common use cases.
Set input variables
The following command passes sets the value of the env input variable to prod:
$ terraform query -var 'env=prod'
Corresponding tfquery.hcl configuration:
list "aws_instance" "instances" {
provider = aws
}
variable "env" {
type = string
default = "test"
}
The following command loads variable values defined in my-vars.tfvars:
$ terraform query -var-file=my-vars.tfvars
Generate import configuration
The following command generates import and resource blocks for the query results to a file in the to-import directory:
$ terraform query -generate-config-out=to-import/file.tf
The following command prints import and resource blocks for the query results as JSON:
$ terraform query -generate-config-out=file.tf -json
Evaluate policies
Before you run a query with policies:
- Install a supported Terraform version as described in Description, and select a supported version for your HCP Terraform workspace.
- Set the workspace's execution mode to Remote or Agent. Agents enable the
queryoperation by default. Refer to HCP Terraform agents. - Use an organization with Terraform policy and Search policy evaluation enabled, including access to policy enforcement and versioned policy sets. Refer to Search policy requirements.
- Provide HCP Terraform credentials with read and write permissions for the workspace. Configure provider credentials in the workspace with permission to read the resources you query.
For example, add the following cloud block and provider requirement to main.tf. Replace ORGANIZATION_NAME and WORKSPACE_NAME with your organization and workspace names:
terraform {
cloud {
organization = "ORGANIZATION_NAME"
workspaces {
name = "WORKSPACE_NAME"
}
}
required_providers {
aws = {
source = "hashicorp/aws"
version = ">= 6.0.0"
}
}
}
Use an AWS provider version that supports listing aws_instance resources. Add the following query to instances.tfquery.hcl:
provider "aws" {
region = "us-east-2"
}
list "aws_instance" "example" {
provider = aws
include_resource = true
}
After you initialize the working directory, run the remote query:
$ terraform query
HCP Terraform automatically evaluates applicable Terraform policy sets configured for your workspace, including inherited project and organization-wide assignments. Query-time policy evaluation does not evaluate Sentinel or OPA policies. When you run remote queries, HCP Terraform also evaluates policies that you specify with the -policies flag.
To supply an explicit policy source, use the -policies flag to select a directory in your configuration that contains your policies. For this example, create a policies directory and add the following resource policy to policies/instance-type.policy.hcl. Refer to Write policies for policy syntax and inputs.
policy {
required_providers {
aws = {
source = "hashicorp/aws"
}
}
}
resource_policy "aws_instance" "instance_type" {
enforcement_level = "advisory"
enforce {
condition = attrs.instance_type == "t3.micro"
error_message = "Use t3.micro instances."
}
}
Run the remote query with the explicit policy directory. The include_resource = true setting supplies policy input without writing a .tf file:
$ terraform query -policies=./policies
To evaluate policies and write importable configuration, use an output file that does not exist:
$ terraform query -policies=./policies -generate-config-out=generated.tf
The -generate-config-out option instructs HCP Terraform to request full resource data and generate configuration. Use it as an alternative to setting include_resource = true in your list blocks when you also want to write an importable configuration file.
To evaluate policies from multiple existing directories, repeat the flag. For example:
$ terraform query -policies=./policies/security -policies=./policies/tagging
Explicit policy directories must exist in your working directory so Terraform includes them in the configuration uploaded to HCP Terraform. The paths must satisfy the Queries API path restrictions. These policies are independent of policies that HCP Terraform applies to your workspace from configured policy sets. Refer to Search and import resources in HCP Terraform for the UI workflow and automatic-policy opt-out control.
Inspect policy results
When HCP Terraform evaluates policies from workspace policy sets or the -policies flag against discovered resources, the remote query log includes policy summaries. The terminal output shows the evaluated-policy count and groups resource outcomes under Policy results for each list block:
| Result | Meaning |
|---|---|
Passed | The resource's generated configuration satisfies the evaluated policies. |
Failed | At least one policy rejects the resource's generated configuration. Review the policy diagnostics printed with the result. |
Unknown | Terraform cannot determine the outcome, for example because resource configuration, required attributes, or relationship data are unavailable. |
Error | Policy evaluation encounters an error. Review the diagnostics to identify the policy or runtime problem. |
N/A | Policies exist, but none target the resource type specified by the list block. This is not a passing result. |
For detailed policy results and diagnostics, inspect the Policy evaluation details in the HCP Terraform UI or retrieve the query log using log-read-url from the Queries API.
Query-time policy results are informational, including failures of mandatory policies. They do not block import or replace plan-time enforcement. Missing resource configuration produces an Unknown result, and generated input can omit relationships or attributes that policies need. A query with no failing policies does not establish that all resources pass policy evaluation during plan and apply operations. Review the results and generated configuration before continuing with the import workflow.