Terraform MCP Server

repository·main·Indexed 23 days ago

https://github.com/hashicorp/terraform-mcp-server

A Model Context Protocol (MCP) implementation that bridges LLMs with the Terraform Registry and HCP Terraform/Terraform Enterprise. It enables AI assistants to perform Infrastructure as Code (IaC) tasks, including managing workspaces, querying providers, and interacting with Terraform modules. The server supports both stdio and streamable-http transport modes and integrates with clients such as Claude Desktop, Cursor, VS Code, and Gemini Extensions.

Tokens
8.3K
Snippets
13
Records
40
Agent score
79%

What's inside terraform-mcp-server

  1. Overview of Terraform MCP Server

    main

    The Terraform MCP Server is a Model Context Protocol (MCP) server that integrates with Terraform Registry APIs. It enables advanced automation and interaction for Infrastructure as Code (IaC) development by providing tools for:

    • Terraform Registry Integration: Accessing public providers, modules, and policies.
    • HCP Terraform & Terraform Enterprise Support: Managing workspaces, listing organizations/projects, and accessing private registries.
    • Workspace Operations: Creating, updating, and deleting workspaces, including managing variables, tags, and runs.
    • Dual Transport Support: Operating in either stdio or streamable-http modes.
    • Observability: Providing OpenTelemetry (OTel) metrics for tool-call volume, latency, and failures in streamable-http mode.

    Security Warning: The MCP server may expose Terraform data to the MCP client and LLM. Do not use it with untrusted clients or LLMs.

  2. How the Terraform MCP Server works

    main

    The Terraform MCP (Model Context Protocol) server is a specialized tool that enables LLMs to generate high-quality Terraform code and manage Terraform workflows through API integrations with HCP Terraform and Terraform Enterprise.

    Core Capabilities

    Code Generation Enhancement

    • Registry Integration: Connects to both public and private Terraform registries for module and provider information.
    • Style Guide Compliance: Provides access to Terraform styling guide resources for consistent HCL/TF file generation.
    • Module Development: Supports creation of reusable Terraform modules following best practices.

    Workflow Automation

    • API Operations: Executes HCP Terraform and Terraform Enterprise commands via API calls.
    • Iterative Development: Enables automated testing, refinement, and enhancement of Terraform configurations.
    • State Management: Facilitates proper state handling and workspace management.
  3. Configure StreamableHTTP session modes

    main

    When using the StreamableHTTP transport, you can choose between two session modes:

    • Stateful Mode (Default): Maintains session state between requests, enabling context-aware operations.
    • Stateless Mode: Each request is processed independently. This is recommended for high-availability deployments or when using load balancers.

    To enable stateless mode, set the MCP_SESSION_MODE environment variable to stateless.

    export MCP_SESSION_MODE=stateless
  4. Understand Terraform MCP Server Transport Modes

    main

    The server supports two primary communication protocols:

    1. Stdio Transport (Default): Uses standard input/output with JSON-RPC. Best for local development and direct integration with local MCP clients.
    2. StreamableHTTP Transport: Uses HTTP and Server-Sent Events (SSE). Recommended for remote or distributed setups.

    StreamableHTTP Configuration:

    • Endpoint: http://{hostname}:8080/mcp
    • Health Check: http://{hostname}:8080/health
    • Environment Variables:
      • TRANSPORT_MODE=http to enable HTTP mode.
      • TRANSPORT_PORT=8080 to set the port.
      • TRANSPORT_HOST=0.0.0.0 (Required when running in Docker to allow external connections).
      • MCP_ORGANIZATION_ALLOWLIST=org1,org2 to restrict access to specific HCP Terraform organizations.
  5. Run End To End (e2e) tests

    main

    The E2E tests verify the terraform-mcp-server by building its Docker image, running the container, and interacting with the server via stdio to test existing Resources and Tools.

    To run these tests, you must have a service running that supports image building and container creation via the docker CLI.

    make test-e2e
  6. Best practices for Terraform code generation with MCP

    main

    To ensure high-quality, compatible, and valid Terraform code, follow these guidelines when using the MCP server tools:

    1. Registry-First Approach: Before generating code, always query registries for the latest provider/module versions and styling guidelines. If an enterprise token is provided, search private registries before falling back to public ones.
    2. Provider Consistency: Ensure all modules in a project use compatible provider versions. Use get_provider_details to verify compatibility before generation.
    3. Validation Workflow: Follow this sequence after generating code:
      • Run terraform validate immediately after generation.
      • Run terraform plan only if validation passes.
      • Use terraform fmt to ensure correct formatting.
    4. Safety First: Always obtain explicit user confirmation (yes/no) before executing destructive or state-changing operations such as create_run, apply_run, discard_run, or cancel_run.
  7. Install Terraform MCP Server in Visual Studio Code

    main

    To use the Terraform MCP server in VS Code (agent mode), add the configuration to your User Settings (JSON).

    For Version 0.3.0+, use the mcp key and define inputs to securely prompt for credentials. For Version 0.2.3 or lower, use the legacy format.

    You can also create a .vscode/mcp.json file in your workspace to share the configuration with your team (omit the mcp key for workspace-level files).

    // VS Code User Settings (JSON) - Version 0.3.0+
    {
      "mcp": {
        "servers": {
          "terraform": {
            "command": "docker",
            "args": [
              "run",
              "-i",
              "--rm",
              "-e", "TFE_TOKEN=${input:tfe_token}",
              "-e", "TFE_ADDRESS=${input:tfe_address}",
              "hashicorp/terraform-mcp-server:1.1.0"
            ]
          }
        },
        "inputs": [
          {
            "type": "promptString",
            "id": "tfe_token",
            "description": "Terraform API Token",
            "password": true
          },
          {
            "type": "promptString",
            "id": "tfe_address",
            "description": "Terraform Address",
            "password": false
          }
        ]
      }
    }
  8. Install Terraform MCP Server in Claude Code

    main

    Claude Code supports both stdio and streamable-http transports.

    Local (stdio) Transport: Use the claude mcp add command to register the server locally.

    Remote (streamable-http) Transport:

    1. Run the server in Docker with TRANSPORT_MODE=streamable-http.
    2. Use claude mcp add --transport http to connect to the running instance.
  9. Validation and User Confirmation workflows

    main

    Follow these specific workflows for validating code and performing destructive operations:

    Validation Workflow

    Execute validation in this specific order:

    1. terraform validate: Run immediately after code generation to verify syntax correctness, resource attribute validity, and provider configuration completeness.
    2. terraform plan: Only execute after successful validation to review resource changes and identify potential issues before apply.

    User Confirmation Requirements

    MANDATORY: Request explicit user confirmation before executing any of these destructive operations:

    • create_run: Initiates a new Terraform run
    • apply_run: Applies changes to infrastructure
    • discard_run: Discards a planned run
    • cancel_run: Cancels an in-progress run

    The confirmation prompt must include:

    • A clear description of the operation.
    • A list of resources to be affected.
    • Potential risks or impacts.
    • A request for explicit "yes/no" confirmation.
  10. Perform CLI-driven runs for Terraform Cloud

    main

    Once your configuration includes the terraform { cloud { ... } } block, follow these steps to execute your workflow:

    1. Initialize the workspace: Run terraform init to set up the backend and required providers.
    2. Execute the run: Run terraform apply to start the first run for the configured workspace.

    For a complete reference on this workflow, consult the official CLI workflow guide.

    terraform init
    terraform apply
  11. Install Terraform MCP Server for Claude Desktop, Amazon Q, or Kiro CLI

    main

    Add the following JSON block to your MCP configuration file. This setup uses Docker to run the server and requires providing your TFE_ADDRESS and TFE_TOKEN as environment variables.

    {
      "mcpServers": {
        "terraform": {
          "command": "docker",
          "args": [
            "run",
            "-i",
            "--rm",
            "-e", "TFE_ADDRESS=<<PASTE_TFE_ADDRESS_HERE>>",
            "-e", "TFE_TOKEN=<<PASTE_TFE_TOKEN_HERE>>",
            "hashicorp/terraform-mcp-server:1.1.0"
          ]
        }
      }
    }