Skip to content

Instantly share code, notes, and snippets.

@fsouza
Created March 2, 2016 19:04
Show Gist options
  • Save fsouza/4834151266b87f43411d to your computer and use it in GitHub Desktop.
Save fsouza/4834151266b87f43411d to your computer and use it in GitHub Desktop.
#!/bin/bash -elx
# This script uses the archive-server (https://github.com/tsuru/archive-server)
# to generate archives and deploy applications using them.
#
# It depends on the following environment variables:
#
# - ARCHIVE_SERVER_READ: the base URL that will be sent to the tsuru server,
# is a public URL that will be used to serve the
# archive (for example: http://archive-server:8080)
# - ARCHIVE_SERVER_WRITE: the base URL that will be used to generate the
# archive, it's commonly a private URL (for example:
# http://127.0.0.1:8181)
# - TSURU_HOST: URL to the Tsuru API (for example: http://yourtsuru:8080)
# - TSURU_TOKEN: the token to communicate with the API (generated with
# `tsurud token`, in the server).
while read oldrev newrev refname
do
set +e
echo $refname | grep -v tags/master$ | grep -q /master$
status=$?
set -e
if [ $status = 0 ]
then
COMMIT=${newrev}
fi
done
if [ -z ${COMMIT} ]
then
echo "ERROR: please push to master"
exit 3
fi
wait_archive() {
url="${1}&keep=1"
content_type=`curl -sI $url | grep Content-Type | awk '{print $2}'`
while echo $content_type | grep -v application/x-gzip
do
sleep 1
content_type=`curl -sI $url | grep Content-Type | awk '{print $2}'`
done
}
git_archive_all() {
REV=$1; FILE=$2
TMP_WORK_DIR=$(mktemp -d)
chmod 755 $TMP_WORK_DIR
unset GIT_DIR GIT_WORK_TREE
git clone -q $PWD $TMP_WORK_DIR &> /dev/null
pushd $TMP_WORK_DIR > /dev/null
git config advice.detachedHead false
git checkout $REV > /dev/null
git submodule update --init --recursive > /dev/null
find -name .git -prune -exec rm -rf {} \; > /dev/null
tar zcf /tmp/$FILE .
popd > /dev/null
rm -rf $TMP_WORK_DIR > /dev/null
}
save_archive() {
url="${ARCHIVE_SERVER_WRITE}/"
result=`curl -sN -F archive=@/tmp/${1} $url`
python <<END
import json
print json.loads(u"""${result}""")["id"]
END
}
APP_DIR=${PWD##*/}
APP_NAME=${APP_DIR/.git/}
UUID=`python -c 'import uuid; print uuid.uuid4().hex'`
ARCHIVE_FILE_NAME=${APP_NAME}_${COMMIT}_${UUID}.tar.gz
git_archive_all $COMMIT $ARCHIVE_FILE_NAME
archive_id=`save_archive $ARCHIVE_FILE_NAME`
archive_url="${ARCHIVE_SERVER_READ}/?id=$archive_id"
wait_archive $archive_url
url="${TSURU_HOST}/apps/${APP_NAME}/deploy"
curl -H "Authorization: bearer ${TSURU_TOKEN}" -d "archive-url=${archive_url}&commit=${COMMIT}&user=${TSURU_USER}" -s -N $url | tee /tmp/deploy-${APP_NAME}.log
rm /tmp/${ARCHIVE_FILE_NAME}
tail -1 /tmp/deploy-${APP_NAME}.log | grep -q "^OK$"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment