Synopsis
Search and list remote infrastructure with TerraformUsage
Description
Theterraform query command queries remote infrastructure for resources. Terraform will search for .tfquery.hcl files within the current configuration directory. It then uses the configured providers to query the remote infrastructure for resources that match the defined list blocks.
The results are printed to the terminal and can optionally be used to generate Terraform configuration and import blocks for discovered resources.
This command is particularly useful for:
- Discovering existing infrastructure that is not yet managed by Terraform
- Generating import configurations for existing resources
- Auditing cloud resources
- Finding resources that match specific criteria
Query Customization Options
Set a value for one of the input variables in the query file. Use the format
-var 'name=value'. This option can be specified multiple times to set multiple variables.Example: -var 'environment=production'Load variable values from the given file, in addition to the default files
terraform.tfvars and *.auto.tfvars. This option can be specified multiple times to include multiple variable files.Example: -var-file="prod.tfvars"Other Options
Instructs Terraform to generate import and resource blocks for any found results. The configuration is written to a new file at the specified path, which must not already exist.When this option is used with the
-json flag, the generated configuration will be part of the JSON output instead of written to a file.Example: -generate-config-out=generated.tfIf specified, machine-readable output will be printed in JSON format instead of human-readable output.Default:
falseIf specified, output won’t contain any color formatting.Default:
falseQuery Files
Query files use the.tfquery.hcl extension and define the search criteria for remote resources. These files are automatically discovered in the current configuration directory when the query command runs.
Exit Codes
- 0 - Success (operation completed successfully)
- 1 - Error occurred (flag parsing errors, backend errors, configuration errors, or operation failures)
- Operation-specific exit codes - The command returns the exit status from the backend operation
Examples
Basic query operation
.tfquery.hcl files and displays results in human-readable format.
Query with JSON output
Query with configuration generation
discovered.tf.
Query with variables
Query with variable file
Query with JSON and config generation
Query without color output
Notes
- The command sets parallelism to the default value (
DefaultParallelism) internally - The
-chdirglobal flag should be used to specify a working directory, not positional arguments - Actions cannot be specified during query operations (no
-targetflags) - The command respects provider development overrides and will show warnings when they are active