Skip to main content
Glama

aws_iam

Manage AWS IAM roles and policies to control access permissions for cloud resources, enabling administrators to create, list, and delete security configurations.

Instructions

Manage AWS IAM roles and policies

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
actionYes
regionYes
nameNo
roleNameNo
policyNameNo
policyDocumentNo
assumeRolePolicyDocumentNo
pathNo
managedPoliciesNo

Implementation Reference

  • The primary handler function for the 'aws_iam' tool. It destructures input args, prepares temporary policy files if needed, dynamically generates an Ansible playbook YAML based on the specified IAM action (list_roles, list_policies, create_role, etc.), and executes it using the shared executeAwsPlaybook helper.
    export async function iamOperations(args: IAMOptions): Promise<string> {
      await verifyAwsCredentials();
    
      const { action, region, policyName, policyDocument, path, roleName, assumeRolePolicyDocument, managedPolicies } = args;
    
      const tempFiles: { filename: string, content: string }[] = [];
      let policyDocParam = '';
      let assumeRoleDocParam = '';
    
      if (policyDocument) {
        const policyFilename = 'policy.json';
        tempFiles.push({ filename: policyFilename, content: JSON.stringify(policyDocument, null, 2) });
        policyDocParam = `policy_document: "{{ lookup('file', '${policyFilename}') }}"`;
      }
    
      if (assumeRolePolicyDocument) {
        const assumeRoleFilename = 'assume_role_policy.json';
        tempFiles.push({ filename: assumeRoleFilename, content: JSON.stringify(assumeRolePolicyDocument, null, 2) });
        assumeRoleDocParam = `assume_role_policy_document: "{{ lookup('file', '${assumeRoleFilename}') }}"`;
      }
    
      let playbookContent = `---
    - name: AWS IAM ${action} operation
      hosts: localhost
      connection: local
      gather_facts: no
      tasks:`;
      
      switch (action) {
        case 'list_roles':
          playbookContent += `
        - name: List IAM roles
          amazon.aws.iam_role_info:
            region: "${region}"
          register: iam_roles
        
        - name: Display roles
          debug:
            var: iam_roles.iam_roles`;
          break;
          
        case 'list_policies':
          playbookContent += `
        - name: List IAM policies
          amazon.aws.iam_policy_info:
            region: "${region}"
          register: iam_policies
        
        - name: Display policies
          debug:
            var: iam_policies.policies`;
          break;
          
        case 'create_role':
          playbookContent += `
        - name: Create IAM role
          amazon.aws.iam_role:
            region: "${region}"
            name: "${roleName}"
            ${assumeRoleDocParam}
            state: present
    ${formatYamlParams({
      path,
      managed_policies: managedPolicies
    })}
          register: iam_result
        
        - name: Display role details
          debug:
            var: iam_result`;
          break;
          
        case 'create_policy':
          playbookContent += `
        - name: Create IAM policy
          amazon.aws.iam_policy:
            region: "${region}"
            policy_name: "${policyName}"
            ${policyDocParam}
            state: present
    ${formatYamlParams({ path })}
          register: iam_result
        
        - name: Display policy details
          debug:
            var: iam_result`;
          break;
          
        case 'delete_role':
          playbookContent += `
        - name: Delete IAM role
          amazon.aws.iam_role:
            region: "${region}"
            name: "${roleName}"
            state: absent
          register: iam_role_delete
        
        - name: Display deletion result
          debug:
            var: iam_role_delete`;
          break;
          
        case 'delete_policy':
          playbookContent += `
        - name: Delete IAM policy
          amazon.aws.iam_policy:
            region: "${region}"
            policy_name: "${policyName}"
            state: absent
          register: iam_policy_delete
        
        - name: Display deletion result
          debug:
            var: iam_policy_delete`;
          break;
          
        default:
          throw new AnsibleError(`Unsupported IAM action: ${action}`);
      }
      
      // Execute the generated playbook, passing policy docs if needed
      return executeAwsPlaybook(`iam-${action}`, playbookContent, '', tempFiles);
    }
  • Zod schema IAMSchema defining the input validation for the aws_iam tool, including required region and action from IAMActionEnum, and optional fields for IAM operations.
    export const IAMSchema = z.object({
      action: IAMActionEnum,
      region: z.string().min(1, 'AWS region is required'),
      name: z.string().optional(),
      roleName: z.string().optional(),
      policyName: z.string().optional(),
      policyDocument: z.any().optional(),
      assumeRolePolicyDocument: z.any().optional(),
      path: z.string().optional(),
      managedPolicies: z.array(z.string()).optional()
    });
  • Tool registration in the toolDefinitions object, specifying name 'aws_iam', its description, input schema (aws.IAMSchema), and handler function (aws.iamOperations).
    aws_iam: {
      description: 'Manage AWS IAM roles and policies',
      schema: aws.IAMSchema,
      handler: aws.iamOperations,
    },
  • Zod enum defining possible actions for the aws_iam tool, used in IAMSchema.
    export const IAMActionEnum = z.enum(['list_roles', 'list_policies', 'create_role', 'create_policy', 'delete_role', 'delete_policy']);
    export type IAMAction = z.infer<typeof IAMActionEnum>;
  • Shared helper function used by iamOperations (and other AWS handlers) to create temp dir, write playbook and extra files, execute ansible-playbook, 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);
        }
      }
    }
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. 'Manage' implies both read and write operations, but it doesn't specify permissions required, rate limits, side effects, or what 'manage' entails beyond the action enum. For a tool with multiple parameters and no annotation coverage, this is insufficient transparency.

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 a single, efficient sentence with no wasted words. It's appropriately sized and front-loaded, directly stating the tool's purpose without unnecessary elaboration, making it easy to parse quickly.

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 (9 parameters, multiple actions, no output schema, and no annotations), the description is incomplete. It doesn't cover parameter meanings, behavioral details, or output expectations, leaving significant gaps for the agent to understand how to use the tool effectively in 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%, meaning none of the 9 parameters are documented in the schema. The description only mentions 'roles and policies,' which loosely relates to some parameters (e.g., name, roleName, policyName) but doesn't explain their semantics, required formats, or how they interact with the action parameter. It fails to compensate for the lack of schema documentation.

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 'Manage AWS IAM roles and policies' clearly states the verb ('manage') and resources ('AWS IAM roles and policies'), making the purpose understandable. However, it doesn't specifically differentiate this tool from its AWS sibling tools (like aws_ec2 or aws_s3), which would require more specificity to achieve a perfect score.

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?

The description provides no guidance on when to use this tool versus alternatives. It doesn't mention any specific contexts, prerequisites, or exclusions, nor does it reference sibling tools like aws_cloudformation or terraform that might overlap in managing AWS resources. This leaves the agent without clear usage direction.

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