AWS Builder Center
AWS FinOps: automating the detection of idle resources with Slack alerts

AWS FinOps: automating the detection of idle resources with Slack alerts

Learn how to build FinOps automations with Lambda, EventBridge Scheduler, and Slack to reduce costs by finding idle resources, like unused Elastic IPs, unattached EBS volumes, orphan snapshots, and long-stopped EC2 instances.

Cloud Analyst | FinOps | CloudOps | Security

1. Introduction

An idle resource still costs money, but it doesn’t give you any value. Some examples: the disk (EBS volume) of an instance that’s already been deleted, an Elastic IP that was created for an instance but isn’t in use and nobody released, or a Load Balancer from a test environment that doesn’t exist anymore. Too many idle resources can make your cloud bill very high.
This article shows how to create 4 Lambda functions in Python, one for each type of idle resource. They send a weekly report to a Slack channel. The functions only report the resources and don’t delete anything, because it’s up to the team to decide what to remove.

Other resources you can also check:
  • Load Balancers with no registered targets;
  • NAT Gateways with no traffic;
  • CloudWatch log groups with no retention policy;
  • gp2 volumes that you can migrate to gp3, which is about 20% cheaper;
  • RDS instances that are stopped or have no connections;
  • And more.


2. Solution Architecture

The solution uses EventBridge Scheduler to start each function at a set time. Each function calls the AWS APIs with read-only permissions. If it finds idle resources, it sends a message to a Slack webhook. Having one function for each resource type has some advantages. For example, each function can run on its own schedule, if one fails it doesn't affect the others, and it's easy to turn on only the checks that make sense for each account.


The table below shows the functions:

Note: You’ll add the SLACK_WEBHOOK_URL variable to all functions.



3. Implementation

3.1 Creating the Slack channel and webhook

A webhook is a URL that receives messages through HTTP POST and posts them to a specific channel.

1. Create the channel that will receive the alerts, for example, “finops-alerts”:





2. Go to  api.slack.com/apps , click “Create New App”, then “Blank app”. Enter a name (for example: finops-alerts) and select your workspace:





3. In the side menu, go to “Incoming Webhooks” and turn on “Activate Incoming Webhooks”:



4. Then click “Add New Webhook”, select the “finops-alerts” channel, and click “Allow”:



5. Copy the URL that was created, it starts with  https://hooks.slack.com/services/xxx :

Note: Don’t share the full webhook URL, because anyone who has it can post messages to the channel.

3.2 Creating the IAM policy and role for the Lambda functions

The 4 Lambda functions share one role with read-only permissions. In accounts with stricter least-privilege rules, you can create one role per function, each with only the actions that function uses. But in this article, we’ll use the “finops-idle-resources-role” role for all 4.

1. To create the policy, open the AWS Management Console and go to IAM, click “Policies”, then “Create policy”. Open the JSON tab and paste the policy below:



{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "FinOpsIdleResourcesReadOnly",
"Effect": "Allow",
"Action": [
"ec2:DescribeAddresses",
"ec2:DescribeVolumes",
"ec2:DescribeSnapshots",
"ec2:DescribeImages",
"ec2:DescribeInstances"
],
"Resource": "*"
}
]
}

Save the policy with the name "finops-idle-resources-policy":


2. To create the role, stay in IAM and go to the “Roles” tab, click “Create role”, select “AWS service”, “Lambda”, and continue:



3. Then select the “AWSLambdaBasicExecutionRole” and “finops-idle-resources-policy” policies. Enter a name for the role (for example: finops-idle-resources-role) and click “Create role”:




3.3 Lambda function 1: Idle Elastic IPs

The process is the same for all 4 functions, only the name, the code, and the optional variables change.

1. To create the function, go to Lambda and click “Create Event Function”:



2. Then enter the name “finops-idle-elastic-ips”, choose Python as the runtime, and select the arm64 architecture (it costs less than x86_64). Select the role you created before, “finops-idle-resources-role”, and click “Create Event Function”:


3. In the “Code” tab, replace the content of “lambda_function.py” with the function code below and click “Deploy”:
import json
import os
import urllib.request

import boto3

SLACK_WEBHOOK_URL = os.environ["SLACK_WEBHOOK_URL"]
IGNORE_TAG = os.environ.get("IGNORE_TAG", "finops-ignore")
MAX_ITEMS = 20

ec2 = boto3.client("ec2")

def is_ignored(tags):
return any(t.get("Key") == IGNORE_TAG and t.get("Value", "").lower() == "true" for t in tags or [])

def get_name(tags):
return next((t["Value"] for t in tags or [] if t.get("Key") == "Name"), "no name")

def find_idle_elastic_ips():
addresses = [a for a in ec2.describe_addresses()["Addresses"] if not is_ignored(a.get("Tags"))]

findings = [
f"`{a['PublicIp']}` ({get_name(a.get('Tags'))}): not associated"
for a in addresses
if "AssociationId" not in a
]

instance_ids = [a["InstanceId"] for a in addresses if a.get("InstanceId")]
if instance_ids:
response = ec2.describe_instances(
InstanceIds=instance_ids,
Filters=[{"Name": "instance-state-name", "Values": ["stopped"]}],
)
stopped = {i["InstanceId"] for r in response["Reservations"] for i in r["Instances"]}
findings += [
f"`{a['PublicIp']}` ({get_name(a.get('Tags'))}): attached to stopped instance `{a['InstanceId']}`"
for a in addresses
if a.get("InstanceId") in stopped
]
return findings

def notify_slack(title, findings, context):
account_id = context.invoked_function_arn.split(":")[4]
region = os.environ["AWS_REGION"]
lines = "\n".join(f"• {item}" for item in findings[:MAX_ITEMS])
if len(findings) > MAX_ITEMS:
lines += f"\n_...and {len(findings) - MAX_ITEMS} more_"
payload = {
"text": f"{title}: {len(findings)} found",
"blocks": [
{"type": "header", "text": {"type": "plain_text", "text": f"{title} ({len(findings)})"}},
{"type": "context", "elements": [{"type": "mrkdwn", "text": f"Account `{account_id}` | Region `{region}`"}]},
{"type": "section", "text": {"type": "mrkdwn", "text": lines[:2900]}},
],
}
request = urllib.request.Request(
SLACK_WEBHOOK_URL,
data=json.dumps(payload).encode("utf-8"),
headers={"Content-Type": "application/json"},
)
with urllib.request.urlopen(request, timeout=10) as response:
return response.status

def lambda_handler(event, context):
findings = find_idle_elastic_ips()
print(json.dumps({"count": len(findings), "findings": findings}))
if findings:
notify_slack("Idle Elastic IPs", findings, context)
return {"count": len(findings)}


4. Then click “Configuration”, “General configuration”, and “Edit”. Set “Timeout” to 2 minutes and “Memory” to 256 MB. The default timeout of 3 seconds isn’t enough for accounts with many resources:



The settings were updated successfully:


5. The next step is to set up the environment variables. Click “Configuration”, “Environment variables”, and “Edit”. Add “SLACK_WEBHOOK_URL” with the URL you created in section 3.1 ( https://hooks.slack.com/services/xxx ) and, if needed, the optional variables for the function:


Note: In corporate environments, you can store the webhook in a secrets management tool, like AWS Secrets Manager or another solution, instead of an environment variable. This is because environment variables are visible to anyone who has read access to the function in the console. This change needs a small update to the code, and we won’t cover it here.

6. Now we can test it. To make sure the function finds something, create an Elastic IP (for example: eip-test). Go to “EC2/ Elastic IPs”, click “Allocate Elastic IP address”, and don’t associate it with any instance:




7. After that, click the “Test” tab and enter a name for the event (for example: test-01). Replace the content of the “Event JSON” field with {} and click “Test”. The result shows how many resources were found (for example, {“count”: 2}). If the number is greater than zero, the message is sent to the Slack channel.


The function found 2 idle IPs, one that isn’t associated with any instance, and another that’s associated with a stopped instance:


The result was also sent to the "finops-alerts" channel in Slack:

Note: The auto-assigned public IP of an instance is dynamic and can change when you stop and start the instance again. An Elastic IP is static and stays reserved for your account until you release it. When it isn’t associated with a running instance or another resource, the IP can still generate charges. That’s why the function checks for idle IPs that aren’t associated with resources, to find possible ways to reduce costs.


3.4 Lambda function 2: Unattached EBS volumes

A disk in the “available” state isn’t attached to any instance, but you still pay for each provisioned GB. This happens when instances are deleted without the “Delete on termination” option.

Function name: finops-unattached-ebs-volumes
import json
import os
import urllib.request
from datetime import datetime, timezone

import boto3

SLACK_WEBHOOK_URL = os.environ["SLACK_WEBHOOK_URL"]
IGNORE_TAG = os.environ.get("IGNORE_TAG", "finops-ignore")
MAX_ITEMS = 20

ec2 = boto3.client("ec2")

def is_ignored(tags):
return any(t.get("Key") == IGNORE_TAG and t.get("Value", "").lower() == "true" for t in tags or [])

def get_name(tags):
return next((t["Value"] for t in tags or [] if t.get("Key") == "Name"), "no name")

def find_unattached_volumes():
findings = []
now = datetime.now(timezone.utc)
pages = ec2.get_paginator("describe_volumes").paginate(
Filters=[{"Name": "status", "Values": ["available"]}]
)
for page in pages:
for volume in page["Volumes"]:
if is_ignored(volume.get("Tags")):
continue
age_days = (now - volume["CreateTime"]).days
findings.append(
f"`{volume['VolumeId']}` ({get_name(volume.get('Tags'))}): "
f"{volume['Size']} GiB {volume['VolumeType']}, created {age_days} days ago"
)
return findings

def notify_slack(title, findings, context):
account_id = context.invoked_function_arn.split(":")[4]
region = os.environ["AWS_REGION"]
lines = "\n".join(f"• {item}" for item in findings[:MAX_ITEMS])
if len(findings) > MAX_ITEMS:
lines += f"\n_...and {len(findings) - MAX_ITEMS} more_"
payload = {
"text": f"{title}: {len(findings)} found",
"blocks": [
{"type": "header", "text": {"type": "plain_text", "text": f"{title} ({len(findings)})"}},
{"type": "context", "elements": [{"type": "mrkdwn", "text": f"Account `{account_id}` | Region `{region}`"}]},
{"type": "section", "text": {"type": "mrkdwn", "text": lines[:2900]}},
],
}
request = urllib.request.Request(
SLACK_WEBHOOK_URL,
data=json.dumps(payload).encode("utf-8"),
headers={"Content-Type": "application/json"},
)
with urllib.request.urlopen(request, timeout=10) as response:
return response.status

def lambda_handler(event, context):
findings = find_unattached_volumes()
print(json.dumps({"count": len(findings), "findings": findings}))
if findings:
notify_slack("Unattached EBS volumes", findings, context)
return {"count": len(findings)}

1. Repeat the steps from section 3.3 to create the function, deploy the code, and test it.

2. Run the test “test-02”. For this test, we also created an unattached disk in “EC2", "Elastic Block Store/ Volumes” by clicking “Create volume”:



Below is the result in the Slack channel. In this case, the function found one EBS volume that isn’t attached to any instance:



3.5 Lambda function 3: Finding orphan snapshots

On AWS, many services create snapshots, and EBS volume snapshots (the disks of EC2 instances) are among the most common. That’s why this function only checks disk snapshots.
A snapshot is called an orphan when the disk it came from has already been deleted. In this case, you still pay for it. The minimum age for a snapshot to be reported is set by the “SNAPSHOT_MIN_AGE_DAYS” variable. In the code, this variable has a default value of 90 days, as the comment “default: 90 days if the variable is not set” shows. This means that if you don’t add the variable to the function, it uses 90 days, which is a good period for corporate environments. In this example, we’ll set the variable to “0”, so the function finds the test snapshot right away.

Function name: finops-orphan-ebs-snapshots
import json
import os
import urllib.request
from datetime import datetime, timedelta, timezone

import boto3

SLACK_WEBHOOK_URL = os.environ["SLACK_WEBHOOK_URL"]
IGNORE_TAG = os.environ.get("IGNORE_TAG", "finops-ignore")
MAX_ITEMS = 20
SNAPSHOT_MIN_AGE_DAYS = int(os.environ.get("SNAPSHOT_MIN_AGE_DAYS", "90")) # default: 90 days if the variable is not set

ec2 = boto3.client("ec2")

def is_ignored(tags):
return any(t.get("Key") == IGNORE_TAG and t.get("Value", "").lower() == "true" for t in tags or [])

def get_name(tags):
return next((t["Value"] for t in tags or [] if t.get("Key") == "Name"), "no name")

def find_orphan_snapshots():
now = datetime.now(timezone.utc)
limit = now - timedelta(days=SNAPSHOT_MIN_AGE_DAYS)

existing_volumes = {
v["VolumeId"]
for page in ec2.get_paginator("describe_volumes").paginate()
for v in page["Volumes"]
}
ami_snapshots = {
mapping["Ebs"]["SnapshotId"]
for image in ec2.describe_images(Owners=["self"])["Images"]
for mapping in image.get("BlockDeviceMappings", [])
if mapping.get("Ebs", {}).get("SnapshotId")
}

findings = []
for page in ec2.get_paginator("describe_snapshots").paginate(OwnerIds=["self"]):
for snapshot in page["Snapshots"]:
tags = snapshot.get("Tags") or []
if is_ignored(tags) or any(t["Key"].startswith("aws:backup") for t in tags):
continue # ignored or managed by AWS Backup
if snapshot["StartTime"] > limit:
continue # too recent
if snapshot["SnapshotId"] in ami_snapshots:
continue # used by an AMI
if snapshot.get("VolumeId") in existing_volumes:
continue
age_days = (now - snapshot["StartTime"]).days
findings.append(
f"`{snapshot['SnapshotId']}` ({get_name(tags)}): "
f"{snapshot['VolumeSize']} GiB, created {age_days} days ago"
)
return findings

def notify_slack(title, findings, context):
account_id = context.invoked_function_arn.split(":")[4]
region = os.environ["AWS_REGION"]
lines = "\n".join(f"• {item}" for item in findings[:MAX_ITEMS])
if len(findings) > MAX_ITEMS:
lines += f"\n_...and {len(findings) - MAX_ITEMS} more_"
payload = {
"text": f"{title}: {len(findings)} found",
"blocks": [
{"type": "header", "text": {"type": "plain_text", "text": f"{title} ({len(findings)})"}},
{"type": "context", "elements": [{"type": "mrkdwn", "text": f"Account `{account_id}` | Region `{region}`"}]},
{"type": "section", "text": {"type": "mrkdwn", "text": lines[:2900]}},
],
}
request = urllib.request.Request(
SLACK_WEBHOOK_URL,
data=json.dumps(payload).encode("utf-8"),
headers={"Content-Type": "application/json"},
)
with urllib.request.urlopen(request, timeout=10) as response:
return response.status

def lambda_handler(event, context):
findings = find_orphan_snapshots()
print(json.dumps({"count": len(findings), "findings": findings}))
if findings:
notify_slack("Orphan EBS snapshots", findings, context)
return {"count": len(findings)}

1. Repeat the steps from section 3.3 to create the function, deploy the code, and test it.
2. We set up the environment variables like this:


3. For the test, we created a snapshot of the disk used in section 3.4. Go to “EC2", "Elastic Block Store/ Volumes”, select the “test-02” disk, click “Actions” and “Create snapshot” (for example: snapshot-test-02). Then we deleted the disk and kept only the snapshot. After that, we tested the “finops-orphan-ebs-snapshots” function to find orphan snapshots:


Below is the result in the Slack channel. In this case, the function found one orphan snapshot:



3.6 Lambda function 4: EC2 instances stopped for a long time

A stopped instance doesn’t charge for compute, but you still pay for its EBS volumes and associated IPs. The minimum time an instance must be stopped before it’s reported is set by the “STOPPED_MIN_DAYS” variable. In the code, this variable has a default value of 30 days, as the comment “default: 30 days if the variable is not set” shows. This means that if you don’t add the variable to the function, it uses 30 days. In this example, we’ll set the variable to “0”, so the function finds the instances we stopped for the test right away.

Function name: finops-long-stopped-ec2
import json
import os
import re
import urllib.request
from datetime import datetime, timedelta, timezone

import boto3

SLACK_WEBHOOK_URL = os.environ["SLACK_WEBHOOK_URL"]
IGNORE_TAG = os.environ.get("IGNORE_TAG", "finops-ignore")
MAX_ITEMS = 20
STOPPED_MIN_DAYS = int(os.environ.get("STOPPED_MIN_DAYS", "30")) # default: 30 days if the variable is not set

STOP_DATE = re.compile(r"\((\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) (?:GMT|UTC)\)")

ec2 = boto3.client("ec2")

def is_ignored(tags):
return any(t.get("Key") == IGNORE_TAG and t.get("Value", "").lower() == "true" for t in tags or [])

def get_name(tags):
return next((t["Value"] for t in tags or [] if t.get("Key") == "Name"), "no name")

def find_long_stopped_instances():
now = datetime.now(timezone.utc)
limit = now - timedelta(days=STOPPED_MIN_DAYS)
findings = []
pages = ec2.get_paginator("describe_instances").paginate(
Filters=[{"Name": "instance-state-name", "Values": ["stopped"]}]
)
for page in pages:
for reservation in page["Reservations"]:
for instance in reservation["Instances"]:
if is_ignored(instance.get("Tags")):
continue
match = STOP_DATE.search(instance.get("StateTransitionReason", ""))
if not match:
continue
stopped_at = datetime.strptime(match.group(1), "%Y-%m-%d %H:%M:%S").replace(tzinfo=timezone.utc)
if stopped_at < limit:
findings.append(
f"`{instance['InstanceId']}` ({get_name(instance.get('Tags'))}): "
f"{instance['InstanceType']}, stopped {(now - stopped_at).days} days ago"
)
return findings

def notify_slack(title, findings, context):
account_id = context.invoked_function_arn.split(":")[4]
region = os.environ["AWS_REGION"]
lines = "\n".join(f"• {item}" for item in findings[:MAX_ITEMS])
if len(findings) > MAX_ITEMS:
lines += f"\n_...and {len(findings) - MAX_ITEMS} more_"
payload = {
"text": f"{title}: {len(findings)} found",
"blocks": [
{"type": "header", "text": {"type": "plain_text", "text": f"{title} ({len(findings)})"}},
{"type": "context", "elements": [{"type": "mrkdwn", "text": f"Account `{account_id}` | Region `{region}`"}]},
{"type": "section", "text": {"type": "mrkdwn", "text": lines[:2900]}},
],
}
request = urllib.request.Request(
SLACK_WEBHOOK_URL,
data=json.dumps(payload).encode("utf-8"),
headers={"Content-Type": "application/json"},
)
with urllib.request.urlopen(request, timeout=10) as response:
return response.status

def lambda_handler(event, context):
findings = find_long_stopped_instances()
print(json.dumps({"count": len(findings), "findings": findings}))
if findings:
notify_slack("Long-stopped EC2 instances", findings, context)
return {"count": len(findings)}

1. Repeat the steps from section 3.3 to create the function, deploy the code, and test it.
2. We set up the environment variables like this:


3. For the test, we used 2 servers, “srv-grafana” and “srv-test”, in “EC2/ Instances”. Both are in the “Stopped” state:


Below is the result in the Slack channel. In this case, the function found the 2 instances that are stopped in the account:




4. Automating the scan with EventBridge Scheduler

4.1 Setting up EventBridge Scheduler

EventBridge Scheduler is a service you can use to run the Lambda functions automatically at set times. Each function gets its own schedule, so you can use different frequencies for each resource type.
1. In the EventBridge console, go to “Scheduler”, “Schedules”, click “Create schedule”, and fill in:
  • Schedule name: function name (for example: finops-idle-elastic-ips-weekly)
  • Schedule pattern: select “Recurring schedule” and “Cron-based schedule”
  • Cron expression:  0 9 ? * MON *  (runs every Monday at 9:00 AM)
  • Time zone: America/Sao_Paulo
  • Flexible time window: Off



Note: A weekly schedule avoids repeated alerts, but you can change it to fit each environment. For example:
  • Daily (every day at 9:00 AM):  0 9 * * ? * 
  • Monthly (on the 1st of every month at 9:00 AM):  0 9 1 * ? * 

2. In the next step, select “AWS Lambda”. In the “Invoke” section, select the “finops-idle-elastic-ips” function and continue:


3. In the next step, you can keep the default settings. In “Permissions”, select “Create new role for this schedule” and enter a name for the role (for example: finops-idle-eips-scheduler-role). This role lets EventBridge Scheduler invoke the function automatically:



4. Then click “Next”, review the settings, and click “Create schedule”.


5. The schedule was created successfully:


6. Repeat the steps above for the other Lambda functions.


5. Conclusion

The 4 functions in this article make it easier to find idle resources that still generate costs in your account, like unused Elastic IPs, unattached disks, orphan snapshots, and instances that have been stopped for a long time. With a weekly report in Slack, it’s easier to review these resources and decide what can be removed. You can also use the same process to check other resources, like Load Balancers with no targets, NAT Gateways with no traffic, and more.
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article