Skip to main content
Glama

terraform

Execute Terraform commands to manage infrastructure as code, including init, plan, apply, and destroy operations for cloud resource provisioning and configuration.

Instructions

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

Input Schema

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

Implementation Reference

  • Main handler function that constructs and executes Terraform (or tflocal) commands based on input parameters like action, working directory, variables, etc., handling different actions such as init, plan, apply, destroy.
    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 defining the input parameters for the terraform tool, including action enum, working directory, variables, and action-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>;
  • Registration of the 'terraform' tool in the toolDefinitions map, linking 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,
    },

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-sysoperator'

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