Skip to content

Instantly share code, notes, and snippets.

@zetavg
Last active August 29, 2015 14:14
Show Gist options
  • Save zetavg/77729219e4232f55c85d to your computer and use it in GitHub Desktop.
Save zetavg/77729219e4232f55c85d to your computer and use it in GitHub Desktop.
The script used to deploy Rails apps to AWS OpsWorks via Codeship.
#!/bin/sh
#
# The script used to deploy Rails apps to AWS OpsWorks via Codeship.
#
# It requires the following environment variables to be set:
#
# - AWS_ACCESS_KEY_ID
# - AWS_SECRET_ACCESS_KEY
# - APP_NAME
# - S3_BUCKET
# - OPS_STACK_ID
# - OPS_APP_ID
#
# The following environment variables are optional:
#
# - NOTIFICATION_WEBHOOK_URL
#
# Deployment command on Codeship:
#
# `curl -L http://git.io/codeship_rails_opsdeploy | sh`
#
set -e
echo '-----> Preparing environment'
export APP_VERSION=`git rev-parse --short HEAD`
export DATABASE_URL=sqlite3:db/build.sqlite3
pip install awscli
# clean build artifacts and create the application archive (also ignore any files named .git* in any folder)
echo '-----> Cleaning build artifacts'
git clean -fd
# precompile assets
echo '-----> Precompiling assets'
echo 'Devise.setup { |c| c.secret_key = "build_key" } if defined? Devise' > config/initializers/devise_build_tmp.rb
RAILS_ENV=production bundle exec rake assets:precompile
rm config/initializers/devise_build_tmp.rb
# remove unnecessary files
echo '-----> Cleaning up'
rm -rf tmp/*
rm -rf .git
rm -rf .env
# zip the application
echo '-----> Packing up application'
zip -x *.git* -r "${APP_NAME}-${APP_VERSION}.zip" .
# upload to S3
echo '-----> Uploading application to S3'
aws s3 cp "${APP_NAME}-${APP_VERSION}.zip" "s3://${S3_BUCKET}/${APP_NAME}-${APP_VERSION}.zip"
echo "${APP_VERSION}" > "${APP_NAME}-latest.txt"
aws s3 cp "${APP_NAME}-latest.txt" "s3://${S3_BUCKET}/${APP_NAME}-latest.txt"
# Update OpsWorks App Source (OpsWorks CLI commands should set the region to us-east-1, regardless of the stack's location)
echo '-----> Updating OpsWorks application data'
aws opsworks --region us-east-1 update-app --app-id ${OPS_APP_ID} --app-source "Type=s3,Url=https://${S3_BUCKET}.s3.amazonaws.com/${APP_NAME}-${APP_VERSION}.zip,Username=${AWS_ACCESS_KEY_ID},Password=${AWS_SECRET_ACCESS_KEY}"
# Deploy OpsWorks App
echo '-----> Create deployment'
DATA=$(aws opsworks --region us-east-1 create-deployment --stack-id ${OPS_STACK_ID} --app-id ${OPS_APP_ID} --command "{\"Name\":\"deploy\", \"Args\":{\"migrate\":[\"true\"]}}")
# Send Notification to Webhook
if [ ! -z "${NOTIFICATION_WEBHOOK_URL+x}" ]; then
echo '-----> Sending Notification'
curl -X POST -H "Content-Type: application/json" -d "${DATA}" "${NOTIFICATION_WEBHOOK_URL}"
echo ''
fi
echo "${DATA}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment