-
Notifications
You must be signed in to change notification settings - Fork 0
/
Jenkinsfile-v1
88 lines (87 loc) · 3.88 KB
/
Jenkinsfile-v1
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
pipeline {
agent any
tools {
nodejs 'nodejs'
}
environment {
MY_IMAGE = 'seiha-react-img'
DOCKER_REGISTRY = 'sovanseyha'
CONTAINER_NAME = 'jenkins-container'
TELEGRAM_BOT_TOKEN = credentials('telegramToken')
TELEGRAM_CHAT_ID = credentials('telegramChatid')
}
stages {
stage('Build') {
steps {
script {
try {
sh "whoami"
sh "npm install"
sh "docker build -t ${MY_IMAGE} ."
currentBuild.result = 'SUCCESS'
sendToTelegram("✅ Build Succeeded for Build #${BUILD_NUMBER}")
} catch (Exception e) {
currentBuild.result = 'FAILURE'
currentBuild.description = e.toString()
def errorLog = sh(script: 'cat ${JENKINS_HOME}/jobs/${JOB_NAME}/builds/${BUILD_NUMBER}/log', returnStdout: true)
sendToTelegram("❌ Build Failed for Build #${BUILD_NUMBER}\nError Message:\n${errorLog}")
throw e // Re-throw the exception to stop the pipeline
}
}
}
}
stage('Test') {
steps {
script {
try {
def status = currentBuild.resultIsBetterOrEqualTo('SUCCESS') ? 'Succeed' : 'Failed'
sendToTelegram("🧪 Testing Status: ${status} for Build #${BUILD_NUMBER}")
} catch (Exception e) {
currentBuild.result = 'FAILURE'
currentBuild.description = e.toString()
sendToTelegram("❌ Testing Failed for Build #${BUILD_NUMBER}\nError Message:\n${e.message}")
throw e
}
}
}
}
stage('Deploy') {
steps {
script {
try {
withCredentials([usernamePassword(credentialsId: 'dockerhub_id', usernameVariable: 'DOCKER_USERNAME', passwordVariable: 'DOCKER_PASSWORD')]) {
def existImageID = sh(script: 'docker ps -aq -f name="${MY_IMAGE}"', returnStdout: true)
echo "ExistImageID:${existImageID}"
if (existImageID) {
echo '${existImageID} is removing ...'
sh 'docker rm -f ${MY_IMAGE}'
} else {
echo 'No existing container'
}
sh "docker run -d -p 3001:80 --name ${MY_IMAGE} -e DOCKER_USERNAME=$DOCKER_USERNAME -e DOCKER_PASSWORD=$DOCKER_PASSWORD ${MY_IMAGE}"
}
def status = currentBuild.resultIsBetterOrEqualTo('SUCCESS') ? 'Succeed' : 'Failed'
sendToTelegram("🚀 Deployment Status: ${status} for Build #${BUILD_NUMBER}")
} catch (Exception e) {
currentBuild.result = 'FAILURE'
currentBuild.description = e.toString()
sendToTelegram("❌ Deployment Failed for Build #${BUILD_NUMBER}\nError Message:\n${e.message}")
throw e
}
}
}
}
}
post {
always {
emailext body: 'Check console output at $BUILD_URL to view the results.', subject: '${PROJECT_NAME} - Build #${BUILD_NUMBER} - $BUILD_STATUS', to: '[email protected]'
}
}
}
def sendToTelegram(message) {
script {
sh """
curl -s -X POST https://api.telegram.org/bot\${TELEGRAM_BOT_TOKEN}/sendMessage -d chat_id=\${TELEGRAM_CHAT_ID} -d parse_mode="HTML" -d text="${message}"
"""
}
}