Skip to content

ThothCTL Check IaC Commands

Overview

The thothctl check iac command analyzes Infrastructure as Code generated artifacts including terraform plans, dependency graphs, cost estimates, blast radius assessments, and drift detection. This command helps ensure infrastructure changes are safe, cost-effective, and compliant before deployment.

Command Structure

Usage: thothctl check iac [OPTIONS]

  Analyze IaC artifacts: plans, dependencies, costs, blast radius, drift, and stack optimization

Options:
  --recursive                     Check recursively through subdirectories
  --outmd TEXT                    Output markdown file [default: tfplan_check_results.md]
  --tftool [terraform|tofu]       Terraform tool to use [default: tofu]
  -type, --check_type [tfplan|deps|blast-radius|cost-analysis|drift|stack-optimizer]
                                  Check type to perform [default: tfplan]
  --format [tree|boxart|html|dot] Output format for deps visualization [default: tree]
  --plan-file TEXT                Path to terraform plan JSON file (for blast-radius)
  --post-to-pr                    Post results as a PR comment (Azure DevOps or GitHub)
  --vcs-provider [auto|azure_repos|github]
                                  VCS provider for PR comments [default: auto]
  --space TEXT                    Space name for credential resolution (Azure DevOps)
  --ai-provider [openai|bedrock|azure|ollama]
                                  AI provider for drift analysis
  --ai-model TEXT                 AI model override (e.g. gpt-4, llama3)
  --project-name TEXT             Project name for drift history tracking
  --filter-tags TEXT              Filter drift results by resource tags
  --stacks TEXT                   Comma-separated stack filters for stack-optimizer
  --stacks-base-path TEXT         Base path for stack resolution [default: resources]
  --output-format [table|json|list]
                                  Output format for stack-optimizer [default: table]
  --help                          Show this message and exit.

Check Types

1. Terraform Plan Analysis (tfplan)

Analyzes terraform plan files and validates planned changes.

thothctl check iac -type tfplan --recursive

What it does: - Parses tfplan.json files - Analyzes resource changes (create/update/delete) - Extracts dependencies between resources - Generates summary reports

Requirements: - Must have tfplan.json files (generate with tofu show -json tfplan.bin > tfplan.json)

2. Dependency Analysis (deps)

Visualizes infrastructure dependencies and relationships.

thothctl check iac -type deps --recursive

What it does: - Generates dependency graphs using Terragrunt - Displays ASCII tree visualization - Calculates component risk scores - Shows resource relationships

Advanced Option:

# Show explicit input variables from other stacks
thothctl check iac -type deps --show-inputs

The --show-inputs flag enables advanced visualization that shows: - Input variables passed between stacks - Output values consumed by dependent stacks - External dependencies outside current directory

See Advanced Dependency Visualization for detailed documentation.

Requirements: - Terragrunt project structure - Valid terragrunt.hcl files

3. Blast Radius Assessment (blast-radius)

ITIL v4 compliant risk assessment combining dependency analysis with planned changes.

thothctl check iac -type blast-radius --recursive
thothctl check iac -type blast-radius --recursive --plan-file tfplan.json

What it does: - Component-level risk scoring - ITIL v4 change type classification - Impact analysis across dependencies - Automated approval workflow recommendations - Mitigation and rollback planning

See Blast Radius Assessment for detailed documentation.

4. Cost Analysis (cost-analysis)

Estimates AWS infrastructure costs from Terraform plans.

thothctl check iac -type cost-analysis --recursive

What it does: - Analyzes Terraform plans for AWS resources - Estimates monthly and annual costs - Provides service-by-service breakdown - Offers optimization recommendations - Works offline with regularly updated pricing data

Supported AWS Services: EC2, RDS, S3, Lambda, ELB/ALB/NLB, VPC, EBS, DynamoDB, CloudWatch, EKS, ECS, Secrets Manager, API Gateway, Bedrock

See Cost Analysis for detailed documentation.

5. Drift Detection (drift)

Detects infrastructure drift between IaC state and live cloud resources.

thothctl check iac -type drift --recursive
thothctl check iac -type drift --recursive --filter-tags "env=prod"
thothctl check iac -type drift --recursive --ai-provider ollama

What it does: - Parses tfplan.json files or runs live plans to detect drift - Classifies drift as changed, deleted, or unmanaged - Assigns severity (critical, high, medium, low) based on resource type - Filters by resource tags (--filter-tags "env=prod,team=*") - Evaluates .driftpolicy rules (block, alert, accept, ignore) - Tracks IaC coverage over time with trend analysis - AI-powered risk assessment and remediation guidance - Generates console, JSON, HTML, and markdown reports

Multi-cloud support: AWS, GCP, Azure resource types are classified with appropriate severity levels.

See Drift Detection for detailed documentation.

6. Stack Optimizer (stack-optimizer)

Deduplicates overlapping Terragrunt stack filters by resolving the DAG of dependencies and computing the minimal set of filters.

thothctl check iac -type stack-optimizer --stacks "Network/**,Compute/EC2/**"
thothctl check iac -type stack-optimizer --stacks "Network/**,Compute/EC2/**,Network/VPC/**" --output-format json

What it does: - Discovers all Terragrunt units (directories with terragrunt.hcl) under the stacks base path - Parses dependency blocks to build a full DAG of transitive dependencies - Resolves each input filter glob to its matching units plus all transitive dependencies - Identifies redundant filters whose resolved units are entirely contained by another filter - Returns the minimal filter set that covers the same infrastructure

Use case: When running terragrunt run-all with --include-dir filters in CI/CD, overlapping filters cause stacks to be planned/applied multiple times. The optimizer eliminates redundancy so each unit is processed exactly once.

Options: - --stacks (required): Comma-separated glob patterns relative to the stacks base path (e.g. "Network/**,Compute/EC2/**") - --stacks-base-path: Base directory for stack resolution (default: resources) - --output-format: table (Rich table, default), json (machine-readable), or list (one filter per line)

Example output (table format):

         Stack Optimizer Results          
┌──────────────────────────┬──────────┬──────────┬─────────────────┐
│ Stack Filter             │ Direct   │ With Deps│ Status          │
│                          │ Units    │          │                 │
├──────────────────────────┼──────────┼──────────┼─────────────────┤
│ Network/**               │ 3        │ 3        │ KEEP ✓          │
│ Compute/EC2/**           │ 2        │ 5        │ KEEP ✓          │
│ Network/VPC/**           │ 1        │ 1        │ REDUNDANT ✗     │
└──────────────────────────┴──────────┴──────────┴─────────────────┘

⚡ Removed 1 redundant filter(s): Network/VPC/**
📦 Units before: 9 → after dedup: 8

CI/CD integration:

# Get optimized filters as a plain list for scripting
OPTIMIZED=$(thothctl check iac -type stack-optimizer \
  --stacks "$STACKS" --output-format list)

# Use the optimized filters with terragrunt
for filter in $OPTIMIZED; do
  terragrunt run-all plan --include-dir "$filter"
done

Basic Usage Examples

Quick Plan Analysis

# Generate plan first
tofu plan -out=tfplan.bin
tofu show -json tfplan.bin > tfplan.json

# Analyze the plan
thothctl check iac -type tfplan --recursive

Dependency Visualization

thothctl check iac -type deps --recursive

Complete Pre-Deployment Analysis

# Generate terraform plan first
tofu plan -out=tfplan.bin
tofu show -json tfplan.bin > tfplan.json

# Analyze plan
thothctl check iac -type tfplan --recursive

# Estimate costs
thothctl check iac -type cost-analysis --recursive

# Assess blast radius with plan
thothctl check iac -type blast-radius --recursive --plan-file tfplan.json

Integration Workflow

Complete Pre-Deployment Workflow

# 1. Validate source structure first
thothctl check project iac -p stack -m strict

# 2. Generate terraform plan
tofu plan -out=tfplan.bin
tofu show -json tfplan.bin > tfplan.json

# 3. Analyze plan
thothctl check iac -type tfplan --recursive

# 4. Estimate costs
thothctl check iac -type cost-analysis --recursive

# 5. Analyze dependencies
thothctl check iac -type deps --recursive

# 6. Assess blast radius and risk
thothctl check iac -type blast-radius --recursive --plan-file tfplan.json

# 7. Follow ITIL v4 recommendations from output

PR Comment Integration

The --post-to-pr flag posts check results directly as a pull request comment, making analysis output visible in code reviews without leaving the VCS interface.

Supported Platforms

Platform Detection Max Comment Size
GitHub Actions GITHUB_ACTIONS env var 65,536 characters
Azure Pipelines SYSTEM_TEAMFOUNDATIONCOLLECTIONURI env var 150,000 characters

Comments that exceed the platform limit are automatically truncated with a notice.

GitHub Actions

Required environment variables (set automatically by GitHub Actions): - GITHUB_TOKEN — authentication token - GITHUB_REPOSITORY — owner/repo - GITHUB_REF — must be refs/pull/<number>/merge (PR trigger)

# .github/workflows/check.yml
name: IaC Check
on:
  pull_request:
    branches: [main]

jobs:
  check:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: pip install thothctl
      - run: |
          tofu plan -out=tfplan.bin
          tofu show -json tfplan.bin > tfplan.json
      - run: thothctl check iac -type tfplan --recursive --post-to-pr
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

Azure Pipelines

Required environment variables — all are set automatically by Azure Pipelines except the PAT:

Env Var Source Notes
SYSTEM_TEAMFOUNDATIONCOLLECTIONURI Built-in Organization URL
SYSTEM_TEAMPROJECT Built-in Project name
BUILD_REPOSITORY_NAME Built-in Repository name
SYSTEM_PULLREQUEST_PULLREQUESTID Built-in PR ID (only present on PR-triggered builds)
AZDO_PERSONAL_ACCESS_TOKEN You must map it Use $(System.AccessToken) — no PAT creation needed

Pipeline permissions

The build service identity needs one permission to post PR comments:

  1. Go to Project SettingsRepositories → your repo → Security
  2. Find <ProjectName> Build Service (<OrgName>)
  3. Set Contribute to pull requestsAllow

No other permissions, PAT creation, or admin access is required.

# azure-pipelines.yml
trigger: none
pr:
  branches:
    include: [main]

steps:
  - checkout: self
  - script: pip install thothctl
  - script: |
      tofu plan -out=tfplan.bin
      tofu show -json tfplan.bin > tfplan.json
  - script: thothctl check iac -type tfplan --recursive --post-to-pr
    displayName: 'Plan Summary Report'
    env:
      AZDO_PERSONAL_ACCESS_TOKEN: $(System.AccessToken)

Alternatively, credentials can be resolved from an encrypted thothctl space instead of System.AccessToken:

  - script: thothctl check iac -type tfplan --recursive --post-to-pr --space my-space
    env:
      AZDO_PERSONAL_ACCESS_TOKEN: $(AZDO_PERSONAL_ACCESS_TOKEN)

VCS Provider Selection

# Auto-detect from CI environment (default)
thothctl check iac -type tfplan --recursive --post-to-pr

# Explicitly specify provider
thothctl check iac -type tfplan --recursive --post-to-pr --vcs-provider github
thothctl check iac -type tfplan --recursive --post-to-pr --vcs-provider azure_repos --space my-space

Output Examples

Dependency Analysis Output

🔍 Infrastructure Dependency Analysis
=====================================

📊 Risk Assessment Summary
┌─────────────────┬────────────┬──────────────┬─────────────┐
│ Component       │ Risk Score │ Dependencies │ Dependents  │
├─────────────────┼────────────┼──────────────┼─────────────┤
│ vpc-main        │ 85%        │ 0            │ 8           │
│ security-groups │ 72%        │ 1            │ 3           │
└─────────────────┴────────────┴──────────────┴─────────────┘

Blast Radius Assessment Output

🎯 BLAST RADIUS ASSESSMENT (ITIL v4 Compliant)
===============================================

📊 Risk Summary
Risk Level: HIGH
Change Type: NORMAL
Total Components: 12
Affected Components: 7

📋 ITIL v4 Recommendations
• ⚠️ HIGH: Require senior management approval
• ⚠️ Schedule during maintenance window
• ⚠️ Prepare detailed rollback procedures

Configuration

Terraform Tool Selection

# Use OpenTofu
thothctl check iac -type tfplan --tftool tofu

# Use Terraform
thothctl check iac -type tfplan --tftool terraform

Output Customization

# Custom output file
thothctl check iac -type tfplan --outmd custom_results.md

# Recursive analysis
thothctl check iac -type tfplan --recursive

Best Practices

1. Regular Dependency Analysis

Run dependency analysis regularly to understand component relationships:

thothctl check iac -type deps --recursive

2. Pre-Deployment Risk Assessment

Always assess blast radius before major deployments:

thothctl check iac -type blast-radius --recursive --plan-file tfplan.json

3. Automated Validation

Integrate checks into CI/CD pipelines:

# In CI/CD pipeline
thothctl check iac -type tfplan --recursive --mode hard

# Post results to PR for visibility in code reviews
thothctl check iac -type tfplan --recursive --post-to-pr

4. Documentation Generation

Generate documentation from validation results:

thothctl check iac -type tfplan --recursive --outmd deployment_validation.md

Troubleshooting

Common Issues

Plan File Not Found

# Generate plan first
terraform plan -out=tfplan.json
# or
tofu plan -out=tfplan.json

Dependencies Not Detected

# Ensure terragrunt.hcl files exist
ls -la */terragrunt.hcl

# Check directory structure
tree -L 2

High Risk False Positives

  • Review component criticality settings
  • Validate dependency graph accuracy
  • Check change type detection logic

Module Structure Table

Displays module-specific files found in subfolders: - Module files: variables.tf, main.tf, outputs.tf, README.md - Subfolder content: Files within module directories

Example Output

╭──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
│ 🏗️ Infrastructure as Code Project Structure Check                                                                                                                                                                                 │
╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
⚛️ Checking root structure
📝 Checking content of subfolder terraform-aws-gitops-bridge-spoke

                                         🏗️ Root Structure                                          
╭───────────────────────────┬──────────┬────────────┬────────────┬────────────────────────────────╮
│ Item                      │ Type     │ Required   │ Status     │ Details                        │
├───────────────────────────┼──────────┼────────────┼────────────┼────────────────────────────────┤
│ common                    │ 📁       │ Required   │ ✅ Pass    │ .                          │
│ docs                      │ 📁       │ Required   │ ✅ Pass    │ .                          │
│ modules                   │ 📁       │ Required   │ ✅ Pass    │ .                          │
│ resources                 │ 📁       │ Required   │ ❌ Fail    │ .                          │
│ test                      │ 📁       │ Optional   │ ❌ Fail    │ .                          │
│ .gitignore                │ 📄       │ Required   │ ✅ Pass    │                                │
│ .pre-commit-config.yaml   │ 📄       │ Required   │ ✅ Pass    │                                │
│ README.md                 │ 📄       │ Required   │ ✅ Pass    │                                │
│ root.hcl                  │ 📄       │ Required   │ ✅ Pass    │                                │
╰───────────────────────────┴──────────┴────────────┴────────────┴────────────────────────────────╯

                                        📁 Module Structure                                        
╭───────────────────────────┬──────────┬────────────┬────────────┬────────────────────────────────╮
│ Item                      │ Type     │ Required   │ Status     │ Details                        │
├───────────────────────────┼──────────┼────────────┼────────────┼────────────────────────────────┤
│ variables.tf              │ 📄       │ Required   │ ✅ Pass    │ terraform-aws-gitops-bridge-s… │
│ main.tf                   │ 📄       │ Required   │ ✅ Pass    │ terraform-aws-gitops-bridge-s… │
│ outputs.tf                │ 📄       │ Required   │ ✅ Pass    │ terraform-aws-gitops-bridge-s… │
│ README.md                 │ 📄       │ Required   │ ✅ Pass    │ terraform-aws-gitops-bridge-s… │
╰───────────────────────────┴──────────┴────────────┴────────────┴────────────────────────────────╯

╭──────────────────────────────────────────────────────────────────────────────────────────────────────────── Summary ─────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
│ ❌ IaC project structure validation failed                                                                                                                                                                                       │
│ 💡 Review the issues above and ensure your project follows the expected structure                                                                                                                                                │
╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯

Configuration

The command uses configuration from .thothcf_project.toml files. If no configuration is found, it uses default template rules.

Default Project Structure Rules

[project_structure]
root_files = [
    ".gitignore",
    ".pre-commit-config.yaml", 
    "README.md",
    "root.hcl"
]

[[project_structure.folders]]
name = "common"
mandatory = true
type = "root"

[[project_structure.folders]]
name = "docs"
mandatory = true
type = "root"

[[project_structure.folders]]
name = "modules"
mandatory = true
type = "root"
content = [
    "variables.tf",
    "main.tf", 
    "outputs.tf",
    "README.md"
]

[[project_structure.folders]]
name = "resources"
mandatory = true
type = "root"

[[project_structure.folders]]
name = "test"
mandatory = false
type = "root"

Validation Behavior

Exit Codes

  • Exit Code 0: Validation passed successfully
  • Exit Code 1: Validation failed (required items missing)

Validation Logic

  • Required items: Must be present for validation to pass
  • Optional items: Can be missing without causing validation failure
  • Dynamic detection: Uses file extensions and validation output patterns instead of hardcoded lists
  • Template-based: Reads structure rules from thothcf configuration files

Key Features

Professional Output

  • Rich-formatted tables with color-coded status indicators
  • Separate tables for root structure vs module structure
  • Clear distinction between required and optional items
  • Detailed summary with actionable guidance

Dynamic Configuration

  • No hardcoded folder or file lists in the CLI code
  • Reads structure rules from .thothcf_project.toml template files
  • Falls back to default templates when no configuration is found
  • Supports custom project structure definitions

Proper Categorization

  • Root Structure: Items detected by patterns like "root exists! in ." or "exists!" (no path)
  • Module Structure: Items detected by patterns like "exists in [subfolder]" or "missing in [subfolder]"
  • Type Detection: Uses file extensions to determine if item is file (📄) or folder (📁)

Examples

Basic Project Structure Check

thothctl check project iac

Strict Validation

thothctl check project iac --mode strict

Check from Specific Directory

thothctl -d /path/to/project check project iac

Best Practices

  1. Template Configuration: Define project structure rules in .thothcf_project.toml for consistency
  2. CI/CD Integration: Add validation to CI/CD pipelines to enforce structure requirements
  3. Version Control: Include thothcf configuration files in version control
  4. Regular Validation: Run validation during development to catch issues early
  5. Custom Rules: Adapt structure rules to match your organization's standards

Troubleshooting

Common Issues

Using Default Options

Using default options
Solution: Create a .thothcf_project.toml file with your project structure rules.

Validation Failures

❌ - resources doesn't exist in .
Project structure is invalid
Solution: Create the missing required folder or update your structure rules.

Permission Issues

Error: [Errno 13] Permission denied: '/path/to/directory'
Solution: Ensure you have read permissions for all directories being validated.

Debugging

For detailed logs, run with debug flag:

thothctl --debug check project iac

Comparison: check iac vs check project iac

Understanding when to use each command:

Aspect check iac check project iac
Purpose Analyze generated artifacts Validate source structure
Focus Runtime analysis Code organization
Input tfplan.json, graphs Source .tf files
Validates Plans, costs, dependencies, impact Folders, files, structure
When to use Pre-deployment Development, CI/CD
Output Analysis reports Structure validation
Validation mode N/A (informational only) --mode soft/strict
Exit on issues No (always informational) Yes (in strict mode)

Recommended workflow:

# Step 1: Validate source structure (development/CI)
thothctl check project iac -p stack -m strict

# Step 2: Generate plan
tofu plan -out=tfplan.bin
tofu show -json tfplan.bin > tfplan.json

# Step 3: Analyze artifacts (pre-deployment)
thothctl check iac -type tfplan
thothctl check iac -type cost-analysis
thothctl check iac -type blast-radius

See check project iac documentation for source structure validation.