Connect Amazon Web Services to AI Agents: Track Logs and Compliance
Give your AI agent Amazon Web Services tools.
The guide
Learn how to connect Amazon Web Services to ai agents using Truto. Step-by-step guide to tool calling, API quirks, and autonomous workflows.
You want to connect Amazon Web Services (AWS) to an AI agent so your system can autonomously audit IAM policies, track compliance violations, parse CloudTrail logs, and isolate misconfigured security groups. Here is exactly how to do it using Truto's /tools endpoint and SDK, bypassing the need to build and maintain a custom, multi-region AWS integration from scratch.
Giving a Large Language Model (LLM) read and write access to your AWS infrastructure is a high-stakes engineering challenge. You either spend months building, hosting, and maintaining a custom connector that correctly handles AWS's fractured API protocols, or you use a managed infrastructure layer that normalizes the boilerplate for you. If your team uses ChatGPT, check out our guide on connecting Amazon Web Services to ChatGPT, or if you are building on Anthropic's models, read our guide on connecting Amazon Web Services to Claude. For developers building custom autonomous workflows, you need a programmatic way to fetch these tools and bind them to your agent framework.
This guide breaks down exactly how to fetch AI-ready tools for AWS, bind them natively to an LLM using frameworks like LangChain, LangGraph, CrewAI, or the Vercel AI SDK, and execute complex cloud infrastructure workflows. For a broader look at this design pattern, read our research on architecting AI agents and the SaaS integration bottleneck.
The Engineering Reality of the AWS API
Giving an LLM access to external data sounds simple during local prototyping. You write a Node.js function that makes a fetch request using the AWS SDK and wrap it in a tool decorator. In production against a sprawling enterprise AWS environment, this approach collapses.
Amazon Web Services does not have a single API. It is a collection of hundreds of independent service APIs built over two decades, each with different design philosophies, pagination schemes, and error formats. If you hardcode these interactions into your agent, you will spend your sprints writing defensive integration code instead of improving your model's reasoning.
The XML vs JSON Protocol Split
Standard LLMs are trained to expect flat, intuitive JSON objects. When an agent calls an API, it expects a clean JSON response. However, large portions of AWS - specifically foundational services like EC2, SQS, and CloudWatch - rely on legacy XML Query APIs.
When you request EC2 instances or Load Balancers directly, the response arrives as deeply nested XML. Even if you run a generic XML-to-JSON parser, every scalar leaf comes back wrapped as {_text: value}, and lists containing exactly one item collapse into bare objects instead of arrays. An LLM attempting to parse this raw structure will hallucinate array indices or fail to find the correct _text property. A unified tool layer normalizes these responses into standard JSON before the LLM ever sees them.
The Regional Fanning Trap
AWS resources are overwhelmingly scoped by region. An agent tasked with finding a specific GuardDuty finding or exposed EC2 instance cannot simply call a global endpoint. It must fan out requests across us-east-1, eu-west-1, ap-southeast-2, and potentially dozens of other regions.
Worse, a lack of resources in a region does not always return an empty list. In many AWS security services, querying a region where the service is not explicitly enabled returns an HTTP 403 or 404 (e.g., InvalidAccessException in Security Hub). If you feed raw AWS errors to an agent, it will interpret a 404 as a critical failure and abort the workflow, rather than understanding that a 404 simply means "Security Hub is not enabled here" - which is normal data, not an integration failure.
Strict Rate Limits and the Backoff Burden
AWS enforces hard, unyielding rate limits on administrative endpoints. The Organizations API, for example, throttles at just 1 request per second for certain calls.
When integrating these APIs, you must handle rate limits explicitly. Truto does not retry, throttle, or apply backoff on rate limit errors. When an upstream AWS API returns an HTTP 429, Truto passes that exact error down to your caller. However, Truto normalizes the upstream rate limit information into standardized headers (ratelimit-limit, ratelimit-remaining, ratelimit-reset) per the IETF specification. Your agent framework or calling code is entirely responsible for reading the ratelimit-reset header, sleeping, and retrying. We will show you exactly how to implement this in the workflow section.
Architecting the Agent Context
A unified tool layer collapses the complexity of the AWS API into a stable schema. Your agent sees deterministic tool names like list_all_amazon_web_services_s_3_buckets instead of juggling raw s3:ListAllMyBuckets operations, XML parsing, and region selection.
sequenceDiagram
participant Agent as "AI Agent (LangChain)"
participant Truto as "Truto Tool Manager"
participant AWS as "AWS API (Upstream)"
Agent->>Truto: Call list_all_amazon_web_services_s_3_buckets
Truto->>AWS: Execute s3:ListAllMyBuckets (Region-sharded)
AWS-->>Truto: Raw XML or JSON response
Truto-->>Agent: Normalized JSON array
Note over Agent,Truto: Agent receives flat JSON, no XML or region-fanning required.Hero Tools for AWS Compliance
Instead of exposing hundreds of raw AWS endpoints, Truto provides highly curated, normalized tools designed specifically for autonomous agents. Here are six high-leverage tools for building AWS security and compliance workflows.
1. IAM Account Authorization Details
Tool name: list_all_amazon_web_services_iam_account_authorization_details
This is the primary IAM collector. One paginated sweep returns every user, group, role, and policy with attached managed policies, inline policy documents, and permissions boundaries. It replaces four to eight per-user API calls that would otherwise exhaust rate limits. Note that IAM policy documents are returned URL-encoded; your agent will receive the normalized data.
"Fetch all IAM roles in the AWS account. Filter the list to find any role that has an inline policy granting
sts:AssumeRolewithout an external ID condition, and return their ARNs."
2. Security Hub Findings
Tool name: list_all_amazon_web_services_securityhub_findings
Lists ASFF (AWS Security Finding Format) findings via AWS Security Hub. This tool handles the pagination limits of AWS (MaxResults capped at 100) and correctly maps the compliance status. Crucially, a 404 response here simply means Security Hub is not enabled for the account/region, preventing the agent from crashing on a normal state.
"Retrieve all Security Hub findings for the current account. Group them by severity and list the titles of any findings categorized as FAILED and CRITICAL. Ignore archived findings."
3. S3 Bucket Public Access Block
Tool name: list_all_amazon_web_services_s_3_bucket_public_access_block
Retrieves the bucket-level Block Public Access (BPA) configuration. A 404 NoSuchPublicAccessBlockConfiguration means BPA is not configured (all four flags false). The tool normalizes this so your agent can accurately determine if a bucket is vulnerable, distinguishing between 'not configured' and 'access denied'.
"Check the Public Access Block configuration for the bucket named 'prod-customer-data-backups'. Tell me if
RestrictPublicBucketsorIgnorePublicAclsare set to false."
4. CloudTrail Trails Inventory
Tool name: list_all_amazon_web_services_cloudtrail_trails
Lists CloudTrail trails visible in the account and region. It automatically handles the multi-region deduplication required when querying shadow trails. An absent KMS Key ID is correctly interpreted as SSE-S3 encryption, not a lack of encryption entirely.
"Inventory all CloudTrail trails in the account. Tell me which trails are multi-region and verify if they are currently using a KMS key for log file encryption."
5. EC2 Security Groups
Tool name: list_all_amazon_web_services_ec_2_security_groups
Lists security groups in the given region, returning stateful, allow-only rules. It normalizes the complex ipPermissions nested objects. The tool translates protocol "-1" to mean all protocols and all ports, ensuring the LLM correctly interprets wide-open access rules.
"List all EC2 security groups in us-east-1. Identify any security group that has an ingress rule allowing protocol '-1' or TCP port 22 open to the CIDR block 0.0.0.0/0."
6. Organizations Accounts
Tool name: list_all_amazon_web_services_organizations_accounts
Retrieves every account in the AWS organization in one global sweep, avoiding the need to fan out per region. It maps the state from Account.State correctly and loops until the NextToken is null, ensuring your agent gets a complete infrastructure map.
"Sweep the AWS Organization and list all member accounts. Flag any account where the state is not ACTIVE, and tell me the join date for each."
For the complete inventory of available AWS tools, schema definitions, and parameter structures, visit the Amazon Web Services integration page.
Building Multi-Step Workflows
To give your AI agent access to these tools, you need to bind them to your LLM framework. This example demonstrates how to fetch Truto's proxy tools, bind them to a LangChain agent, and explicitly handle the AWS rate limits that Truto passes through.
Remember, Truto does not absorb or retry HTTP 429s. If you hammer the AWS Organizations or IAM APIs, AWS will throttle the request, Truto will return a 429, and your code must back off using the ratelimit-reset header.
import { ChatOpenAI } from "@langchain/openai";
import { AgentExecutor, createToolCallingAgent } from "langchain/agents";
import { ChatPromptTemplate } from "@langchain/core/prompts";
import { TrutoToolManager } from "truto-langchainjs-toolset";
async function runAWSComplianceAudit() {
const llm = new ChatOpenAI({ modelName: "gpt-4o", temperature: 0 });
// Initialize Truto Tool Manager with your tenant and integrated account ID
const truto = new TrutoToolManager({
apiKey: process.env.TRUTO_API_KEY,
accountId: "aws_integrated_account_123"
});
// Fetch AWS tools dynamically
const tools = await truto.getTools();
const prompt = ChatPromptTemplate.fromMessages([
["system", "You are a senior AWS cloud security engineer. Your job is to audit AWS resources."],
["human", "{input}"],
["placeholder", "{agent_scratchpad}"],
]);
const agent = createToolCallingAgent({ llm, tools, prompt });
const executor = new AgentExecutor({ agent, tools, maxIterations: 10 });
// Custom wrapper to handle Truto's transparent 429 rate limits
const executeWithBackoff = async (input: string, retries = 3) => {
try {
const result = await executor.invoke({ input });
console.log(result.output);
} catch (error: any) {
if (error.status === 429 && retries > 0) {
// Truto passes upstream limits via standard IETF headers
const resetSeconds = parseInt(error.headers['ratelimit-reset'] || "5", 10);
console.warn(`[AWS Rate Limit Hit] Sleeping for ${resetSeconds} seconds...`);
await new Promise(res => setTimeout(res, resetSeconds * 1000));
await executeWithBackoff(input, retries - 1);
} else {
console.error("Workflow failed:", error);
}
}
};
await executeWithBackoff(
"List all EC2 security groups. Then, find any groups allowing 0.0.0.0/0 on port 22 and report their Group IDs."
);
}
runAWSComplianceAudit();Workflows in Action
Once the agent is bound to the Truto tool layer, it can execute multi-step cloud engineering tasks autonomously. Here are two real-world examples of how security teams use these capabilities.
Use Case 1: Public S3 Bucket Exposure Triage
When a security alert flags a potential data leak, the agent can immediately verify the exposure without requiring a human to log into the AWS Console.
"Audit the S3 bucket named 'legacy-customer-exports'. Check its Public Access Block configuration, its bucket policy, and its ACLs. Tell me definitively if the bucket allows unauthenticated public read access."
How the agent executes this:
- Tool Call:
list_all_amazon_web_services_s_3_bucket_public_access_blockpassing the bucket name. The agent checks ifRestrictPublicBucketsandIgnorePublicAclsare active at the bucket level. - Tool Call:
list_all_amazon_web_services_s_3_bucket_policy_statusto evaluate if the bucket policy is overtly public. - Tool Call:
list_all_amazon_web_services_s_3_bucket_aclto check forAllUsersorAuthenticatedUsersgrants in the ACL. - Synthesis: The agent combines the three signals. If BPA is off, but the policy and ACLs are private, it reports the bucket is safe but misconfigured. If the policy is public and BPA is off, it escalates the alert as a verified exposure.
Use Case 2: Cross-Referencing IAM Keys with CloudTrail
Security teams frequently need to determine if a stale IAM access key is actually dormant, or if it is actively being used by a hidden service.
"List all IAM users in the account. Find any user whose access keys have not been rotated in the last 90 days. For those users, check their
LastUseddate, and if they were used in the last 7 days, cross-reference CloudTrail to see what actions they took."
How the agent executes this:
- Tool Call:
list_all_amazon_web_services_iam_usersto get the baseline roster of users. - Tool Call:
list_all_amazon_web_services_iam_access_keysfor each user to retrieve key metadata. - Tool Call:
get_single_amazon_web_services_iam_access_key_last_used_by_idto determine exactly when the key was last fired against the AWS API. - Tool Call:
list_all_amazon_web_services_cloudtrail_trails(and subsequent event queries) to look up the exact API operations performed by the flaggedAccessKeyIdover the last 7 days. - Synthesis: The agent outputs a report isolating the exact long-lived keys that are actively being used, allowing engineers to rotate them safely without breaking production services.
If you want your AI agents to perform complex, multi-step cloud engineering tasks, you cannot afford to have them wrestling with XML parsing, pagination cursors, and regional endpoint routing. By placing Truto's unified tool layer between your agent and the AWS API, you eliminate the integration boilerplate. Your LLM gets a clean, predictable set of REST JSON tools, your framework handles the explicit rate limit backoffs, and your engineering team gets back to focusing on the intelligence of the agent itself.