Managing costs is critical in DevOps, especially in cloud-heavy environments. Optimizing resource usage, pipelines, and infrastructure ensures better ROI.
import boto3
from botocore.exceptions import NoCredentialsError
def list_underutilized_ec2_instances(threshold_hours=24):
ec2 = boto3.client('ec2')
instances = ec2.describe_instances()
underutilized = []
for reservation in instances['Reservations']:
for instance in reservation['Instances']:
launch_time = instance['LaunchTime']
current_time = datetime.datetime.now(launch_time.tzinfo)
uptime_hours = (current_time - launch_time).total_seconds() / 3600
if uptime_hours < threshold_hours:
underutilized.append(instance['InstanceId'])
return underutilized
try:
print("Underutilized EC2 Instances:", list_underutilized_ec2_instances())
except NoCredentialsError:
print("AWS credentials not found.")
Cost optimization ensures DevOps teams deliver value efficiently, maintaining performance while reducing unnecessary cloud and infrastructure expenses.