Skip to content

Instantly share code, notes, and snippets.

@tokudu
Created November 14, 2012 02:41
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save tokudu/4069955 to your computer and use it in GitHub Desktop.
Save tokudu/4069955 to your computer and use it in GitHub Desktop.
A simple deployment script for EC2 instances
#!/bin/bash
# Updates all EC2 instances from git
# Author: anton@sothree.com
CODE_LOCATION=/var/www/your_project
SERVER_PREFIX=your_project
# exit if something fails
set -e
if [ $# -gt 1 ]
then
echo "Usage: `basename $0` [instance_type]"
exit 1
fi
instance_type=$1
read -p "Are you sure you want to push code to production [y/N]? " -n 1 -r
echo -e
if [[ $REPLY =~ ^[Yy]$ ]]
then
echo "Starting deployment..."
else
exit 0;
fi
echo "$(tput setaf 2)Running tests...$(tput sgr0)"
# RUN ALL TESTS HERE
echo "Done."
if [ -n "$instance_type" ]
then
type_filter="--filter \"tag:Type=${instance_type}\""
echo "$(tput setaf 2)Updating all instances of type ${instance_type}...$(tput sgr0)"
else
echo "$(tput setaf 2)Updating all instances...$(tput sgr0)"
fi
# find all EC2 instances by type
for instance_id in $(ec2-describe-instances ${type_filter} --filter instance-state-name=running | grep INSTANCE | awk '{print $2}' ); do
echo "$(tput setaf 3)Updating instance ${instance_id}...$(tput sgr0)"
# get instance address
instance_address=`ec2-describe-instances ${instance_id} | grep INSTANCE | awk '{print $4}'`
echo "Instance address: $instance_address"
# get instance type
instance_type=`ec2-describe-instances ${instance_id} | grep Type | awk '{print $5}'`
echo "Instance type: $instance_type"
echo "Deploying and restarting servers..."
# example deployment steps for instance of type 'www'
if [ $instance_type == "www" ]; then
ssh ${instance_address} 'bash' <<EOF
# Find al servers in the upstart directory
servers=`ls -la /etc/init/ | grep -oEi '${SERVER_PREFIX}[a-z]+'`
# Stop all servers
for server in $servers; do
sudo stop $server
done
# Pull new code from git
cd ${CODE_LOCATION};
git pull;
# Start all servers
for server in $servers; do
sudo start $server
done
EOF
fi
echo "Finished updating instance ${instance_id}"
done
echo "Done."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment