Skip to content

Instantly share code, notes, and snippets.

@huygn
Created April 2, 2018 09:13
Show Gist options
  • Save huygn/ea26c077c3ed7610c8d03f7cc124577d to your computer and use it in GitHub Desktop.
Save huygn/ea26c077c3ed7610c8d03f7cc124577d to your computer and use it in GitHub Desktop.
// Template for slack chat msg
def slackBaseMsg = "*${env.JOB_NAME}* <${env.BUILD_URL}|#${env.BUILD_NUMBER}>"
// Base Predix/tmca repo
def projectName = 'ge-pae'
def tmcaBranch = 'develop'
// List of apps
def apps = ['predix-fm-integration']
// AWS uri
def awsURI = '[email protected]'
// Methods for doing things on a remote machine via ssh
// Requires a credentialFile (private key) to perform password-less ssh
def PrepareRemoteCmd = { exe, credentialFile , debug=false ->
def debugFlag = '-v'
if(!debug) { debugFlag = '' }
return "${exe} -i ${credentialFile} ${debugFlag}"
}
def ExecOnRemote = { cmd, remoteURL, credentialFile, debug=false ->
r = PrepareRemoteCmd('ssh', credentialFile, debug)
c = "${r} ${remoteURL} \'${cmd}\'"
sh(c)
}
def CopyToRemote = { source, remoteDest, remoteURL, credentialFile, debug=false ->
r = PrepareRemoteCmd('scp', credentialFile, debug)
c = "${r} ${source} ${remoteURL}:${remoteDest}"
sh(c)
}
// The main Jenkins workflow
node {
// Send Slack msg to inform build started
try {
timeout(time: 30, unit: 'SECONDS') {
slackSend message: "Started ${slackBaseMsg}"
}
} catch (err) {
echo "slackSend Failed: ${err}"
}
timestamps {
catchError {
try {
// Cleanup Git untracked files
sh 'git clean -qdff || exit 0'
// Get current commit hash and save it GIT_COMMIT_CURRENT file
sh 'git rev-parse HEAD > GIT_COMMIT_CURRENT || exit 0'
git_commit_current = readFile('GIT_COMMIT_CURRENT').trim()
} catch (err) {
echo "no git repo found at current dir"
git_commit_current = 0
}
stage 'Pull TMCA repo'
git poll: true, branch: "${tmcaBranch}", url: 'https://github.com/PredixSolutions/predix-tmca-app.git', credentialsId: 'github-dangndq'
// Get new commit hash and save it to GIT_COMMIT_NEW file.
sh 'git rev-parse HEAD > GIT_COMMIT_NEW'
git_commit_new = readFile('GIT_COMMIT_NEW').trim()
// List commits between 2 commit hashes and save them to GIT_CHANGELOG file,
// Slack will use the commit list to send msg to channel.
def git_log = /git log --pretty=format:"\`%h\` %s - %an" --since="$(git show -s --format=%ci $(cat GIT_COMMIT_CURRENT))" --until="$(git show -s --format=%ci $(cat GIT_COMMIT_NEW))" | head -n -1 > GIT_CHANGELOG/
sh (git_log)
git_changes = readFile('GIT_CHANGELOG')
// stage 'Build dummy app'
// sh '''
// docker run --rm \
// -v $(pwd):/tmp \
// -w /tmp/build \
// -e NPM_CONFIG_LOGLEVEL=warn \
// node:5 \
// npm install
// '''
stage 'Build FM apps'
sh '''
docker run --rm \
--net=host \
-v /var/jenkins_home/.m2:/root/.m2 \
-v $(pwd):/tmp \
-w /tmp \
maven:3.3.9-jdk-8 \
sh -c "mvn clean install -DskipITs"
'''
stage 'Build FM-Integration app'
sh '''
docker run --rm \
--net=host \
-v /var/jenkins_home/.m2:/root/.m2 \
-v $(pwd)/predix-fm-integration:/tmp \
-w /tmp \
maven:3.3.9-jdk-8 \
sh -c "mvn dependency:resolve && mvn package"
'''
archive '**/target/*.jar'
stage 'Build UI app'
wrap([$class: 'AnsiColorBuildWrapper', 'colorMapName': 'gnome-terminal']) {
sh '''
docker run --rm \
-u $(id -u):$(id -g) \
-v $(pwd):/tmp \
-w /tmp/predix-fm-ui \
-e NPM_CONFIG_LOGLEVEL=warn \
gnhuy91/nodejs-bower-grunt \
bash -c "npm install \
&& bower install \
&& grunt --force dist"
'''
}
stage 'Tag Docker images'
// append docker image name with Jenkins build tag,
// ie. ge-pae/predix-fm-integration:jenkins-predix-tmca-628
def imageTag = "${env.BUILD_TAG}"
def integration_img
for (app in apps) {
def image = "${projectName}/${app}"
integration_img = "${image}:${imageTag}"
}
currentBuild.result = 'SUCCESS'
stage 'Deploy to EC2'
// Copy .jar files to AWS instance & rebuilding docker images there
withCredentials([[$class: 'FileBinding', credentialsId: 'aws', variable: 'FILE']]) {
def sourceDir = 'predix-fm-integration'
def destDir = '/home/ubuntu/opt/artifacts'
CopyToRemote(
"${sourceDir}/target/*.jar",
destDir + '/target',
awsURI,
'$FILE'
)
CopyToRemote(
"${sourceDir}/.env ${sourceDir}/*.env ${sourceDir}/docker-compose.yml ${sourceDir}/*.sh",
destDir,
awsURI,
'$FILE'
)
CopyToRemote(
"${sourceDir}/Dockerfile",
destDir + '/Dockerfile',
awsURI,
'$FILE'
)
// Start integration_dev app
def startDevCmd = """
cd ${destDir} && \
export INTEGRATION_IMG=${integration_img} && \
export \$(cat dev.env) && \
docker-compose -p dev kill integration && \
docker-compose -p dev rm -f --all && \
docker-compose -p dev up -d --build --remove-orphans
"""
ExecOnRemote(startDevCmd, awsURI, '$FILE')
// Start integration_showcase app
def startShowcaseCmd = """
cd ${destDir} && \
export INTEGRATION_IMG=${integration_img} && \
export \$(cat showcase.env) && \
docker-compose -p showcase kill integration && \
docker-compose -p showcase rm -f --all && \
docker-compose -p showcase up -d --build --remove-orphans
"""
ExecOnRemote(startShowcaseCmd, awsURI, '$FILE')
// Remove old images, only keep 3 latest images
def numImgKeep = 3
def buildPrefix = "jenkins-${env.JOB_NAME}"
cleanImgCmd = /bash -c "docker images --no-trunc --format \"{{.ID}} {{.Tag}}\" | grep ${buildPrefix} | cut -d \" \" -f 1 | awk \"NR > ${numImgKeep} { print }\" | xargs --no-run-if-empty docker rmi -f"/
ExecOnRemote(cleanImgCmd, awsURI, '$FILE')
}
// // cf deploy
// def api = 'https://api.system.aws-usw02-pr.ice.predix.io'
// withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: 'cf_dangndq', usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD']]) {
// sh("cf login -a ${api} " + '-u $USERNAME -p $PASSWORD')
// }
}
// Send Slack chat to inform build status
def color
def additionMsg = "- <${env.BUILD_URL}console|console output> @everyone"
switch (currentBuild.result) {
case 'SUCCESS':
color = 'good'
additionMsg = ''
break
case 'FAILURE':
color = 'danger'
break
case 'UNSTABLE':
color = 'warning'
break
}
try {
timeout(time: 30, unit: 'SECONDS') {
slackSend color: "${color}",
message: """Finished ${slackBaseMsg} - ${currentBuild.result} ${additionMsg}\n${git_changes}"""
}
} catch (err) {
echo "slackSend Failed: ${err}"
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment