Getting data from docker MySQL database with Jenkins pipeline and send Email as attachment
In this post, a simple daily data report for one microservice will be created using the Jenkins pipeline.
Prerequisites:
1. Background
This is a special request from the developer team.
We have a web service, which is running in the remote docker cluster.
2. 1 Configure Mattermost Config
3. 2 Create Job
4. 3 Add Build Trigger
For the upper three steps, please check this article: Creating a web service health check with Jenkins pipeline and Mattermost notification
5. 4 Publish Over SSH Config
6. Full script:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 |
pipeline { agent any environment { stageName = "Daily Data Report" matterMostChannel = "#jenkins-job-debug" mysqlContainer = "a33bdcebf6e4" execOutput = "" datePeriod = "" } stages { stage('Load part data') { steps { script { //ae-clip timezone -1 // the day before yesterday 23:00::00 ---- yesterday 23:00::00 def now = new Date() def dateMinusOne = now - 1 dayMinusOne = dateMinusOne.format("yyyy-MM-dd") def dayStart = dayMinusOne + " 00:00:00" def dayEnd = dayMinusOne + " 23:59:59" datePeriod = dayStart + "--" + dayEnd stageName = stageName + " [" + datePeriod + "]" echo "mysql/date: ${mysqlContainer} ${datePeriod}" echo "BEGINBEGINBEGIN" def cmd = """ cd /local/home/mobabel-dev/ucp_bundle && eval "\$(<env.sh)" && cd /local/home/mobabel-dev/docker-stack container_string=`docker ps | grep service-mysql-name` ; container_name=`echo "\$container_string" | cut -c1-12` ; exec_output=`docker exec -i \$container_name mysql -uroot <<< "use databasename;\ select * from my_data where created_date >= '${dayStart}' and created_date <= '${dayEnd}';"` ; if [ -z "\$exec_output" ] then echo "token""==No_data==" else echo "token""BEGINBEGINBEGIN\n""\$exec_output" echo "token""ENDENDEND\n" fi """ sshPublisher( continueOnError: false, failOnError: true, publishers: [ sshPublisherDesc( configName: 'MyServerClient', transfers: [ sshTransfer( execCommand: ''' cd /local/home/mobabel-dev/ucp_bundle && eval "$(<env.sh)" && cd /local/home/mobabel-dev/docker-stack ''' ), sshTransfer( remoteDirectory: 'docker-stack', removePrefix: '', execCommand: cmd ) ], verbose: true ) ] ) } } } stage('CheckLog') { steps { script { def list = manager.build.logFile.readLines() def BeginCount = list.count {it.startsWith("token") && it.contains("BEGINBEGINBEGIN")} def EndCount = list.count {it.startsWith("token") && it.contains("ENDENDEND")} echo("BeginCount: ${BeginCount}/EndCount: ${EndCount}") if (BeginCount == 1 && EndCount == 1){ // enable "staticMethod org.codehaus.groovy.runtime.DefaultGroovyMethods getText java.io.File" // in https://jenkins.server/scriptApproval/ def logContent = manager.build.logFile.text def startIndex = logContent.indexOf('tokenBEGINBEGINBEGIN') + 'tokenBEGINBEGINBEGIN'.length() def endIndex = logContent.indexOf('tokenENDENDEND') def rawOutput = logContent.substring(startIndex, endIndex) //execOutput = rawOutput.replace("\n", "<br/>\n") execOutput = 'Please see attachment.' writeFile file: "dailylog.txt", text: rawOutput } } } } } // Finishing Up Actions post { success { script { notifySucc(stageName, matterMostChannel, execOutput) } } failure { script { notifyError(stageName, matterMostChannel) } } unstable { script { notifyUnstable(stageName, matterMostChannel) } } fixed { script { notifyFixed(stageName, matterMostChannel) } } } } def notifySucc(String stageName = '', String matterMostChannel = '', String execOutput = '') { def message = "$stageName" mattermostSend channel: matterMostChannel, color: "good", message: message emailext ( subject: message, to: "your_mail@mail.com", body: """<p>$stageName':</p> <p>$execOutput</p>""", attachmentsPattern: 'dailylog.txt' ) } def notifyError(String stageName = '', String matterMostChannel = '') { def message = ":rage: $stageName failed, please (<${env.BUILD_URL}| check detail for line id>). | ${env.BUILD_NUMBER} " echo(message) mattermostSend channel: matterMostChannel, color: "danger", message: message emailext ( subject: message, to: "your_mail@mail.com;", body: """<p>$stageName Failed: '${env.JOB_NAME} [${env.BUILD_NUMBER}]':</p> <p>Check console output at "<a href='${env.BUILD_URL}'>${env.JOB_NAME} [${env.BUILD_NUMBER}]</a>"</p>""" ) } def notifyUnstable(String stageName = '', String matterMostChannel = '') { def message = ":warning: $stageName is aborted. | ${env.BUILD_NUMBER} (<${env.BUILD_URL}|Open>)" echo(message) mattermostSend channel: matterMostChannel, color: "warning", message: message } def notifyFixed(String stageName = '', String matterMostChannel = '') { def message = ":white_check_mark: $stageName is returning to health. | ${env.BUILD_NUMBER} (<${env.BUILD_URL}|Open>)" echo(message) mattermostSend channel: matterMostChannel, color: "good", message: message } |
It will capture part of the Jenkins log output and save it into one text file under the Jenkins workshop. Then send an email with this text file as an attachment.
Reference:
Get a job’s console logfile from a Jenkins pipeline
https://medium.com/@gustavo.guss/jenkins-send-email-with-attachment-cec1e052583a