terraform-search-import

作者: hashicorp

使用 Terraform Search 查詢發現現有雲端資源,並大量匯入至 Terraform 管理。適用於將未受管理的基礎設施納入管理時…

npx skills add https://github.com/hashicorp/agent-skills --skill terraform-search-import

Terraform Search and Bulk Import

Discover existing cloud resources using declarative queries and generate configuration for bulk import into Terraform state.

References:

When to Use

  • Bringing unmanaged resources under Terraform control
  • Auditing existing cloud infrastructure
  • Migrating from manual provisioning to IaC
  • Discovering resources across multiple regions/accounts

IMPORTANT: Check Provider Support First

BEFORE starting, you MUST verify the target resource type is supported:

# Check what list resources are available
./scripts/list_resources.sh aws      # Specific provider
./scripts/list_resources.sh          # All configured providers

Decision Tree

  1. Identify target resource type (e.g., aws_s3_bucket, aws_instance)

  2. Check if supported: Run ./scripts/list_resources.sh <provider>

  3. Choose workflow:

    • ** If supported**: Check for terraform version available.
    • ** If terraform version is above 1.14.0** Use Terraform Search workflow (below)
    • ** If not supported or terraform version is below 1.14.0 **: Use Manual Discovery workflow (see references/MANUAL-IMPORT.md)

    Note: The list of supported resources is rapidly expanding. Always verify current support before using manual import.

Prerequisites

Before writing queries, verify the provider supports list resources for your target resource type.

Discover Available List Resources

Run the helper script to extract supported list resources from your provider:

# From a directory with provider configuration (runs terraform init if needed)
./scripts/list_resources.sh aws      # Specific provider
./scripts/list_resources.sh          # All configured providers

Or manually query the provider schema:

terraform providers schema -json | jq '.provider_schemas | to_entries | map({key: (.key | split("/")[-1]), value: (.value.list_resource_schemas // {} | keys)})'

Terraform Search requires an initialized working directory. Ensure you have a configuration with the required provider before running queries:

# terraform.tf
terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 6.0"
    }
  }
}

Run terraform init to download the provider, then proceed with queries.

Terraform Search Workflow (Supported Resources Only)

  1. Create .tfquery.hcl files with list blocks defining search queries
  2. Run terraform query to discover matching resources
  3. Generate configuration with -generate-config-out=<file>
  4. Review and refine generated resource and import blocks
  5. Run terraform plan and terraform apply to import

Query File Structure

Query files use .tfquery.hcl extension and support:

  • provider blocks for authentication
  • list blocks for resource discovery
  • variable and locals blocks for parameterization
# discovery.tfquery.hcl
provider "aws" {
  region = "us-west-2"
}

list "aws_instance" "all" {
  provider = aws
}

List Block Syntax

list "<list_type>" "<symbolic_name>" {
  provider = <provider_reference>  # Required

  # Optional: filter configuration (provider-specific)
  # The `config` block schema is provider-specific. Discover available options using `terraform providers schema -json | jq '.provider_schemas."registry.terraform.io/hashicorp/<provider>".list_resource_schemas."<resource_type>"'`

  config {
    filter {
      name   = "<filter_name>"
      values = ["<value1>", "<value2>"]
    }
    region = "<region>"  # AWS-specific
  }
  # Optional: limit results
  limit = 100
}

Supported List Resources

Provider support for list resources varies by version. Always check what's available for your specific provider version using the discovery script.

Query Examples

Basic Discovery

# Find all EC2 instances in configured region
list "aws_instance" "all" {
  provider = aws
}

Filtered Discovery

# Find instances by tag
list "aws_instance" "production" {
  provider = aws
  
  config {
    filter {
      name   = "tag:Environment"
      values = ["production"]
    }
  }
}

# Find instances by type
list "aws_instance" "large" {
  provider = aws
  
  config {
    filter {
      name   = "instance-type"
      values = ["t3.large", "t3.xlarge"]
    }
  }
}

Multi-Region Discovery

provider "aws" {
  region = "us-west-2"
}

locals {
  regions = ["us-west-2", "us-east-1", "eu-west-1"]
}

list "aws_instance" "all_regions" {
  for_each = toset(local.regions)
  provider = aws
  
  config {
    region = each.value
  }
}

Parameterized Queries

variable "target_environment" {
  type    = string
  default = "staging"
}

list "aws_instance" "by_env" {
  provider = aws
  
  config {
    filter {
      name   = "tag:Environment"
      values = [var.target_environment]
    }
  }
}

Running Queries

# Execute queries and display results
terraform query

# Generate configuration file
terraform query -generate-config-out=imported.tf

# Pass variables
terraform query -var='target_environment=production'

Query Output Format

list.aws_instance.all   account_id=123456789012,id=i-0abc123,region=us-west-2   web-server

Columns: <query_address> <identity_attributes> <name_tag>

Generated Configuration

The -generate-config-out flag creates:

# __generated__ by Terraform
resource "aws_instance" "all_0" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"
  # ... all attributes
}

import {
  to       = aws_instance.all_0
  provider = aws
  identity = {
    account_id = "123456789012"
    id         = "i-0abc123"
    region     = "us-west-2"
  }
}

Post-Generation Cleanup

Generated configuration includes all attributes. Clean up by:

  1. Remove computed/read-only attributes
  2. Replace hardcoded values with variables
  3. Add proper resource naming
  4. Organize into appropriate files
# Before: generated
resource "aws_instance" "all_0" {
  ami                    = "ami-0c55b159cbfafe1f0"
  instance_type          = "t2.micro"
  arn                    = "arn:aws:ec2:..."  # Remove - computed
  id                     = "i-0abc123"        # Remove - computed
  # ... many more attributes
}

# After: cleaned
resource "aws_instance" "web_server" {
  ami           = var.ami_id
  instance_type = var.instance_type
  subnet_id     = var.subnet_id
  
  tags = {
    Name        = "web-server"
    Environment = var.environment
  }
}

Import by Identity

Generated imports use identity-based import (Terraform 1.12+):

import {
  to       = aws_instance.web
  provider = aws
  identity = {
    account_id = "123456789012"
    id         = "i-0abc123"
    region     = "us-west-2"
  }
}

Best Practices

Query Design

  • Start broad, then add filters to narrow results
  • Use limit to prevent overwhelming output
  • Test queries before generating configuration

Configuration Management

  • Review all generated code before applying
  • Remove unnecessary default values
  • Use consistent naming conventions
  • Add proper variable abstraction

Troubleshooting

IssueSolution
"No list resources found"Check provider version supports list resources
Query returns emptyVerify region and filter values
Generated config has errorsRemove computed attributes, fix deprecated arguments
Import failsEnsure resource not already in state

Complete Example

# main.tf - Initialize provider
terraform {
  required_version = ">= 1.14"
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 6.0"  # Always use latest version
    }
  }
}

# discovery.tfquery.hcl - Define queries
provider "aws" {
  region = "us-west-2"
}

list "aws_instance" "team_instances" {
  provider = aws
  
  config {
    filter {
      name   = "tag:Owner"
      values = ["platform"]
    }
    filter {
      name   = "instance-state-name"
      values = ["running"]
    }
  }
  
  limit = 50
}
# Execute workflow
terraform init
terraform query
terraform query -generate-config-out=generated.tf
# Review and clean generated.tf
terraform plan
terraform apply

來自 hashicorp 的更多技能

provider-actions
hashicorp
使用 Plugin Framework 實作 Terraform Provider 動作。在開發於生命週期事件(前/後…)執行的命令式操作時使用。
official
provider-docs
hashicorp
使用 HashiCorp 推薦的模式、tfplugindocs 模板和 schema,為 Terraform Registry 建立、更新和審查 Terraform provider 文件…
official
aws-ami-builder
hashicorp
使用Packer的amazon-ebs建置器建立自訂Amazon Machine Images。透過HCL範本自動化從來源AMI建立AMI,並搭配佈建工具(Shell腳本、檔案上傳、組態管理)進行自訂。支援透過ami_regions進行多區域AMI分發,以及依名稱、擁有者和虛擬化類型進行靈活的來源AMI篩選。可透過環境變數、AWS憑證檔案或IAM執行個體設定檔進行驗證;包含範本的驗證與建置命令...
official
azure-image-builder
hashicorp
使用 Packer 建置 Azure 受控映像與 Azure Compute Gallery 映像。適用於為 Azure VM 建立自訂映像時使用。
official
azure-verified-modules
hashicorp
認證要求與Azure Terraform模組尋求AVM合規性的最佳實踐。強制執行提供者版本限制(azurerm >= 4.0, < 5.0;azapi >= 2.0, < 3.0),並禁止基於git的模組引用,改為使用固定的Terraform註冊表來源。要求所有識別碼採用小寫蛇形命名法、精確的變數類型、透過防腐層模式實現離散的輸出屬性,以及按字母順序排列的locals。新增資源時需要功能切換變數...
official
new-terraform-provider
hashicorp
使用 Plugin Framework 建立新的 Terraform provider。生成新的 Go 模組工作區,採用標準的「terraform-provider-」命名慣例,並初始化所需的依賴項。提供遵循 HashiCorp Plugin Framework 模式的範本 main.go 檔案,並附有待辦事項標記供自訂使用。透過執行建置與測試指令來驗證設定,確保 provider 能成功編譯並通過初步檢查。在建立新的工作區前,會先確認意圖以管理工作區。
official
provider-actions
hashicorp
使用 Plugin Framework 在資源生命週期事件中執行命令式的 Terraform Provider 動作。支援建立前/後與更新前/後的觸發機制(Terraform 1.14.0 不支援銷毀事件)。需以正確的框架類型、集合的 ElementType 及輸入驗證器定義適當的綱要。包含進度回報、逾時管理及長時間操作的全面錯誤處理。實作輪詢與...
official
provider-docs
hashicorp
使用 HashiCorp 推薦的模式、tfplugindocs 模板和 schema,為 Terraform Registry 建立、更新和審查 Terraform provider 文件。
official