Skip to content

Instantly share code, notes, and snippets.

@immanuelpotter
Last active April 30, 2021 08:23
Show Gist options
  • Save immanuelpotter/e0007b5468a50241466673e59385b4aa to your computer and use it in GitHub Desktop.
Save immanuelpotter/e0007b5468a50241466673e59385b4aa to your computer and use it in GitHub Desktop.
packer-cleanup-serverless
# Distribution / packaging
.Python
env/
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
*.egg-info/
.installed.cfg
*.egg
# Serverless directories
.serverless

snapshot-cleanup

Install node.js/npm if you haven't already, as serverless framework is a node package:

brew install node

Install serverless framework:

npm install -g serverless

Configure credentials:

serverless config credentials --provider aws --key ***<REDACTED>*** --secret ***<REDACTED>***

Invocation locally, while developing:

serverless invoke local -f packersnapshotcleanup --path event-mock.json

Deploy & test:

serverless deploy function -f packersnapshotcleanup && sls invoke -f packersnapshotcleanup --path event-mock.json

[
{
"Time": "00-00-00T00:00:00Z",
"Source": "my-custom-source",
"Resources": ["my-custom-resources"],
"DetailType": "my-custom-detail",
"Detail": "{ \"key\": \"value\"}"
}
]
import json, boto3, botocore
def snapshot_cleanup(event, context):
ec2 = boto3.resource('ec2')
snapshots = ec2.snapshots.filter(Filters=[
{
'Name': 'tag:Name',
'Values': [
'something-images-are-named-*',
'something-else-images-are-named-*'
]
}
])
all_ids = []
deleted_ids = []
for snapshot in snapshots:
all_ids.append(snapshot.id)
try:
snapshot.delete(SnapshotId=snapshot.id)
deleted_ids.append(snapshot.id)
except botocore.exceptions.ClientError as ex:
print(f'Deletion for snapshot {snapshot.id} failed. Exception: {ex}')
continue
except Exception as ex:
print(f'Something went wrong while trying to delete snapshot {snapshot.id}. Exception: {ex}')
continue
return {
"all_snapshots": all_ids,
"snapshots_deleted": deleted_ids,
"event": event
}
# Call this where you want to trigger the process.
function put_events() {
local DATE_NOW=$(date +%Y-%m-%dT%H:%M:%SZ)
aws events \
put-events \
--entries '[{"Time": "'${DATE_NOW}'", "Source": "my-custom-source", "Resources": ["my-custom-resources"], "DetailType": "my-custom-detail", "Detail": "{ \"key\": \"value\"}"}]'
return $?
}
put_events
service: packersnapshotcleanup
frameworkVersion: '2'
provider:
name: aws
runtime: python3.8
lambdaHashingVersion: 20201221
timeout: 10
region: eu-west-2
stage: dev
iamRoleStatements:
- Effect: "Allow"
Action:
- ec2:DeleteSnapshot
- ec2:DescribeVolumes
- ec2:DescribeSnapshots
Resource: "*"
functions:
packersnapshotcleanup:
handler: handler.snapshot_cleanup
events:
- cloudwatchEvent:
event:
source:
- "my-custom-source"
detail-type:
- "my-custom-detail"
detail:
key:
- value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment