Practical AWS SDK for JavaScript Examples

25 working Node.js and TypeScript scripts for everyday AWS jobs: find where your money goes, clean up idle resources, work with S3, check IAM and security groups, and troubleshoot EC2, Route 53 and CloudFront. Each guide explains the code, shows the expected output, lists the caveats and includes the IAM policy the script needs.

154 examples

All practical AWS examples

Cost optimization 53

Get AWS billing details by service for last month

Query Cost Explorer for last month’s unblended cost, grouped by service.

SDK v3Cost Explorer
Find your most expensive AWS service

Pull a monthly cost and usage report grouped by service to see where spend goes.

SDK v3Cost Explorer
Get this month’s CloudWatch cost

Total the month-to-date unblended cost of CloudWatch alone.

SDK v3Cost Explorer
Detect and stop underutilized EC2 instances

Check 24 hours of CPU utilization for running instances and stop those under 20%.

SDK v3EC2CloudWatchChanges resources
Find and tag unattached EBS volumes

List volumes with no attachments and tag them for review, without deleting anything.

SDK v3EBS
Release unassociated Elastic IP addresses

Find Elastic IPs that aren’t attached to an instance and release them.

SDK v3EC2Changes resources
Clean up AMIs and snapshots older than 30 days

Deregister private AMIs older than 30 days and delete their snapshots.

SDK v3EC2Changes resources
Find overprovisioned DynamoDB capacity

Compare a table’s provisioned read and write capacity with last month’s consumption.

SDK v3DynamoDBCloudWatch
Find EC2 Reserved Instances about to expire

List active Reserved Instances ending in the next 30 days, before on-demand rates kick in.

SDK v3EC2
Set retention on CloudWatch log groups that never expire

Find log groups kept forever, ranked by stored GB, and set a retention period on them.

SDK v3CloudWatch Logs
Find idle NAT gateways

Report NAT gateways with no routes or no traffic in 14 days, and what each one costs.

SDK v3VPCCloudWatch
Find unused load balancers

Flag ALBs and NLBs with no targets, no healthy targets or no traffic, with their hourly cost.

SDK v3ELB
Find and delete old RDS manual snapshots

List manual RDS and Aurora snapshots past an age limit; delete only with --delete --apply.

SDK v3RDS
Find idle RDS instances

Flag RDS instances with zero DatabaseConnections in 14 days and estimate their monthly cost.

SDK v3RDSCloudWatch
Delete old ECR images with a lifecycle policy

Find ECR repos without a lifecycle policy, estimate the savings and set one with --apply.

SDK v3ECR
Find CloudWatch alarms stuck in INSUFFICIENT_DATA

Find alarms stuck in INSUFFICIENT_DATA on deleted metrics; delete them with --apply.

SDK v3CloudWatch
Find unattached network interfaces

List ENIs with status available, skip service-managed ones, delete yours with --apply.

SDK v3EC2VPC
Find unused VPC interface endpoints

Find interface VPC endpoints with zero BytesProcessed in 14 days and their hourly cost.

SDK v3VPC
Find untagged AWS resources

List resources missing required tag keys in each Region with GetResources, plus CSV export.

SDK v3Tagging
Create an AWS budget alert

Create a monthly cost budget with ACTUAL/FORECASTED email or SNS alerts; safe to re-run.

SDK v3Budgets
Find orphaned EBS snapshots

Find EBS snapshots whose volume is gone and no AMI uses; archive or delete behind --apply.

SDK v3EBS
Find idle ElastiCache clusters

Caches with zero GetTypeCmds/SetTypeCmds in 14 days, node-based and serverless.

SDK v3ElastiCache
Check Savings Plans coverage and utilization

Savings Plans coverage by month, uncovered On-Demand spend by service, utilization and AWS’s recommendation.

SDK v3Cost Explorer
Find unused Secrets Manager secrets

List secrets nobody retrieved in 90 days via LastAccessedDate; schedule deletion safely.

SDK v3Secrets Manager
Compare EC2 Spot price history

Average up to 90 days of Spot prices per Availability Zone and compare the cheapest zone with On-Demand.

SDK v3EC2
Find overprovisioned EBS IOPS on io1 and io2

Compare io1/io2 provisioned IOPS with 14-day peaks and price the cut.

SDK v3EBS
Find EFS file systems without a lifecycle policy

Find EFS file systems with no lifecycle policy and set IA/Archive transitions.

SDK v3EFS
Find unused DynamoDB tables

Find tables with zero reads and writes in 30 days and price their storage and provisioned capacity.

SDK v3DynamoDB
Find and delete unused CloudWatch dashboards

List dashboards past the free tier, flag stale ones and delete them behind --apply.

SDK v3CloudWatch
Find idle SageMaker endpoints

Find real-time endpoints with no invocations in N days and delete them behind --apply.

SDK v3SageMaker
Find idle Amazon Redshift clusters

Flag clusters with no connections in 14 days and compare pausing with a final snapshot.

SDK v3Redshift
Find idle OpenSearch Service domains

Find domains with no search or indexing traffic in 14 days and what they cost to keep.

SDK v3OpenSearch
Find and abort incomplete S3 multipart uploads

Size the hidden parts of abandoned multipart uploads per bucket and abort old ones with --apply.

SDK v3S3
Find empty and abandoned CloudWatch log groups

Find log groups with no data or no recent events, including ones left by deleted Lambda functions.

SDK v3CloudWatch
Find idle Amazon EMR clusters

Flag clusters idle for hours and set an auto-termination policy with --apply.

SDK v3EMR
Find unused Amazon WorkSpaces

Find WorkSpaces with no recent logins and switch them to AutoStop with --apply.

SDK v3WorkSpaces
Find EKS clusters on extended support

List clusters past standard support, their end dates and the extra hourly cost until you upgrade.

SDK v3EKS
Find RDS databases on extended support

Find instances and clusters on engine versions that incur Extended Support charges, with their dates.

SDK v3RDS
Find unused Transit Gateway attachments

Find attachments with no traffic in 30 days and what each one costs per month.

SDK v3VPC
Find idle AWS DMS replication instances

Find replication instances with no running tasks and delete empty ones with --apply.

SDK v3DMS
Find unused ECR repositories

Find repositories with no pulls or pushes in N days, size their storage and delete them with --apply.

SDK v3ECR
Find idle Kinesis data streams

Find streams with no records in or out for 14 days and what their shards and retention cost.

SDK v3Kinesis
Find idle Amazon MSK clusters

Flag Kafka clusters with no traffic in 14 days and price their brokers and storage.

SDK v3MSK
Find idle Amazon FSx file systems

Find FSx file systems with no reads or writes in 14 days and what they cost to keep.

SDK v3FSx
Find EBS snapshots to move to the archive tier

Find old snapshots worth archiving, estimate the saving and move them with --apply.

SDK v3EBS
Find unused RDS proxies

Find proxies with no client connections in 14 days and delete them with --apply.

SDK v3RDS
Find unused Elastic Beanstalk environments

Find environments with no traffic, list what they run and terminate them with --apply.

SDK v3Elastic Beanstalk
Get EC2 right-sizing recommendations

Pull Compute Optimizer findings and estimated monthly savings for every EC2 instance.

SDK v3EC2Compute Optimizer
Find idle SageMaker notebook instances

Find notebook instances left running and stop them with --apply.

SDK v3SageMaker
Find ECS services that could use Fargate Spot

List Fargate services on on-demand capacity and estimate what Fargate Spot would save.

SDK v3ECS
Find unused EC2 capacity reservations

Find capacity reservations with unused slots and what they cost, and cancel them with --apply.

SDK v3EC2
Find idle EC2 Dedicated Hosts

Find Dedicated Hosts running no instances and release empty ones with --apply.

SDK v3EC2
Measure S3 noncurrent version storage

Measure how much of each versioned bucket is old versions and delete markers, and the lifecycle fix.

SDK v3S3

Security & IAM 67

Categorize S3 buckets as public or private

Inspect each bucket’s ACL for grants to all users or all authenticated users.

SDK v3S3
Find security groups open on common ports

Flag security group rules that allow overly broad access to a list of common ports.

SDK v3EC2
See the permissions of your current IAM role

Use STS GetCallerIdentity to find the assumed role, then read its policy from IAM.

SDK v3IAMSTS
Find IAM users without MFA

Flag console IAM users with no MFA device using ListUsers, GetLoginProfile and ListMFADevices.

SDK v3IAM
Find old and unused IAM access keys

Find access keys older than 90 days or unused for 45, with a dry-run --deactivate flag.

SDK v3IAM
Find unencrypted EBS volumes

Find unencrypted EBS volumes in every Region and turn on EnableEbsEncryptionByDefault.

SDK v3EC2EBS
Find public EBS and RDS snapshots

Find EBS, RDS and Aurora snapshots shared with everyone and make them private.

SDK v3EBSRDS
Find unused IAM roles

List IAM roles unused for 90 days with RoleLastUsed, skipping service-linked roles.

SDK v3IAM
Find unused security groups

Find security groups no network interface or rule uses; delete them only with --apply.

SDK v3EC2VPC
Find unused customer managed KMS keys

Report customer managed KMS keys with no recent use via GetKeyLastUsage and CloudTrail.

SDK v3KMS
Enable DynamoDB point-in-time recovery

Find DynamoDB tables without point-in-time recovery, see the cost, and enable PITR with --apply.

SDK v3DynamoDB
Find EC2 instances without IMDSv2

Find instances that still accept IMDSv1, count their MetadataNoToken calls and require IMDSv2.

SDK v3EC2
Find expiring ACM certificates

Find ACM certificates expiring soon and why they won’t auto-renew (imported, unused, CNAME gone).

SDK v3ACM
Check CloudTrail logging in every Region

Check every enabled Region for a logging CloudTrail trail with read and write management events.

SDK v3CloudTrail
Check GuardDuty in every Region

Find Regions with no GuardDuty detector or a suspended one; create missing ones with --apply.

SDK v3GuardDuty
Find load balancers serving plain HTTP

Flag ALB HTTP listeners that don’t redirect to HTTPS and TLS policies still allowing TLS 1.0/1.1.

SDK v3ELB
Find SQS queues without a dead-letter queue

Flag SQS queues with no RedrivePolicy, broken DLQ targets and DLQs filling up.

SDK v3SQS
Find publicly accessible RDS instances

Find RDS and Aurora instances with PubliclyAccessible, IGW routes and open security groups.

SDK v3RDS
Find RDS instances without backups or encryption

Find RDS databases with backups off, no encryption or no deletion protection; enable backups with --apply.

SDK v3RDS
Find IAM policies that grant admin access

Find managed and inline IAM policies with Action "*", NotAction or iam:*.

SDK v3IAM
Check AWS Config recording in every Region

Check the AWS Config recorder, its scope and delivery channel in every Region.

SDK v3AWS Config
Find plaintext secrets in ECS task definitions

Find plaintext passwords in ECS task definition environment and map secrets to execution roles.

SDK v3ECS
Find EKS clusters with a public API endpoint

List EKS clusters whose API endpoint is public to 0.0.0.0/0, with CIDRs and auth mode.

SDK v3EKS
Find EC2 instances with public IP addresses

Instances with public IPv4 or IPv6, Elastic IP vs auto-assigned, subnet auto-assign and world-open ports.

SDK v3EC2VPC
Find IAM roles trusted by external accounts

Audit every IAM role trust policy for other accounts, Principal * and missing sts:ExternalId.

SDK v3IAM
Find KMS keys without automatic rotation

Find KMS keys with rotation off and turn it on with EnableKeyRotation behind --apply.

SDK v3KMS
Find public SNS topics and SQS queues

Flag SNS topic and SQS queue policies with Principal * and no source or org condition.

SDK v3SNSSQS
Find public AMIs

Find AMIs shared with all, check block public access per Region, make them private.

SDK v3EC2
Find VPCs without flow logs

Report flow log coverage for VPCs in each Region and create S3 flow logs for gaps behind --apply.

SDK v3VPC
Find and delete unused default VPCs

Find default VPCs in every Region, see what still uses them and delete empty ones behind --apply.

SDK v3VPC
Check the root user for MFA and access keys

Check root MFA, active root access keys, signing certs and recent root sign-ins from one script.

SDK v3IAM
Find IAM users with directly attached policies

List IAM users with managed or inline policies attached directly, plus groups to move them into.

SDK v3IAM
Find API Gateway methods without authorization

Flag REST methods and HTTP routes with NONE auth, weighed against API keys and resource policies.

SDK v3API Gateway
Find API Gateway stages without access logging

Audit access logs, execution logs and X-Ray per API stage; turn on access logs with --apply.

SDK v3API Gateway
Find ECR repositories without image scanning

Find ECR repos without automatic scanning and CRITICAL findings; add a scan rule with --apply.

SDK v3ECR
Detect CloudFormation drift across all stacks

Run drift detection on every CloudFormation stack and list changed properties.

SDK v3CloudFormation
Check Security Hub is enabled in every Region

Check Security Hub, enabled standards and cross-Region aggregation per Region; enable it with --apply.

SDK v3Security Hub
Check IAM Access Analyzer in every Region

Find Regions with no Access Analyzer, summarise active public and cross-account findings, create one with --apply.

SDK v3IAM
Find unused EC2 key pairs

List key pairs no instance or launch template references and delete them behind --apply.

SDK v3EC2
Find CloudFront distributions where WAF is not enabled

Flag distributions with no web ACL and show the managed rule groups on the ones that have one.

SDK v3CloudFront
Migrate launch configurations to launch templates

Find groups still on launch configurations and the steps to move each one to a launch template.

SDK v3EC2 Auto Scaling
Find EBS volumes without a recent snapshot

Find in-use volumes with no snapshot in N days, checked against AWS Backup and DLM coverage.

SDK v3EBS
Find unencrypted RDS instances and Aurora clusters

List databases with StorageEncrypted off and the snapshot-copy steps to encrypt them.

SDK v3RDS
Find RDS databases without deletion protection

Flag instances and Aurora clusters without deletion protection and turn it on with --apply.

SDK v3RDS
Find S3 buckets without server access logging

Find buckets with access logging off and enable it to a target bucket with --apply.

SDK v3S3
Check the IAM account password policy

Compare the account password policy with CIS recommendations and update it with --apply.

SDK v3IAM
Find privileged ECS task definitions

Flag task definitions with privileged containers, root users, added capabilities or host networking.

SDK v3ECS
Find unencrypted SQS queues and SNS topics

List queues and topics with no server-side encryption and turn on SSE-SQS with --apply.

SDK v3SQSSNS
Find ElastiCache clusters without encryption

Check at-rest and in-transit encryption and AUTH/RBAC on every cache, with the fix for each gap.

SDK v3ElastiCache
Find Secrets Manager secrets without rotation

Flag secrets with rotation off, overdue or failing, and trigger rotation with --apply.

SDK v3Secrets Manager
Find secrets stored as plaintext SSM parameters

Find String parameters that look like secrets and convert them to SecureString.

SDK v3Systems Manager
Check Amazon Inspector is enabled in every Region

Check Inspector scan types, coverage and critical findings per Region; enable it with --apply.

SDK v3Inspector
Find load balancers without access logs

Flag ALBs, NLBs and Classic ELBs with access logging off and enable it to a bucket with --apply.

SDK v3ELB
Find publicly shared SSM documents

Find Systems Manager documents shared with all accounts and make them private with --apply.

SDK v3Systems Manager
Find unused ACM certificates

List certificates nothing uses, plus expired and stuck ones, and delete unused ones with --apply.

SDK v3ACM
Check Amazon Macie is enabled in every Region

Check Macie status and automated sensitive data discovery per Region; enable it with --apply.

SDK v3Macie
Find resources not protected by AWS Backup

Compare RDS, DynamoDB, EFS, EBS and EC2 inventory with AWS Backup protected resources and recovery points.

SDK v3AWS Backup
Find Step Functions without logging or tracing

Flag state machines with logging off or X-Ray disabled and turn on logging with --apply.

SDK v3Step Functions
Find Cognito user pools without MFA

List user pools with MFA off, their password policy and threat protection, and set MFA to optional.

SDK v3Cognito
Find CloudWatch log groups without KMS encryption

List log groups with no customer managed KMS key and associate one with --apply.

SDK v3CloudWatchKMS
Check Route 53 Resolver query logging for every VPC

Find VPCs with no DNS query logging and associate a query log config with --apply.

SDK v3Route 53VPC
Find CloudFront distributions without access logging

Flag distributions with neither legacy standard logging nor CloudWatch Logs delivery configured.

SDK v3CloudFront
Audit VPC peering connections and their routes

List peerings, cross-account peers, peerings with no routes and routes that point nowhere.

SDK v3VPC
Audit IAM SAML and OIDC identity providers

List SAML and OIDC providers, the roles that trust them and trust policies missing audience or subject conditions.

SDK v3IAM
Find expired and unused IAM server certificates

Find IAM server certificates that expired or nothing uses, and delete safe ones with --apply.

SDK v3IAM
Check AWS Backup vaults for Vault Lock

Report each vault’s lock mode, retention limits and whether its access policy blocks deletes.

SDK v3AWS Backup
Find CloudFormation stacks without termination protection

List root stacks that can be deleted in one call and turn protection on with --apply.

SDK v3CloudFormation

AWS Lambda 14

Invoke a Lambda function with SDK v3

Call a function with LambdaClient and InvokeCommand, synchronously or as an event.

SDK v3Lambda
Count Lambda invocations in the last 24 hours

Use CloudWatch GetMetricData to count invocations per function and rank the busiest.

SDK v3LambdaCloudWatch
Delete old Lambda function versions

Remove every published version of a function except $LATEST.

SDK v3LambdaChanges resources
Find Lambda functions on deprecated runtimes

Every function on a deprecated runtime across all regions, with the dates updates get blocked.

SDK v3Lambda
Find public Lambda function URLs

List Lambda function URLs with AuthType NONE and a public resource policy, plus CORS.

SDK v3Lambda
Find Lambda functions with too much memory

Compare each function’s peak memory with its setting and estimate the GB-second savings.

SDK v3LambdaCloudWatch Logs
Find secrets in Lambda environment variables

Scan every Lambda function’s env vars for keys and tokens; prints names and masked hints, never values.

SDK v3Lambda
Find Lambda functions without a failure destination

Find functions with no on-failure destination or DLQ and add an SQS destination with --apply.

SDK v3Lambda
Find Lambda functions with over-privileged roles

Flag execution roles with admin access or wildcard actions and roles shared across many functions.

SDK v3LambdaIAM
Find Lambda functions not on arm64

List x86_64 functions, check layers and runtimes for arm64 readiness and estimate the saving.

SDK v3Lambda
Find unused Lambda provisioned concurrency

Find provisioned concurrency with low utilization and remove it with --apply.

SDK v3Lambda
Find Lambda SQS triggers without partial batch responses

Find SQS event source mappings without ReportBatchItemFailures and check visibility timeouts.

SDK v3LambdaSQS
Find unused Lambda layer versions

Find layer versions no function uses, see code-storage usage and delete them with --apply.

SDK v3Lambda
Find Lambda functions with excessive timeouts

Compare each function’s timeout with its p99 and maximum duration and suggest a tighter value.

SDK v3Lambda
No example matches those filters.

How to run an AWS SDK for JavaScript example

You need Node.js, an AWS account and credentials the SDK can find. The whole setup takes about five minutes the first time.

  1. Open an example and copy the codeStart with a read-only one, such as billing by service or listing buckets without versioning, to confirm your setup works.
  2. Install the SDK it importsExamples that require('aws-sdk') use v2. Examples that import from @aws-sdk/… use v3 and need each client package.
    $ npm install aws-sdk
    $ npm install @aws-sdk/client-s3 @aws-sdk/s3-request-presigner
  3. Give the SDK credentials and a regionUse a profile from ~/.aws or environment variables. See AWS’s guide to setting credentials in Node.js. Several examples hard-code us-west-2, so change it to your region.
  4. Check the IAM permissionsEach guide ends with the actions the script calls. Run it with a role that has exactly those, and use a read-only profile for anything that only reads.
  5. Run it and compare the outputRun node script.js, or npx tsx script.ts for TypeScript examples, and compare the result with the guide’s “Expected output” section.
Terminal showing npm install aws-sdk, then running node get-billing-by-service.js with AWS_PROFILE and AWS_REGION set, and a JSON array of AWS services with their monthly cost
Install, choose a profile and region, run, then check the output against the guide.

What each example guide includes

These aren’t bare snippets. Every guide follows the same six-part structure, so you can judge whether a script fits your account before you run it. The caveats section is the one to read carefully: it tells you when the script only covers one region, skips pagination, or looks at ACLs but not bucket policies.

Diagram of an example guide's six sections: code, detailed code explanation, expected output, considerations and caveats, required IAM permissions with an example policy, and FAQ
The same six sections appear in every guide.

Why every example uses AWS SDK for JavaScript v3

Every example here uses AWS SDK for JavaScript v3, the modular @aws-sdk/client-* packages. v2 reached end-of-support on September 8, 2025, so it no longer receives updates. If you still have v2 code of your own, moving it to v3 is mostly mechanical, and the step-by-step guide shows how to migrate a Node.js app from AWS SDK v2 to v3:

SDK v2SDK v3
PackageOne package: aws-sdkOne per service: @aws-sdk/client-s3
Clientnew AWS.S3()new S3Client({})
Calling an APIs3.listBuckets().promise()s3.send(new ListBucketsCommand({}))
PaginationManual NextToken loopsBuilt-in paginators, e.g. paginateListObjectsV2
S3 object bodyBufferStream; call transformToString()

To convert an example, paste it into the free AWS SDK v2 to v3 converter, then check the result against AWS’s v3 migration guide. If you work in Python or Go, the other AI code converters port SDK code between languages.

Common workflows you can build from these examples

Several examples chain together into routines worth running regularly.

A monthly AWS cost cleanup

Start by breaking down last month’s bill by service to see where to look. If EC2 or EBS dominates, run the idle-instance, unattached-volume, Elastic IP and old-AMI examples to list candidates. Review the list before running anything that stops, releases or deletes. Finally, check for Reserved Instances expiring in the next 30 days, before those instances fall back to on-demand pricing.

Workflow diagram: measure spend with Cost Explorer billing by service and expiring Reserved Instances; find waste in EC2 instances under 20% CPU, unattached EBS volumes, unassociated Elastic IPs and AMIs older than 30 days; then act by stopping instances, tagging volumes, releasing addresses and deregistering AMIs
Measure, find waste, then act. Amber steps change resources.

A quick security review

Three read-only scripts give you a fast baseline. Scan security groups for open common ports, sort S3 buckets into public and private, and check what your current role can actually do. The bucket script reads ACLs only, so also confirm S3 Block Public Access is on at the account level.

Browser uploads straight to S3

Have your backend generate a presigned upload URL, let the browser PUT the file directly to S3, then confirm the upload with a HeadObject existence check. Your server never handles the file itself, and clients never see your AWS keys. If you’re estimating what that storage will cost, try the S3 pricing calculator.

Tips for running AWS scripts safely

  • Read before you write. For any script that stops, releases or deletes, first comment out the action call and log what it would affect.
  • Separate read and write credentials. Run discovery scripts with a read-only profile, and switch to a scoped write role only for the action step. This follows AWS’s least-privilege guidance.
  • Loop over regions. Most examples act on a single region. Resources such as Elastic IPs, EBS volumes and AMIs are regional, so waste in other regions won’t show up.
  • Add pagination for large accounts. Several examples read only the first page of results. Follow NextToken in v2, or use the built-in paginators in v3.
  • Back off on throttling. Describe calls across hundreds of resources can hit API rate limits. Retry with exponential backoff instead of failing halfway through.

Common mistakes to avoid

  • Treating unblended cost as your final bill. The Cost Explorer examples use UnblendedCost, which excludes credits and Savings Plans discounts.
  • Running cost scripts in a loop. Each Cost Explorer API request costs $0.01. Cache the results instead of polling.
  • Deleting AMIs that are still in use. An AMI can be old but still referenced by a launch template or an Auto Scaling group. Check before deregistering it.
  • Committing credentials. Never paste access keys into a script. Let the SDK read them from your profile, environment or IAM role.

Frequently asked questions

Which version of the AWS SDK for JavaScript do these examples use?

All of them use the modular AWS SDK for JavaScript v3 packages, such as @aws-sdk/client-s3. The v2 aws-sdk package reached end-of-support on September 8, 2025, so convert any v2 code of your own to v3 before using it in new projects.

What do I need to install to run an example?

Node.js and the SDK packages the example imports, such as npm install @aws-sdk/client-s3. For TypeScript examples, run them with a TypeScript runner such as tsx, or compile them with tsc first.

How do the examples get my AWS credentials?

The examples create SDK clients without hard-coded keys, so the SDK uses its default credential chain: environment variables, your shared ~/.aws config and credentials files (including SSO profiles), or the IAM role of the machine or Lambda function running the code. Set AWS_PROFILE to choose a profile.

Will running these examples cost money?

Most describe and list calls are free. The Cost Explorer examples cost $0.01 per API request, and CloudWatch metric requests can be billed once you’re past the free tier. Examples that stop, release or delete resources change your bill directly, which is usually the point.

Can I run these examples in AWS Lambda?

Yes. Wrap the code in a handler, give the function an execution role with the permissions listed in the example, and remove any hard-coded region if you want it to use the function’s region. For large accounts, watch the 15-minute Lambda timeout and paginate API calls.

Are the examples safe to run against production?

The read-only examples are, when you run them with a read-only IAM role. Four examples change resources: stopping underutilized EC2 instances, releasing Elastic IPs, deregistering old AMIs and deleting their snapshots, and deleting old Lambda versions. Run those in a test account first, log what they would change, and only then let them act.

How is this different from the ChatWithCloud CLI?

These examples are code you copy, adapt and run yourself. The ChatWithCloud CLI takes a plain-English question in your terminal, writes and runs the AWS SDK calls against your account for you, and explains the result.

Rather ask than write the script?

Ask ChatWithCloud “which EBS volumes are unattached?” in your terminal. It writes and runs the SDK calls for you. The first 15 runs are free.

$ npx chatwithcloud