Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Create post-recive hook in Atlassian Stash that notifys Jenkins on push
#!/bin/bash
# Create git hook on stash server
# Exit script on error
set -e
# Define the function that renders super awesome header
renderHeader () {
HEADER=$1
printf "\n\n"
printf "$HEADER"
printf "\n************************************************************************************\n"
}
createJenkinsFile() {
echo "#!/bin/bash
# Notify Jenkins on commits
# Repo name
REPOSITORY_BASENAME=$1/
# Project name
REPOSITORY_PROJECTNAME=$2.git
# Base url for jenkins git plugin
BASEURL=http://<jenkins-url>/git/notifyCommit?url=http://<stash-url>/scm/
NOTIFY_URL=\$BASEURL\$REPOSITORY_BASENAME\$REPOSITORY_PROJECTNAME
echo Notifying Jenkins
curl \$NOTIFY_URL > /dev/null 2>&1" > 10_jenkins
}
### Input ###
REPOSITORY_BASENAME=$1
REPOSITORY_PROJECTNAME=$2
renderHeader "Starting jenkins git hook job for repository: $REPOSITORY_PROJECTNAME in project: $REPOSITORY_BASENAME."
### 1 ###
renderHeader "Checkout repository and create new branch."
rm -rf /tmp/hooks
mkdir -p /tmp/hooks/
cd /tmp/hooks/
git clone ssh://git@<stash-url>:7999/$REPOSITORY_BASENAME/$REPOSITORY_PROJECTNAME.git
cd $REPOSITORY_PROJECTNAME
git checkout -b $REPOSITORY_PROJECTNAME
git push origin $REPOSITORY_PROJECTNAME
### 2 ###
renderHeader "Finding repository number."
# Find repository number
REPOSITORY_NUMBER=$(ssh <username>@<stash-server> "find /data/atlassian/stash/data/repositories/. -name *${REPOSITORY_PROJECTNAME}* -print | cut -d/ -f8")
echo "Repository number for $REPOSITORY_PROJECTNAME is: $REPOSITORY_NUMBER"
### 3 ###
renderHeader "Creating git hook and copy to server."
cd /tmp/hooks/
createJenkinsFile $REPOSITORY_BASENAME $REPOSITORY_PROJECTNAME
HOOK_FILENAME=10_jenkins
ssh <username>@<stash-server> "cd /data/atlassian/stash/data/repositories/$REPOSITORY_NUMBER/hooks/post-receive.d/;rm -f $HOOK_FILENAME 10_custom"
# Copy hooks to server
scp $HOOK_FILENAME <username>@<stash-server>:/data/atlassian/stash/data/repositories/$REPOSITORY_NUMBER/hooks/post-receive.d/$HOOK_FILENAME
# Run the script to the sandbox
ssh <username>@<stash-server> "cd /data/atlassian/stash/data/repositories/$REPOSITORY_NUMBER/hooks/post-receive.d/;chmod 777 $HOOK_FILENAME"
### 4 ###
renderHeader "Remove branch and temp folder."
cd /tmp/hooks/$REPOSITORY_PROJECTNAME
git checkout master
git branch -D $REPOSITORY_PROJECTNAME
git push origin --delete $REPOSITORY_PROJECTNAME
rm -rf /tmp/hooks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment