Skip to main content
Glama
tarnover
by tarnover

aws_vpc

Automate AWS VPC management in Ansible by listing, creating, or deleting virtual private clouds, configuring subnets, DNS settings, and tags across specified regions.

Instructions

Manage AWS VPC networks

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
actionYes
cidrBlockNo
dnsHostnamesNo
dnsSupportNo
nameNo
regionYes
subnetsNo
tagsNo
vpcIdNo

Implementation Reference

  • Main handler function for the aws_vpc tool. Generates and executes an Ansible playbook for VPC operations (list, create with optional subnets, delete) using AWS collection modules.
    export async function vpcOperations(args: VPCOptions): Promise<string> {
      await verifyAwsCredentials();
    
      const { action, region, vpcId, cidrBlock, name, dnsSupport, dnsHostnames, tags, subnets } = args;
    
      let playbookContent = `---
    - name: AWS VPC ${action} operation
      hosts: localhost
      connection: local
      gather_facts: no
      tasks:`;
      
      switch (action) {
        case 'list':
          playbookContent += `
        - name: List VPCs
          amazon.aws.ec2_vpc_net_info:
            region: "${region}"
          register: vpc_info
        
        - name: Display VPCs
          debug:
            var: vpc_info.vpcs`;
          break;
          
        case 'create':
          playbookContent += `
        - name: Create VPC
          amazon.aws.ec2_vpc_net:
            region: "${region}"
            cidr_block: "${cidrBlock}"
            state: present
    ${formatYamlParams({
      name,
      dns_support: dnsSupport,
      dns_hostnames: dnsHostnames,
      tags
    })}
          register: vpc_create
        
        - name: Display VPC details
          debug:
            var: vpc_create.vpc`;
          
          // If subnets are specified, add subnet creation task
          if (subnets && subnets.length > 0) {
            playbookContent += `
            
        - name: Create subnets
          amazon.aws.ec2_vpc_subnet:
            region: "${region}"
            vpc_id: "{{ vpc_create.vpc.id }}"
            cidr: "{{ item.cidr }}"
            az: "{{ item.az | default(omit) }}"
            tags: "{{ item.tags | default(omit) }}"
            state: present
          loop:
    ${subnets.map((subnet) => `        - ${JSON.stringify(subnet)}`).join('\n')}
          register: subnet_create
          
        - name: Display subnet details
          debug:
            var: subnet_create`;
          }
          break;
          
        case 'delete':
          playbookContent += `
        - name: Delete VPC
          amazon.aws.ec2_vpc_net:
            region: "${region}"
            vpc_id: "${vpcId}"
            state: absent
          register: vpc_delete
          
        - name: Display deletion result
          debug:
            var: vpc_delete`;
          break;
          
        default:
          throw new AnsibleError(`Unsupported VPC action: ${action}`);
      }
      
      // Execute the generated playbook
      return executeAwsPlaybook(`vpc-${action}`, playbookContent);
    }
  • Zod schema defining input validation for aws_vpc tool, including action enum (list/create/delete), required region, and optional parameters like vpcId, cidrBlock, tags, and subnets array.
    // AWS VPC Schema
    export const VPCSchema = z.object({
      action: VPCActionEnum,
      region: z.string().min(1, 'AWS region is required'),
      vpcId: z.string().optional(),
      cidrBlock: z.string().optional(),
      name: z.string().optional(),
      dnsSupport: z.boolean().optional(),
      dnsHostnames: z.boolean().optional(),
      tags: z.record(z.string()).optional(),
      subnets: z.array(z.object({
        cidr: z.string(),
        az: z.string().optional(),
        tags: z.record(z.string()).optional()
      })).optional()
    });
    
    export type VPCOptions = z.infer<typeof VPCSchema>;
  • Registration of aws_vpc tool in the toolDefinitions object, linking to its description, schema (VPCSchema), and handler (vpcOperations).
    aws_vpc: {
      description: 'Manage AWS VPC networks',
      schema: aws.VPCSchema,
      handler: aws.vpcOperations,
    },
  • Helper function used by aws_vpc handler to execute the dynamically generated Ansible playbook, handling temp files and cleanup.
    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);
        }
      }
    }
  • Helper function to format parameters into YAML strings for embedding in generated Ansible playbooks, used by aws_vpc handler.
    const formatYamlParams = (params: Record<string, any>, indentation: number = 6): string => {
      // Filter out undefined/null values and format each key-value pair
      return Object.entries(params)
        .filter(([_, value]) => value !== undefined && value !== null)
        .map(([key, value]) => {
          const indent = ' '.repeat(indentation);
          let formattedValue;
          
          // Format based on value type
          if (typeof value === 'string') {
            // Basic YAML string escaping (double quotes, escape backslashes and double quotes)
            formattedValue = `"${value.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
          } else if (Array.isArray(value) || typeof value === 'object') {
            // Use JSON.stringify for arrays and objects, assuming it's valid YAML subset
            formattedValue = JSON.stringify(value); 
          } else {
            formattedValue = value; // Numbers, booleans
          }
          return `${indent}${key}: ${formattedValue}`;
        })
        .join('\n');
    };
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. 'Manage' implies both read and write operations, but the description doesn't disclose behavioral traits like authentication requirements, rate limits, destructive consequences of delete actions, or what happens when creating VPCs with specific configurations. The description is too generic to provide meaningful behavioral context.

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 at just three words. It's front-loaded with the essential information (verb and resource) with zero wasted words. While under-specified, it's structurally efficient.

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 9 parameters, nested objects, no output schema, and no annotations, the description is inadequate. It doesn't explain the tool's scope, behavior, parameter usage, or expected outcomes. The agent would struggle to use this tool correctly without significant trial and error or 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 9 parameters, the description provides no parameter information beyond what's in the schema. It doesn't explain what 'action' values do, what 'cidrBlock' represents, how 'subnets' array should be structured, or any parameter relationships. The description fails to compensate for the complete lack of schema descriptions.

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

Purpose3/5

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

The description 'Manage AWS VPC networks' states a general purpose (verb+resource) but is vague about what management entails. It doesn't specify the CRUD operations available or distinguish this from sibling AWS tools like aws_ec2 or aws_cloudformation that might also manage network-related resources.

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 prerequisites, appropriate contexts, or exclusions. With many sibling AWS tools, there's no indication of when aws_vpc is the right choice versus other infrastructure management tools.

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