Skip to content

Instantly share code, notes, and snippets.

@alemazz
Last active November 6, 2015 11:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alemazz/69beae9129faf60bd29a to your computer and use it in GitHub Desktop.
Save alemazz/69beae9129faf60bd29a to your computer and use it in GitHub Desktop.
jenkins EC2 instance switchoff
#!/bin/bash
BACKUPLOG="/var/tmp/backuplogaws"
SENDTO="webmaster@example.com"
echo "start setup jenkinsCI" > ${BACKUPLOG} 2>&1
AMI_ID_OLD=$(aws ec2 describe-images --owner 184559516538 --query 'Images[?starts_with(Name, `jenkinsAMI`) == `true`]|[0:5].[CreationDate,ImageId,Name]' --profile **** --output text | sort -k1 | tail -n1 | awk '{print $2}')
sleep 20
echo "found ami id : $AMI_ID_OLD" >> ${BACKUPLOG} 2>&1
INSTANCE_ID_OLD=$(aws ec2 describe-instances --filters "Name=image-id,Values=$AMI_ID_OLD" --query 'Reservations[*].Instances[*].{ID:InstanceId}' --profile **** --output text)
sleep 20
echo "found instance id : $INSTANCE_ID_OLD" >> ${BACKUPLOG} 2>&1
aws ec2 stop-instances --instance-ids $INSTANCE_ID_OLD --profile ****
sleep 300
echo "stopped instance id : $INSTANCE_ID_OLD" >> ${BACKUPLOG} 2>&1
AMI_NAME=jenkinsAMI-$(date +'%d/%m/%Y')
aws ec2 create-image --instance-id $INSTANCE_ID_OLD --name $AMI_NAME --profile ****
sleep 1200
echo "created image for instance id : $INSTANCE_ID_OLD" >> ${BACKUPLOG} 2>&1
aws ec2 disassociate-address --public-ip **** --profile ****
echo "disassociate ip for instance : $INSTANCE_ID_OLD" >> ${BACKUPLOG} 2>&1
sleep 50
aws ec2 terminate-instances --instance-ids $INSTANCE_ID_OLD --profile ****
sleep 500
echo "terminated instance id id : $INSTANCE_ID_OLD" >> ${BACKUPLOG} 2>&1
SNAPSHOT_ID=$(aws ec2 describe-images --image-id $AMI_ID_OLD --query 'Images[*].BlockDeviceMappings[0].Ebs.SnapshotId' --profile **** --output text)
echo "found SNAPSHOT id : $SNAPSHOT_ID" >> ${BACKUPLOG} 2>&1
aws ec2 deregister-image --image-id $AMI_ID_OLD --profile ****
sleep 500
echo "deregistered ami id : $AMI_ID_OLD" >> ${BACKUPLOG} 2>&1
aws ec2 delete-snapshot --snapshot-id $SNAPSHOT_ID --profile ****
sleep 500
echo "deleted snapshot for id : $SNAPSHOT_ID" >> ${BACKUPLOG} 2>&1
mail -s "JENKINS AWS switched off" ${SENDTO}
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment