Skip to main content
Glama

aws_ec2

Manage AWS EC2 instances by listing, creating, starting, stopping, or terminating them through the MCP SysOperator server.

Instructions

Manage AWS EC2 instances (list, create, start, stop, terminate)

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
actionYes
regionYes
instanceIdsNo
filtersNo
instanceTypeNo
imageIdNo
keyNameNo
securityGroupsNo
userDataNo
countNo
tagsNo
waitForCompletionNo
terminationProtectionNo

Implementation Reference

  • Main handler function that destructures input args, generates an Ansible playbook YAML based on the 'action' (list, create, terminate, start, stop), and executes it via executeAwsPlaybook helper.
    export async function ec2InstanceOperations(args: EC2InstanceOptions): Promise<string> {
      await verifyAwsCredentials();
    
      const { action, region, instanceIds, filters, instanceType, imageId, keyName, securityGroups, userData, count, tags, waitForCompletion, terminationProtection, ...restParams } = args;
    
      let playbookContent = `---
    - name: AWS EC2 ${action} operation
      hosts: localhost
      connection: local
      gather_facts: no
      tasks:`;
      
      switch (action) {
        case 'list':
          playbookContent += `
        - name: List EC2 instances
          amazon.aws.ec2_instance_info:
            region: "${region}"
    ${filters ? formatYamlParams({ filters }) : ''}
          register: ec2_info
        
        - name: Display instances
          debug:
            var: ec2_info.instances`;
          break;
          
        case 'create':
          playbookContent += `
        - name: Create EC2 instance
          amazon.aws.ec2_instance:
            region: "${region}"
            state: present
            instance_type: "${instanceType}"
            image_id: "${imageId}"
    ${formatYamlParams({
      key_name: keyName,
      security_groups: securityGroups,
      user_data: userData,
      exact_count: count,
      tags: tags,
      wait: waitForCompletion,
      termination_protection: terminationProtection,
      ...restParams
    })}
          register: ec2_create
        
        - name: Display created instance details
          debug:
            var: ec2_create`;
          break;
          
        case 'terminate':
          playbookContent += `
        - name: Terminate EC2 instances
          amazon.aws.ec2_instance:
            region: "${region}"
            instance_ids: ${JSON.stringify(instanceIds)}
            state: absent
            wait: ${waitForCompletion ? 'yes' : 'no'}
          register: ec2_terminate
          
        - name: Display termination result
          debug:
            var: ec2_terminate`;
          break;
          
        case 'start':
          playbookContent += `
        - name: Start EC2 instances
          amazon.aws.ec2_instance:
            region: "${region}"
            instance_ids: ${JSON.stringify(instanceIds)}
            state: running
            wait: ${waitForCompletion ? 'yes' : 'no'}
          register: ec2_start
          
        - name: Display start result
          debug:
            var: ec2_start`;
          break;
          
        case 'stop':
          playbookContent += `
        - name: Stop EC2 instances
          amazon.aws.ec2_instance:
            region: "${region}"
            instance_ids: ${JSON.stringify(instanceIds)}
            state: stopped
            wait: ${waitForCompletion ? 'yes' : 'no'}
          register: ec2_stop
          
        - name: Display stop result
          debug:
            var: ec2_stop`;
          break;
          
        default:
          // Should be caught by Zod validation, but good to have a fallback
          throw new AnsibleError(`Unsupported EC2 action: ${action}`);
      }
      
      // Execute the generated playbook
      return executeAwsPlaybook(`ec2-${action}`, playbookContent);
    }
  • Zod input schema for aws_ec2 tool, defining required 'action' and 'region', and optional parameters for EC2 operations.
    export const EC2InstanceSchema = z.object({
      action: EC2InstanceActionEnum,
      region: z.string().min(1, 'AWS region is required'),
      instanceIds: z.array(z.string()).optional(),
      filters: z.record(z.any()).optional(),
      instanceType: z.string().optional(),
      imageId: z.string().optional(),
      keyName: z.string().optional(),
      securityGroups: z.array(z.string()).optional(),
      userData: z.string().optional(),
      count: z.number().optional(),
      tags: z.record(z.string()).optional(),
      waitForCompletion: z.boolean().optional().default(true),
      terminationProtection: z.boolean().optional()
    });
  • Registration of the aws_ec2 tool in the toolDefinitions map, linking to its description, Zod schema, and handler function.
    aws_ec2: {
      description: 'Manage AWS EC2 instances (list, create, start, stop, terminate)',
      schema: aws.EC2InstanceSchema,
      handler: aws.ec2InstanceOperations,
    },
  • Helper function used by AWS tool handlers to execute dynamically generated Ansible playbooks in temporary directories.
    async function executeAwsPlaybook(
      operationName: string, 
      playbookContent: string, 
      extraParams: string = '',
      tempFiles: { filename: string, content: string }[] = [] // For additional files like templates, policies
    ): Promise<string> {
      let tempDir: string | undefined;
      try {
        // Create a unique temporary directory
        tempDir = await createTempDirectory(`ansible-aws-${operationName}`);
        
        // Write the main playbook file
        const playbookPath = await writeTempFile(tempDir, 'playbook.yml', playbookContent);
        
        // Write any additional temporary files
        for (const file of tempFiles) {
          await writeTempFile(tempDir, file.filename, file.content);
        }
    
        // Build the command
        const command = `ansible-playbook ${playbookPath} ${extraParams}`;
        console.error(`Executing: ${command}`);
    
        // Execute the playbook asynchronously
        const { stdout, stderr } = await execAsync(command);
        
        // Return stdout, or a success message if stdout is empty
        return stdout || `${operationName} completed successfully (no output).`;
    
      } catch (error: any) {
        // Handle execution errors
        const errorMessage = error.stderr || error.message || 'Unknown error';
        throw new AnsibleExecutionError(`Ansible execution failed for ${operationName}: ${errorMessage}`, error.stderr);
      } finally {
        // Ensure cleanup happens even if errors occur
        if (tempDir) {
          await cleanupTempDirectory(tempDir);
        }
      }
    }
  • Zod enum defining valid actions for the aws_ec2 tool.
    export const EC2InstanceActionEnum = z.enum(['list', 'create', 'terminate', 'start', 'stop']);
    export type EC2InstanceAction = z.infer<typeof EC2InstanceActionEnum>;
Behavior2/5

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

No annotations are provided, so the description carries full burden. It mentions actions but doesn't disclose critical behavioral traits: which actions are destructive (terminate), which require specific parameters, whether operations are synchronous/asynchronous, error handling, rate limits, or authentication requirements. The description is insufficient for a tool with 13 parameters and multiple operations.

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

Conciseness4/5

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

The description is appropriately concise - a single sentence that efficiently lists the core actions. It's front-loaded with the main purpose. However, it could be more structured by separating different operation types or indicating this is a multi-function tool.

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?

Given the complexity (13 parameters, multiple operations, no annotations, no output schema), the description is incomplete. It doesn't address parameter dependencies, operation-specific requirements, return values, error conditions, or authentication. For a tool with this level of complexity and no structured metadata, the description provides minimal context.

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?

Schema description coverage is 0%, so the description must compensate. It only mentions the 'action' parameter implicitly through listed operations but doesn't explain any of the 13 parameters, their relationships, or which parameters apply to which actions. No parameter semantics are provided beyond the basic action list.

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 tool manages AWS EC2 instances and lists specific actions (list, create, start, stop, terminate). It distinguishes from siblings by focusing on EC2 instances rather than other AWS services like S3 or Lambda. However, it doesn't specify that this is a multi-action tool that requires an 'action' parameter to select operation.

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 on when to use this tool versus alternatives. The description doesn't mention when to choose this tool over sibling tools like 'aws_dynamic_inventory' or 'list_inventory' for listing instances, or when to use other AWS service tools. There's no context about prerequisites, authentication, or environment setup.

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

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