Home About Who We Are Team Services Startups Businesses Enterprise Case Studies Blog Guides Contact Connect with Us
Back to Guides
Software & Platforms 17 min read

How to Connect AWS to OpenClaw: Cloud Infrastructure AI Agent

How to Connect AWS to OpenClaw: Cloud Infrastructure AI Agent

Every guide about OpenClaw and AWS covers the same thing: how to host OpenClaw on EC2 or Lightsail. That is a deployment question, not an integration question. What most DevOps engineers want is the opposite direction: an AI agent that can query their AWS account, flag cost anomalies, check instance health, tail Lambda logs, and verify S3 backups, all from a chat message.

This guide covers that second use case. You will create an IAM user with least-privilege permissions, configure AWS credentials in OpenClaw, write a custom skill that wraps the AWS CLI, and build practical automations for the infrastructure tasks you repeat every week. If OpenClaw is already running, the whole setup takes about 30 minutes.


What This Integration Does

Once connected, your OpenClaw agent becomes a conversational interface to your AWS account. Instead of switching to the AWS Console or typing CLI commands in a terminal, you message your agent and it runs the queries for you.

Here is what the skill supports out of the box:

  • List and inspect EC2 instances by state, region, or tag
  • Check S3 bucket sizes, permissions, and recent uploads
  • Query CloudWatch metrics and alarms for any service
  • Invoke and tail Lambda function logs without opening the console
  • Pull Cost Explorer data to catch spend spikes early
  • Audit IAM policies and security groups for misconfigurations

The agent uses the AWS CLI under the hood. Every command runs on your machine (or VPS), authenticated with the IAM credentials you configure. No data passes through third-party middleware.


Before You Start

You need four things in place:

  1. OpenClaw installed and running. If you have not done this yet, follow our OpenClaw setup guide. That guide covers installation, workspace files, memory, and model configuration.

  2. An AWS account where you have permission to create IAM users and policies. If you are in an organization with strict access controls, you may need your admin to create the IAM user for you.

  3. The AWS CLI (v2) installed on the same machine running OpenClaw. The skill calls aws commands directly, so the CLI must be on the system path. Install it via aws.amazon.com/cli if you have not already.

  4. A text editor for writing the skill file. VS Code, Cursor, or any Markdown-capable editor works.

If you want your agent monitoring AWS 24/7 without keeping your laptop open, you will also need OpenClaw running on a VPS. Our Hostinger deployment guide covers that. You can also run OpenClaw directly on an EC2 instance, which simplifies credential management through IAM instance roles.


Step 1: Create an IAM User with Minimal Permissions

Do not give your OpenClaw agent your root credentials or an AdministratorAccess policy. Teams often do this during proof-of-concept setups, and it always creates problems later: an unintended terminate-instances call, a policy change that locks out other services, or an access key that leaks into a log file and gets exposed.

The right approach: a dedicated IAM user with read-only permissions by default, and narrow write permissions added only for specific operations you trust the agent to perform.

Create the IAM User

  1. Open the IAM Console
  2. Go to Users and click Create user
  3. Name it something clear: openclaw-agent
  4. Do not enable console access. This user only needs programmatic access.
  5. Click Next to proceed to permissions

Attach a Least-Privilege Policy

Instead of using AWS-managed policies (which tend to be overly broad), create a custom policy. Go to Policies > Create policy and paste this JSON:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "EC2ReadOnly",
      "Effect": "Allow",
      "Action": [
        "ec2:DescribeInstances",
        "ec2:DescribeSecurityGroups",
        "ec2:DescribeVolumes",
        "ec2:DescribeVpcs",
        "ec2:DescribeSubnets",
        "ec2:DescribeImages"
      ],
      "Resource": "*"
    },
    {
      "Sid": "S3ReadOnly",
      "Effect": "Allow",
      "Action": [
        "s3:ListAllMyBuckets",
        "s3:ListBucket",
        "s3:GetBucketLocation",
        "s3:GetBucketPolicy",
        "s3:GetBucketPublicAccessBlock",
        "s3:GetObject"
      ],
      "Resource": "*"
    },
    {
      "Sid": "CloudWatchReadOnly",
      "Effect": "Allow",
      "Action": [
        "cloudwatch:DescribeAlarms",
        "cloudwatch:GetMetricData",
        "cloudwatch:ListMetrics",
        "logs:DescribeLogGroups",
        "logs:GetLogEvents",
        "logs:FilterLogEvents"
      ],
      "Resource": "*"
    },
    {
      "Sid": "LambdaReadOnly",
      "Effect": "Allow",
      "Action": [
        "lambda:ListFunctions",
        "lambda:GetFunction",
        "lambda:GetFunctionConfiguration"
      ],
      "Resource": "*"
    },
    {
      "Sid": "CostExplorerReadOnly",
      "Effect": "Allow",
      "Action": [
        "ce:GetCostAndUsage",
        "ce:GetCostForecast"
      ],
      "Resource": "*"
    },
    {
      "Sid": "IAMAuditReadOnly",
      "Effect": "Allow",
      "Action": [
        "iam:ListUsers",
        "iam:ListRoles",
        "iam:ListPolicies",
        "iam:GetPolicy",
        "iam:GetPolicyVersion",
        "iam:ListAttachedUserPolicies",
        "iam:ListAttachedRolePolicies"
      ],
      "Resource": "*"
    },
    {
      "Sid": "STSIdentity",
      "Effect": "Allow",
      "Action": "sts:GetCallerIdentity",
      "Resource": "*"
    }
  ]
}

Name this policy OpenClawAgentReadOnly and attach it to your openclaw-agent user.

This policy covers the five core AWS services most teams want to query through chat: EC2, S3, CloudWatch, Lambda, and Cost Explorer. It also includes IAM read access for security auditing and STS for identity verification. Every action is read-only. The agent can look at everything but change nothing.

When you are ready to let the agent perform write operations (starting or stopping instances, invoking Lambda functions), add those permissions in a separate policy statement with explicit resource constraints. More on that in the security section below.

Generate Access Keys

  1. Go to your openclaw-agent user in the IAM Console
  2. Click the Security credentials tab
  3. Under Access keys, click Create access key
  4. Select Command Line Interface (CLI) as the use case
  5. Copy both the Access Key ID and Secret Access Key immediately. AWS only shows the secret once.

Step 2: Configure AWS Credentials in OpenClaw

Store Credentials Safely

Do not paste AWS credentials into your skill file or any workspace file your agent reads into context. Store them as environment variables:

# Add to ~/.env or your shell profile
export AWS_ACCESS_KEY_ID=AKIA...your-access-key
export AWS_SECRET_ACCESS_KEY=wJalrX...your-secret-key
export AWS_DEFAULT_REGION=us-east-1

If OpenClaw runs on a VPS, add these to the server’s environment. For systemd-managed deployments, put them in the service file’s Environment= directives.

Better option for EC2-hosted OpenClaw: If your OpenClaw instance runs on EC2, skip access keys entirely. Attach an IAM instance role with the same policy instead. The AWS CLI picks up the role credentials automatically through the Instance Metadata Service, and you never have to manage or rotate keys. This is the approach AWS recommends for production workloads.

Verify the Connection

Before writing the skill, confirm the AWS CLI can authenticate. SSH into your OpenClaw machine (or open a terminal locally) and run:

aws sts get-caller-identity

You should see output like:

{
  "UserId": "AIDA...",
  "Account": "123456789012",
  "Arn": "arn:aws:iam::123456789012:user/openclaw-agent"
}

If this fails, check that your environment variables are set and the access key is active in the IAM Console.


Step 3: Write the OpenClaw AWS Skill

OpenClaw skills are Markdown files that tell your agent what a tool does, when to use it, and how to execute operations. The skill file lives in your workspace’s skills/ directory.

Create the Skill Directory

mkdir -p ~/.openclaw/workspace/skills/aws-infra

Write the SKILL.md File

Create ~/.openclaw/workspace/skills/aws-infra/SKILL.md with this content:

---
name: aws-infra
description: Query, audit, and monitor AWS infrastructure using AWS CLI. Covers EC2, S3, CloudWatch, Lambda, Cost Explorer, and IAM.
tools:
  - shell
---

# AWS Infrastructure Skill

## Environment

AWS credentials and region are set via environment variables:
- AWS_ACCESS_KEY_ID
- AWS_SECRET_ACCESS_KEY
- AWS_DEFAULT_REGION

Verify identity before first use:
aws sts get-caller-identity

## Available Operations

### EC2 Instances

List all running instances with key details:

aws ec2 describe-instances \
  --filters "Name=instance-state-name,Values=running" \
  --query "Reservations[].Instances[].{ID:InstanceId,Type:InstanceType,State:State.Name,AZ:Placement.AvailabilityZone,Name:Tags[?Key=='Name']|[0].Value}" \
  --output table

Describe a specific instance:

aws ec2 describe-instances --instance-ids INSTANCE_ID

### S3 Buckets

List all buckets:

aws s3 ls

Check bucket size (approximate):

aws s3 ls s3://BUCKET_NAME --recursive --summarize | tail -2

Check public access settings:

aws s3api get-public-access-block --bucket BUCKET_NAME

### CloudWatch

List alarms in ALARM state:

aws cloudwatch describe-alarms --state-value ALARM \
  --query "MetricAlarms[].{Name:AlarmName,Metric:MetricName,State:StateValue}" \
  --output table

Get CPU utilization for an EC2 instance (last 1 hour):

aws cloudwatch get-metric-data --metric-data-queries '[
  {"Id":"cpu","MetricStat":{"Metric":{"Namespace":"AWS/EC2","MetricName":"CPUUtilization","Dimensions":[{"Name":"InstanceId","Value":"INSTANCE_ID"}]},"Period":300,"Stat":"Average"}}
]' --start-time $(date -u -d '1 hour ago' +%Y-%m-%dT%H:%M:%S) --end-time $(date -u +%Y-%m-%dT%H:%M:%S)

### Lambda Functions

List all functions:

aws lambda list-functions \
  --query "Functions[].{Name:FunctionName,Runtime:Runtime,Memory:MemorySize,LastModified:LastModified}" \
  --output table

Tail recent logs for a function:

aws logs filter-log-events \
  --log-group-name /aws/lambda/FUNCTION_NAME \
  --start-time $(date -u -d '30 minutes ago' +%s000) \
  --query "events[].message" --output text

### Cost Explorer

Get month-to-date spend:

aws ce get-cost-and-usage \
  --time-period Start=$(date +%Y-%m-01),End=$(date +%Y-%m-%d) \
  --granularity MONTHLY \
  --metrics BlendedCost \
  --group-by Type=DIMENSION,Key=SERVICE

Get cost forecast for rest of month:

aws ce get-cost-forecast \
  --time-period Start=$(date +%Y-%m-%d),End=$(date -d "$(date +%Y-%m-01) +1 month -1 day" +%Y-%m-%d) \
  --granularity MONTHLY --metric BLENDED_COST

### IAM Audit

List all users:

aws iam list-users --query "Users[].{Name:UserName,Created:CreateDate}" --output table

Check policies attached to a user:

aws iam list-attached-user-policies --user-name USER_NAME

## Rules

- Default to read-only operations. Never run destructive commands (terminate, delete, remove) unless the user explicitly confirms.
- Before any write operation, show what will change and ask for confirmation.
- When querying costs, always show both the current period and the forecast.
- For security audits, flag anything publicly accessible (S3 buckets, security groups with 0.0.0.0/0).
- Never log or display the AWS access key or secret key in responses.
- If a command fails with AccessDenied, explain which IAM permission is missing.
- Use --output table for human-readable results and --output json when piping data.

What Each Section Does

The frontmatter (name, description, tools) tells OpenClaw when to activate this skill and what system tools it needs. The shell tool lets the agent run aws CLI commands.

The operations section gives your agent templated CLI commands it can adapt. When you ask “what EC2 instances are running?”, the agent reads the describe-instances pattern, executes it, and parses the output. The templates use --query and --output table so the results are already formatted for a chat response.

The rules section is your guardrail layer. The read-only default is critical. Without it, a loosely-phrased instruction like “clean up that old instance” could trigger a terminate command. A confirmation rule like this catches accidental deletion requests before they execute.


Step 4: Test the Connection

Restart OpenClaw so it picks up the new skill:

openclaw gateway restart

Open your chat with your OpenClaw agent (Telegram, Slack, or whichever channel you use) and try these queries in order:

Identity test:

“What AWS account am I connected to?”

The agent should run aws sts get-caller-identity and return your account ID and IAM user ARN.

EC2 test:

“List all running EC2 instances”

The agent should return a table of instance IDs, types, availability zones, and Name tags.

Cost test:

“What is my AWS spend so far this month?”

The agent should run the Cost Explorer query and return a breakdown by service.

If any test fails, here are the common causes:

SymptomLikely CauseFix
”command not found: aws”AWS CLI not installedInstall via aws.amazon.com/cli
AccessDeniedExceptionMissing IAM permissionAdd the required action to your policy
ExpiredTokenExceptionKeys rotated or deactivatedGenerate new access keys in IAM Console
Empty resultsWrong region configuredSet AWS_DEFAULT_REGION to your primary region
Agent does not use skillSkill not loadedRun openclaw gateway restart, check skill directory path

What to Automate First

The connection works. Your agent can query AWS. Now the question is what to build on top of it.

The recommended pattern is the same progression as every other integration: read first, monitor second, automate third. Jumping straight to write operations with cloud infrastructure is riskier than with a CRM. A bad HubSpot update creates a duplicate contact. A bad EC2 command can take down a production server.

Week 1: Read-Only Queries

Use your agent as a faster interface to the AWS Console. Instead of clicking through the UI, ask:

  • “How many EC2 instances are running in us-east-1?”
  • “Which S3 buckets have public access enabled?”
  • “Show me all CloudWatch alarms in ALARM state”
  • “What Lambda functions have not been invoked in the last 30 days?”
  • “What is our projected AWS spend for this month?”

This builds fluency with the skill and lets you verify that the agent’s output matches what you see in the Console. Two or three days of this and you will start trusting the results.

Week 2: Monitoring and Alerts

Add scheduled queries to your OpenClaw heartbeat configuration or cron jobs:

## AWS Morning Brief (weekdays at 8:00 AM)

1. Check CloudWatch for any alarms in ALARM state
2. Pull month-to-date AWS spend and compare to last month
3. List any EC2 instances that have been running for more than 30 days
   without a Name tag (likely forgotten test instances)
4. Check S3 buckets for any with public read access

Send me a summary with anything that needs attention.
If everything looks healthy, send "AWS: all clear" and the current month spend.

This is where the integration starts saving real time. A DevOps engineer checking these manually might spend 15-20 minutes per morning navigating the Console. The agent does it in seconds.

For cost monitoring specifically, add a threshold alert:

## Cost Spike Alert (runs every 6 hours)

Pull the last 24 hours of AWS spend by service.
If any single service exceeds $50 in 24 hours, or total spend
exceeds $200 in 24 hours, send me an alert immediately with:
- Which service spiked
- Current 24h spend vs 7-day average
- The top 3 cost drivers

Week 3: Operational Automation

Once you trust the agent’s read operations and monitoring, add selective write permissions. Update your IAM policy with a new statement for the operations you want to enable:

{
  "Sid": "EC2LimitedWrite",
  "Effect": "Allow",
  "Action": [
    "ec2:StartInstances",
    "ec2:StopInstances"
  ],
  "Resource": "arn:aws:iam::123456789012:instance/*",
  "Condition": {
    "StringEquals": {
      "ec2:ResourceTag/ManagedBy": "openclaw"
    }
  }
}

This lets the agent start and stop instances, but only those tagged with ManagedBy: openclaw. It cannot touch anything else. Tag-based restrictions are the safest way to give an AI agent write access to AWS resources.

With write permissions in place, you can build operational workflows:

  • “Stop all dev instances tagged ManagedBy:openclaw at 7 PM and start them at 8 AM”
  • “If the staging server’s CPU exceeds 90% for 10 minutes, send me the CloudWatch graph and ask if I want to restart it”
  • “Invoke the backup-verification Lambda function and tell me if all S3 backups completed in the last 24 hours”

Security Guardrails for AI-Driven Cloud Access

Giving an AI agent access to your AWS account requires a different security posture than giving a human access. Humans have judgment. Agents have instructions. When the instructions are ambiguous, the agent will guess, and guessing with cloud infrastructure has real consequences.

Start read-only, expand deliberately. The policy we provided above is entirely read-only. Keep it that way until you have specific write operations you want to enable. When you do add write permissions, scope them to specific resources or tags, never "Resource": "*" for write actions.

Never use access keys in skill files. Store them as environment variables. If your OpenClaw instance runs on EC2, use IAM instance roles instead of keys entirely. Access keys in files have a way of ending up in logs, version control, or agent memory.

Require confirmation for write operations. The Rules section in the skill file tells the agent to always ask before modifying anything. Test this. Send a message like “stop the production server” and verify the agent asks for confirmation rather than executing immediately.

Rotate keys on a schedule. AWS access keys do not expire unless you set them to. Create a quarterly rotation reminder. In your OpenClaw heartbeat configuration, add a reminder to rotate the openclaw-agent access key every 90 days.

Audit with CloudTrail. Every AWS CLI call the agent makes is logged in CloudTrail. Review the trail periodically to verify the agent is making the calls you expect and nothing else. Filter by the openclaw-agent IAM user to isolate its activity.


Frequently Asked Questions

Does OpenClaw need to run on AWS for this to work?

No. OpenClaw can run anywhere: your laptop, a Hostinger VPS, a DigitalOcean droplet, or an EC2 instance. The AWS CLI authenticates via access keys or IAM roles regardless of where the machine is located. Running on EC2 does simplify credential management through instance roles, but it is not required.

Can I connect multiple AWS accounts to one OpenClaw agent?

Yes. The AWS CLI supports named profiles. Configure each account in ~/.aws/credentials with a profile name, then reference the profile in your skill commands using --profile account-name. You could have one profile for production and another for staging, with different IAM permissions on each.

What happens if I give the agent too many permissions?

Nothing bad happens until the agent does something you did not intend. The risk scales with permission breadth. Read-only access has zero blast radius, because the worst outcome is the agent reads something you did not ask about. Write access without resource constraints is where problems start. Tag-based conditions and resource ARN restrictions are your best defense.

How much does the AWS API usage cost?

Most AWS API calls are free. EC2 Describe calls, S3 List calls, CloudWatch GetMetricData, and IAM List operations have no charge. Cost Explorer API calls cost $0.01 per request, which means even aggressive monitoring (every 6 hours) costs pennies per month. The significant cost is the LLM token usage for processing the responses, not the AWS API calls themselves.

Can OpenClaw manage Terraform or CloudFormation instead of raw CLI?

OpenClaw can run any CLI tool available on the host machine. If you have Terraform or the AWS CDK installed, you can write a skill that wraps those commands instead. For infrastructure-as-code workflows, a Terraform skill that runs terraform plan (but requires confirmation before terraform apply) is a natural extension of this pattern.

What models work best for parsing AWS CLI output?

GPT-5.4 and Claude Opus 4.6 both handle structured CLI output well. The key factor is context window size: some AWS commands (especially CloudWatch log queries) return large payloads. If you are running a smaller model, add a note to your skill’s Rules section telling the agent to use --max-items or --query to limit response size. For routine infrastructure queries, even Claude Sonnet 4.6 performs reliably.


Key Takeaways

  • Connect AWS to OpenClaw by creating a dedicated IAM user with a read-only custom policy, configuring AWS CLI credentials as environment variables, and writing a SKILL.md file with templated CLI commands
  • Start with read-only permissions covering EC2, S3, CloudWatch, Lambda, and Cost Explorer, then add scoped write permissions only for specific operations you trust
  • Use tag-based IAM conditions (ec2:ResourceTag/ManagedBy: openclaw) to restrict which resources the agent can modify
  • Automate daily infrastructure checks and cost monitoring through OpenClaw’s heartbeat, replacing manual Console clicks with scheduled agent queries
  • Store AWS credentials in environment variables or use IAM instance roles, never inside skill files or workspace documents

Last Updated: Apr 2, 2026

SL

SFAI Labs

SFAI Labs helps companies build AI-powered products that work. We focus on practical solutions, not hype.

Need Help Setting Up OpenClaw?

  • VPS deployment, SSL, and security hardening done for you
  • Integration configuration — connect your tools on day one
  • Custom skill development for your specific workflows
Get OpenClaw Setup Help →
No commitment · Free consultation

Related articles