Skip to content

Commit

Permalink
Cleaner for unused old EBS Volumes (#1065)
Browse files Browse the repository at this point in the history
  • Loading branch information
Paramadon authored Mar 1, 2024
1 parent 3dfbf6a commit 8f1a815
Show file tree
Hide file tree
Showing 2 changed files with 86 additions and 0 deletions.
18 changes: 18 additions & 0 deletions .github/workflows/clean-aws-resources.yml
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,24 @@ jobs:
- name: Clean old eks cluster
working-directory: tool/clean
run: go run ./clean_eks/clean_eks.go --tags=clean
clean-ebs-volumes:
runs-on: ubuntu-latest
permissions:
id-token: write
contents: read
steps:
- uses: actions/checkout@v3
- uses: actions/setup-go@v4

- name: Configure AWS Credentials
uses: aws-actions/configure-aws-credentials@v2
with:
role-to-assume: ${{ secrets.TERRAFORM_AWS_ASSUME_ROLE }}
aws-region: us-west-2

- name: Clean old unused ebs volumes
working-directory: tool/clean
run: go run ./clean_ebs/clean_ebs.go --tags=clean

clean-asg:
runs-on: ubuntu-latest
Expand Down
68 changes: 68 additions & 0 deletions tool/clean/clean_ebs/clean_ebs.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT

package main

import (
"context"
"log"
"time"

"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/ec2"
"github.com/aws/aws-sdk-go-v2/service/ec2/types"

"github.com/aws/amazon-cloudwatch-agent/tool/clean"
)

// Clean ebs volumes if they have been open longer than 7 day and unused
func main() {
err := cleanVolumes()
if err != nil {
log.Fatalf("errors cleaning %v", err)
}
}

func cleanVolumes() error {
log.Print("Begin to clean EBS Volumes")
ctx := context.Background()
defaultConfig, err := config.LoadDefaultConfig(ctx)
if err != nil {
return err
}
ec2Client := ec2.NewFromConfig(defaultConfig)

return deleteUnusedVolumes(ctx, ec2Client)

}

func deleteUnusedVolumes(ctx context.Context, client *ec2.Client) error {

input := &ec2.DescribeVolumesInput{
Filters: []types.Filter{
{
//if the status is availble, then EBS volume is not currently attached to any ec2 instance (so not being used)
Name: aws.String("status"),
Values: []string{"available"},
},
},
}

volumes, err := client.DescribeVolumes(ctx, input)
if err != nil {
return err
}
for _, volume := range volumes.Volumes {
if time.Since(*volume.CreateTime) > clean.KeepDurationOneWeek && len(volume.Attachments) == 0 {
log.Printf("Deleting unused volume %s", *volume.VolumeId)
_, err = client.DeleteVolume(ctx, &ec2.DeleteVolumeInput{
VolumeId: volume.VolumeId,
})
}
if err != nil {
log.Printf("Error deleting volume %s: %v", *volume.VolumeId, err)
}
}
return nil
}

0 comments on commit 8f1a815

Please sign in to comment.