Terraform
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.
Flags
-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=to-import/file.tf
The following command prints import and resource blocks for the query results as JSON:
$ terraform query -generate-config=file.tf -json