Skip to content

Instantly share code, notes, and snippets.

@okram999
Last active April 12, 2019 04:57
Show Gist options
  • Save okram999/a325b0048dc7f691f1d6e974e274b08d to your computer and use it in GitHub Desktop.
Save okram999/a325b0048dc7f691f1d6e974e274b08d to your computer and use it in GitHub Desktop.
Get Config
//This pipeline script will perform sf:retrive, checkin code to vcs & create a PR automatically
//excuse my indentations - this was written in a hurry
/*
Author: Niristotle Okram
*/
import groovy.json.JsonSlurperClassic
import groovy.json.*
node('master') {
println "Selected default/source branch: $default_branch"
println "User input for commit message in git: $commit_msg"
println "sf server URL selected: $sf_url"
println "credentialsId selected: $credentialsId"
println "Git repo for the build: $gitrepo"
println "PR endpoint for the build: $PR_endPoint"
try{
//delete workspace
deleteDir()
time_stamp = sh (returnStdout: true, script: 'date "+%Y%m%d_%H%M%S"').trim()
println "The time stamp for this build is: $time_stamp"
stage('tools') {
antHome = tool 'default-ant'
nodeHome = tool 'nodejs814'
jdk = tool name: 'JAVA1.8'
env.PATH="${env.PATH}:${nodeHome}/bin:${antHome}/bin"
env.JAVA_HOME = "${jdk}"
//env.LD_LIBRARY_PATH = "${env.LD_LIBRARY_PATH}:/opt/rh/rh-ruby24/root/usr/lib64/"
}
//checkout repository with the default branch
stage('CodeCheckout') {
checkout([$class: 'GitSCM', branches: [[name: "*/$default_branch"]], doGenerateSubmoduleConfigurations: false, extensions: [], submoduleCfg: [],
userRemoteConfigs: [[credentialsId: 'okram999ssh',url: "$gitrepo"]]])
}
stage('createBranch'){
withEnv(["time=${time_stamp}"]){
sh '''
echo "Value of time_stamp set as env variable is: $time"
git branch
git fetch origin
git checkout $default_branch
echo "checked out $default_branch"
git checkout -b configChanges/${default_branch}_"$time"
echo "checked out a new branch: configChanges/${default_branch}_$time"
echo "Printing the git branch output: "
git branch
'''
}
}
stage('getCode') {
withCredentials([usernamePassword(credentialsId: "$credentialsId", passwordVariable: 'sf_pass', usernameVariable: 'sf_user')]) {
sh 'ant -f build/build.xml getCode -Dsfdc.serverurl=$sf_url -Dsfdc.username=$sf_user -Dsfdc.password=$sf_pass'
}
}
stage('PushChanges'){
withEnv(["time=${time_stamp}"]){
sh '''
git config user.name jenkinsSvcAcc
git config user.email [email protected]
# add, commit and push changes
filelist=`git status -s`
echo filelist
if [ -n "$filelist" ]; then
git add src/*
git commit -a -m "$commit_msg"
returnval=`git push origin configChanges/${default_branch}_"$time"`
if [ -z $returnval ]; then
exit 0;
else
exit 1;
fi
else
echo '**** Nothing to commit ****'
exit 0
fi
'''
}
}
stage('CreatePR') {
withEnv(["time=${time_stamp}"]){
withCredentials([usernamePassword(credentialsId: "$pat_credentialsId", passwordVariable: 'tfs_pat', usernameVariable: 'tfs_user')]) {
println "Creating a PR for the new branch: configChanges/${default_branch}_$time back to the default/sourcebranch: ${default_branch}"
//tfs_user is nokram and my PAT - personal access token
jsonResponse = sh(script: """
curl --silent -X POST -k -u $tfs_user:$tfs_pat -H "Content-Type: application/json" -d '{"sourceRefName": "refs/heads/configChanges/${default_branch}_$time", "targetRefName": "refs/heads/$default_branch", "title": "PR created via job# ${env.BUILD_NUMBER}", "description": "PR created via job# ${env.BUILD_NUMBER}"}' https://okram999.visualstudio.com/sfdc-test/_apis/git/repositories/cc36e63a-3adc-4a38-8474-eb48877d832f/pullrequests?api-version=4.1
""", returnStdout: true).trim()
//console log the json response
println "${jsonResponse}"
//Read the json and check for the key, this is to find any error during the Automatic PR creation
//json = new JsonSlurperClassic().parseText(jsonResponse)
//if( json.keySet().contains( 'stackTrace' ) ) {
//exit 1; //break the build
}
}
}
stage('success_notify'){
//post(1, 6, 3, 9);
//Send slack notification
//slackSend channel: '#devops_ci-cd', color: '#55FF33', message: "The jenkins job for sf:retrive job: ${env.JOB_NAME} for the source: <git repo here>, completed successfully & ready for code review. The job can be accessed here: ${env.BUILD_URL}"
}
}
catch(err){
//post(1, 6, 3, 9);
currentBuild.result = 'FAILURE'
println "there was a failure"
//send slack notification
//slackSend channel: '#devops_ci-cd', color: '#FF3C33', message: "The jenkins job for sf:retrive job: ${env.JOB_NAME} for the source: <git repo here>, encountered a FAILURE. The job can be accessed here: ${env.BUILD_URL}"
}
}
def fetchBuildDetailsForDashboard() {
url1 = env.BUILD_URL + 'wfapi/describe'
jsonResponse = sh(script: 'echo "{\\"wfapi\\":`curl --silent --user us_svc_jenkinsCI:4266cfedd0720dab4a3744eccfaac3a4 '+url1+'`}"', returnStdout: true).trim()
echo "Fetched build details: "// + jsonResponse
//echo prettyPrint(jsonResponse)
return new JsonSlurperClassic().parseText(jsonResponse)
}
def post(stageNumber, applicationId, automationProcessId, automationToolId) {
def buildDetails = fetchBuildDetailsForDashboard()
desc = buildDetails.wfapi.stages[stageNumber].name
print "desc: " + desc;
startTime = buildDetails.wfapi.stages[stageNumber].startTimeMillis
print "startTime: " + startTime;
end_millisec = buildDetails.wfapi.stages[stageNumber].durationMillis
print "end_millisec: " + end_millisec;
end_time = startTime + end_millisec;
print "end_time: " + end_time;
startTime=sh returnStdout: true, script: "ruby build/getTimeStamp.rb $startTime"
print startTime;
endTime=sh returnStdout: true, script: "ruby build/getTimeStamp.rb $end_time"
print endTime;
sh returnStdout: true, script: """curl -H "Content-Type: application/json" -X POST -d \'{"ApplicationId": "$applicationId","AutomationProcessId": "$automationProcessId","AutomationToolId": "$automationToolId","Description": "$desc","Version": "$default_branch.${env.BUILD_NUMBER}","Cycle": "${env.BUILD_NUMBER}","StartDateTime": "$startTime","EndDateTime": "$endTime","Metadata": "{$desc}"}\' https://stg-devopsmetricsservice.azurewebsites.net/api/metrics/submit"""
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment