Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
AWS Lambda function that will stop and eventually terminate instances that have packer keys attached to them .
#!/usr/bin/env python3
import datetime
import pytz
import boto3
def lambda_handler(event, context):
TerminateDelayDays = 3
StopDelayDays = 1
Targets = []
PackerRunning = []
PackerStopped = []
PackerSpot = []
DateTimeNow = datetime.datetime.now(pytz.utc)
LaunchAge = None
ec2_client = boto3.client("ec2")
response = ec2_client.describe_instances()
for records in response["Reservations"]:
for record in records["Instances"]:
KeyName = "None"
if record["State"]["Name"] != "terminated":
State = record["State"]["Name"]
LaunchTime = record["LaunchTime"]
InstanceId = record["InstanceId"]
LaunchAge = DateTimeNow - LaunchTime
if record.get("InstanceLifecycle") != None:
InstanceType = record["InstanceLifecycle"]
else:
InstanceType = "normal"
if record.get("KeyName") != None:
KeyName = record["KeyName"]
else:
KeyName = "NoKey"
if (LaunchAge != None
and LaunchAge.days > StopDelayDays
and State != "terminated"
and KeyName.startswith("packer_")):
Targets.append({
"KeyName": KeyName,
"State": State,
"InstanceId": InstanceId,
"InstanceType": InstanceType,
"LaunchAge": LaunchAge.days
})
print("Looking for Orphan Packer Instances")
for Target in Targets:
print(
"Handling:",
Target["InstanceId"],
Target["State"],
Target["InstanceType"],
Target["KeyName"],
Target["LaunchAge"],"Days Old"
)
if Target["State"] == "running" and Target["InstanceType"] == 'spot':
PackerSpot.append(Target["InstanceId"])
if Target["State"] == "running" and Target["InstanceType"] != 'spot':
PackerRunning.append(Target["InstanceId"])
if Target["State"] == "stopped" and Target["LaunchAge"] > TerminateDelayDays:
PackerStopped.append(Target["InstanceId"])
if len(PackerSpot) > 0:
print("Terminateing Spots:",PackerSpot)
ec2_client.terminate_instances(InstanceIds=PackerSpot)
if len(PackerRunning) > 0:
print("Stopping:",PackerRunning)
ec2_client.stop_instances(InstanceIds=PackerRunning)
if len(PackerStopped) > 0:
print("Terminateing:",PackerStopped)
ec2_client.terminate_instances(InstanceIds=PackerStopped)
if (len(PackerStopped) == 0
and len(PackerRunning) == 0
and len(PackerSpot) == 0):
print("No old Packer Instances found, no action taken.")
print("Done")
return {
"message" : "Completed"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment