Skip to main content
Glama

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

NameRequiredDescriptionDefault
actionYes
cidrBlockNo
dnsHostnamesNo
dnsSupportNo
nameNo
regionYes
subnetsNo
tagsNo
vpcIdNo

Input Schema (JSON Schema)

{ "$schema": "http://json-schema.org/draft-07/schema#", "additionalProperties": false, "properties": { "action": { "enum": [ "list", "create", "delete" ], "type": "string" }, "cidrBlock": { "type": "string" }, "dnsHostnames": { "type": "boolean" }, "dnsSupport": { "type": "boolean" }, "name": { "type": "string" }, "region": { "minLength": 1, "type": "string" }, "subnets": { "items": { "additionalProperties": false, "properties": { "az": { "type": "string" }, "cidr": { "type": "string" }, "tags": { "additionalProperties": { "type": "string" }, "type": "object" } }, "required": [ "cidr" ], "type": "object" }, "type": "array" }, "tags": { "additionalProperties": { "type": "string" }, "type": "object" }, "vpcId": { "type": "string" } }, "required": [ "action", "region" ], "type": "object" }

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'); };

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