aws_elb
Manage AWS Elastic Load Balancers by listing, creating, or deleting them to distribute application traffic across multiple targets.
Instructions
Manage AWS Elastic Load Balancers
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| action | Yes | ||
| region | Yes | ||
| name | No | ||
| lbType | No | application | |
| scheme | No | ||
| subnets | No | ||
| securityGroups | No | ||
| listeners | No | ||
| healthCheck | No | ||
| tags | No | ||
| targetGroups | No |
Implementation Reference
- Main handler function for the 'aws_elb' tool. Generates and executes an Ansible playbook to manage AWS Elastic Load Balancers (list, create, delete) based on the provided action and parameters.export async function elbOperations(args: ELBOptions): Promise<string> { await verifyAwsCredentials(); const { action, region, name, lbType = 'application', scheme, subnets, securityGroups, listeners, healthCheck, tags, targetGroups } = args; // Determine module based on lbType let moduleName: string; let infoModuleName: string; switch (lbType) { case 'application': moduleName = 'amazon.aws.elb_application_lb'; infoModuleName = 'amazon.aws.elb_application_lb_info'; break; case 'network': moduleName = 'amazon.aws.elb_network_lb'; infoModuleName = 'amazon.aws.elb_network_lb_info'; break; case 'classic': moduleName = 'amazon.aws.elb_classic_lb'; infoModuleName = 'amazon.aws.elb_classic_lb_info'; break; default: throw new AnsibleError(`Unsupported ELB type: ${lbType}`); } let playbookContent = `--- - name: AWS ELB ${action} operation (${lbType}) hosts: localhost connection: local gather_facts: no tasks:`; switch (action) { case 'list': playbookContent += ` - name: List ${lbType} load balancers ${infoModuleName}: region: "${region}" register: elb_info - name: Display load balancers debug: var: elb_info`; // Adjust var based on actual module output if needed break; case 'create': playbookContent += ` - name: Create ${lbType} load balancer ${moduleName}: region: "${region}" name: "${name}" state: present ${formatYamlParams({ scheme, subnets, security_groups: securityGroups, listeners, // May need adjustment for different LB types health_check: healthCheck, // May need adjustment tags, target_groups: targetGroups // For Application/Network LBs })} register: elb_result - name: Display load balancer details debug: var: elb_result`; break; case 'delete': playbookContent += ` - name: Delete ${lbType} load balancer ${moduleName}: region: "${region}" name: "${name}" state: absent register: elb_delete - name: Display deletion result debug: var: elb_delete`; break; default: throw new AnsibleError(`Unsupported ELB action: ${action}`); } // Execute the generated playbook return executeAwsPlaybook(`elb-${action}`, playbookContent); }
- Zod schema definition for input validation of the 'aws_elb' tool, including actions (list, create, delete), region, load balancer name, type, and configuration parameters.export const ELBSchema = z.object({ action: ELBActionEnum, region: z.string().min(1, 'AWS region is required'), name: z.string().optional(), lbType: z.enum(['classic', 'application', 'network']).optional().default('application'), scheme: z.string().optional(), subnets: z.array(z.string()).optional(), securityGroups: z.array(z.string()).optional(), listeners: z.array(z.any()).optional(), // Consider defining a more specific listener schema healthCheck: z.any().optional(), // Consider defining a more specific health check schema tags: z.record(z.string()).optional(), targetGroups: z.array(z.any()).optional() // Added based on usage in aws.ts. Consider a specific schema. }); export type ELBOptions = z.infer<typeof ELBSchema>;
- src/sysoperator/index.ts:126-130 (registration)Registration of the 'aws_elb' tool in the toolDefinitions map, linking its description, input schema, and handler function.aws_elb: { description: 'Manage AWS Elastic Load Balancers', schema: aws.ELBSchema, handler: aws.elbOperations, },
- Shared helper function used by the aws_elb handler (and other AWS handlers) to execute dynamically generated Ansible playbooks for AWS operations, 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); } } }
- Utility helper to format AWS parameters as YAML strings for insertion into generated Ansible playbooks, used by the aws_elb 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'); };