Skip to main content
Glama
tarnover
by tarnover

terraform

Manage infrastructure as code by executing Terraform commands such as init, plan, apply, and destroy through the Ansible MCP Server for streamlined operations and automation.

Instructions

Execute Terraform commands (init, plan, apply, destroy, validate, output, etc.)

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
actionYes
autoApproveNo
backendConfigNo
lockTimeoutNo
refreshNo
stateNo
targetNo
useLocalstackNo
varFilesNo
varsNo
workingDirYes
workspaceNo

Implementation Reference

  • The primary handler function terraformOperations that constructs and executes Terraform CLI commands based on input options, including support for LocalStack via tflocal.
    export async function terraformOperations(options: TerraformOptions): Promise<string> {
      const { 
        action, 
        workingDir, 
        varFiles, 
        vars, 
        useLocalstack, 
        autoApprove, 
        backendConfig, 
        state,
        target,
        lockTimeout,
        refresh,
        workspace
      } = options;
      
      // Determine if we should use terraform or tflocal command
      const terraformCmd = useLocalstack ? 'tflocal' : 'terraform';
    
      // If using tflocal, verify it's installed
      if (useLocalstack) {
        await verifyTflocalInstalled();
      } else {
        // Otherwise, verify terraform is installed
        await verifyTerraformInstalled();
      }
    
      // Base command with terraform/tflocal and action
      let command = `cd "${workingDir}" && ${terraformCmd} ${action}`;
    
      // Add var files if specified
      if (varFiles && varFiles.length > 0) {
        command += ' ' + varFiles.map(file => `-var-file="${file}"`).join(' ');
      }
    
      // Add vars if specified
      if (vars && Object.keys(vars).length > 0) {
        command += ' ' + formatCommandParams(vars, '-var');
      }
    
      // Add backend config if specified
      if (backendConfig && Object.keys(backendConfig).length > 0) {
        command += ' ' + formatCommandParams(backendConfig, '-backend-config');
      }
    
      // Add specific parameters based on action
      switch (action) {
        case 'init':
          // No special options needed here
          break;
          
        case 'apply':
        case 'destroy':
          // Add auto-approve if specified
          if (autoApprove) {
            command += ' -auto-approve';
          }
          
          // Add refresh option
          if (refresh !== undefined) {
            command += ` -refresh=${refresh ? 'true' : 'false'}`;
          }
          
          // Add state file if specified
          if (state) {
            command += ` -state="${state}"`;
          }
          
          // Add targets if specified
          if (target && target.length > 0) {
            command += ' ' + target.map(t => `-target="${t}"`).join(' ');
          }
          
          // Add lock timeout if specified
          if (lockTimeout) {
            command += ` -lock-timeout=${lockTimeout}`;
          }
          break;
          
        case 'plan':
          // Add refresh option
          if (refresh !== undefined) {
            command += ` -refresh=${refresh ? 'true' : 'false'}`;
          }
          
          // Add state file if specified
          if (state) {
            command += ` -state="${state}"`;
          }
          
          // Add targets if specified
          if (target && target.length > 0) {
            command += ' ' + target.map(t => `-target="${t}"`).join(' ');
          }
          
          // Add lock timeout if specified
          if (lockTimeout) {
            command += ` -lock-timeout=${lockTimeout}`;
          }
          break;
          
        case 'workspace':
          // Add workspace name if specified
          if (workspace) {
            command += ` select ${workspace}`;
          } else {
            command += ' list'; // Default to listing workspaces if no name is provided
          }
          break;
          
        // For other actions (validate, output, import), no special handling needed
      }
    
      // For debug purposes
      console.log(`Executing Terraform command: ${command}`);
    
      try {
        // Execute the command
        const { stdout, stderr } = await execAsync(command);
        
        // Adjust output based on action
        switch (action) {
          case 'output':
            // Try to parse JSON output
            try {
              const outputJson = JSON.parse(stdout);
              return JSON.stringify(outputJson, null, 2);
            } catch (error) {
              // If not JSON, return as is
              return stdout;
            }
            
          default:
            return stdout || `Terraform ${action} completed successfully (no output).`;
        }
      } catch (error: any) {
        const errorMessage = error.stderr || error.message || 'Unknown error';
        throw new AnsibleExecutionError(`Terraform execution failed for ${action}: ${errorMessage}`, error.stderr);
      }
    }
  • Zod schema TerraformSchema defining the input validation for the terraform tool, including action enum and various Terraform-specific options.
    export const TerraformSchema = z.object({
      action: TerraformActionEnum,
      workingDir: z.string().min(1, 'Working directory is required'),
      varFiles: z.array(z.string()).optional(),
      vars: z.record(z.any()).optional(),
      autoApprove: z.boolean().optional().default(false),
      useLocalstack: z.boolean().optional().default(false),
      backendConfig: z.record(z.string()).optional(),
      state: z.string().optional(),
      target: z.array(z.string()).optional(),
      lockTimeout: z.string().optional(),
      refresh: z.boolean().optional().default(true),
      workspace: z.string().optional()
    });
    
    export type TerraformOptions = z.infer<typeof TerraformSchema>;
  • Tool registration in the toolDefinitions map, linking the name 'terraform' to its description, schema, and handler function.
    terraform: {
      description: 'Execute Terraform commands (init, plan, apply, destroy, validate, output, etc.)',
      schema: terraform.TerraformSchema,
      handler: terraform.terraformOperations,
    },
  • Helper function verifyTerraformInstalled used by the handler to ensure Terraform is available before execution.
    export async function verifyTerraformInstalled(): Promise<void> {
      const isInstalled = await checkTerraformInstalled();
      if (!isInstalled) {
        throw new TerraformNotInstalledError();
      }
    }
  • Internal helper formatCommandParams used within the handler to format -var and other Terraform CLI parameters from input objects.
    function formatCommandParams(params: Record<string, any> | undefined, prefix: string): string {
      if (!params || Object.keys(params).length === 0) {
        return '';
      }
      
      return Object.entries(params)
        .map(([key, value]) => {
          if (typeof value === 'string') {
            // For string values, wrap in quotes
            return `${prefix} ${key}="${value}"`;
          } else if (typeof value === 'object') {
            // For objects/arrays, convert to JSON and wrap in quotes
            return `${prefix} ${key}='${JSON.stringify(value)}'`;
          } else {
            // For numbers, booleans, etc.
            return `${prefix} ${key}=${value}`;
          }
        })
        .join(' ');
    }
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden of behavioral disclosure. It mentions 'Execute Terraform commands' which implies mutation capabilities (apply, destroy), but doesn't warn about destructive operations, authentication requirements, state management implications, or error handling. For a tool with potentially destructive actions like 'destroy', this is insufficient.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is extremely concise - a single sentence that efficiently communicates the core functionality. It's front-loaded with the main purpose and includes helpful examples. Every word earns its place with no redundancy.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a complex tool with 12 parameters, no annotations, no output schema, and 0% schema description coverage, the description is severely incomplete. It doesn't address Terraform's state management, authentication, destructive operations, or parameter usage. The agent would struggle to use this tool correctly without significant external knowledge.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters2/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

With 0% schema description coverage for 12 parameters, the description provides no information about any parameters. It doesn't explain what 'action' does, what 'workingDir' represents, or the purpose of other parameters like 'autoApprove', 'backendConfig', or 'target'. The description fails to compensate for the complete lack of schema documentation.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the verb ('Execute') and resource ('Terraform commands') with specific examples of commands (init, plan, apply, etc.). It distinguishes from sibling tools by focusing on Terraform rather than AWS or other infrastructure tools, though it doesn't explicitly differentiate from all siblings.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

No guidance is provided on when to use this tool versus alternatives like AWS CloudFormation or other infrastructure-as-code approaches. The description only lists what commands can be executed without context about appropriate use cases or prerequisites.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Related Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/tarnover/mcp-ansible'

If you have feedback or need assistance with the MCP directory API, please join our Discord server