Supply Chain

Query Terraform Configurations

Query Terraform HCL, plan, and state files with cnquery

Mondoo's terraform provider lets you use cnquery to query and analyze HashiCorp Terraform configurations. You can explore HCL files, plan files, and state files to understand your infrastructure-as-code.

Requirements

To analyze Terraform configurations with cnquery, you must have:

Connect to Terraform HCL files

To open a cnquery shell and query Terraform HCL configurations:

cnquery shell terraform PATH
For...Substitute...
PATHThe path to a Terraform file or directory

For example, to query a directory of Terraform files:

cnquery shell terraform ./infrastructure/

To query a single file:

cnquery shell terraform ./main.tf

To exclude the .terraform directory (which contains cached provider plugins and modules):

cnquery shell terraform ./infrastructure/ --ignore-dot-terraform

Connect to Terraform plan files

To query a Terraform plan file (JSON format), first generate the plan JSON:

terraform plan -out=tfplan
terraform show -json tfplan > tfplan.json

Then connect:

cnquery shell terraform plan ./tfplan.json

Connect to Terraform state files

To query a Terraform state file:

cnquery shell terraform state ./terraform.tfstate

Example queries

Files

Retrieve all Terraform files:

cnquery> terraform.files
terraform.files: [
  0: terraform.file path="main.tf"
  1: terraform.file path="variables.tf"
  ...
]

Resources

Retrieve all resources defined in the configuration:

cnquery> terraform.resources
terraform.resources: [
  0: terraform.resource type="aws_instance" nameLabel="web"
  1: terraform.resource type="aws_s3_bucket" nameLabel="data"
  ...
]

Modules

Retrieve all modules:

cnquery> terraform.modules
terraform.modules: [
  0: terraform.module name="vpc"
  ...
]

Variables

Retrieve variables from .tfvars files:

cnquery> terraform.tfvars
terraform.tfvars: {
  environment: "production"
  instance_type: "t3.micro"
  ...
}

Filter resources by type

Find all AWS S3 bucket resources:

cnquery> terraform.resources.where(type == "aws_s3_bucket")

Find all AWS EC2 instance resources with their arguments:

cnquery> terraform.resources.where(type == "aws_instance") { nameLabel arguments }

Resource blocks

Retrieve blocks within resources:

cnquery> terraform.resources { nameLabel blocks { type } }

Plan resource changes

When querying a plan file, retrieve planned resource changes:

cnquery> terraform.plan.resourceChanges
terraform.plan.resourceChanges: [
  0: terraform.plan.resourceChange address="aws_instance.web" actions=["create"]
  ...
]

State resources

When querying a state file, retrieve managed resources:

cnquery> terraform.state.resources
terraform.state.resources: [
  0: terraform.state.resource address="aws_instance.web"
  ...
]

Learn more

On this page