jenkins集成云效发布应用到k8s

1. jenkins部署

 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
#!/bin/bash

ws=$(cd $(dirname $0)/; pwd)
cd $ws

case $1 in

start)
sudo docker run -d \
--name jenkins \
--restart=always \
-v `pwd`/data/jenkins_home:/var/jenkins_home \
-v /etc/localtime:/etc/localtime \
-v /etc/timezone:/etc/timezone \
-p 8080:8080 \
-p 50000:50000 \
--add-host dev-repo.example.io:172.100.100.2 \
jenkins/jenkins:2.507-jdk17
;;

stop)
sudo docker stop jenkins && sudo docker rm jenkins
;;

*)
echo "Usage $0 start|stop"
esac

2. 构建一个golang小程序来提供http接口服务

此应用主要目的是返回对应的云效git仓库地址,以实现通过拉取代码通过ssh协议完成

  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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
package main

import (
	"database/sql"
	"net/http"
	"time"
	"fmt"
	"flag"
	"github.com/gin-gonic/gin"
	_ "github.com/mattn/go-sqlite3"
)

type Server struct {
	ID            int       `json:"id"`
	ServerName    string    `json:"server_name"`
	CodepubURL    string    `json:"codepub_url"`
	CodepubGitURL string    `json:"codepub_git_url"`
	CodepubID     string    `json:"codepub_id"`
	Description   string    `json:"description"`
	CreatedAt     time.Time `json:"created_at"`
	UpdatedAt     time.Time `json:"updated_at"`
}

type Response struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data,omitempty"`
}

var db *sql.DB

func main() {
	var err error
	db, err = sql.Open("sqlite3", "./server.db")
	if err != nil {
		panic(err)
	}

	createTable()

	port := flag.Int("port", 8080, "server port")
	flag.Parse()

	r := gin.Default()

	r.GET("/server", getServer)
	r.POST("/server", createServer)
	r.PUT("/server", updateServer)
	r.DELETE("/server", deleteServer)

	addr := fmt.Sprintf(":%d", *port)
	r.Run(addr)
	//r.Run(":8080")
}

func createTable() {
	sql := `
	CREATE TABLE IF NOT EXISTS servers (
		id INTEGER PRIMARY KEY AUTOINCREMENT,
		server_name TEXT UNIQUE,
		codepub_url TEXT,
		codepub_git_url TEXT,
		codepub_id TEXT,
		description TEXT,
		created_at DATETIME,
		updated_at DATETIME
	);
	`
	_, err := db.Exec(sql)
	if err != nil {
		panic(err)
	}
}

func getServer(c *gin.Context) {
	name := c.Query("name")
	all := c.Query("all")
	onlyName := c.Query("only_name")
	onlyCodepubID := c.Query("only_codepub_id")
	onlyCodepubGitURL := c.Query("only_codepub_git_url")

	if onlyName == "true" {
		rows, err := db.Query("SELECT server_name FROM servers")
		if err != nil {
			c.JSON(http.StatusInternalServerError, Response{Code: 500, Message: err.Error()})
			return
		}
		defer rows.Close()

		var names []string
		for rows.Next() {
			var serverName sql.NullString
			err = rows.Scan(&serverName)
			if err != nil {
				c.JSON(http.StatusInternalServerError, Response{Code: 500, Message: err.Error()})
				return
			}
			if serverName.Valid {
				names = append(names, serverName.String)
			}
		}

		c.JSON(http.StatusOK, Response{Code: 0, Message: "Success", Data: names})
		return
	}

	if all == "true" {
		// 之前的查全部逻辑...
		rows, err := db.Query("SELECT * FROM servers")
		if err != nil {
			c.JSON(http.StatusInternalServerError, Response{Code: 500, Message: err.Error()})
			return
		}
		defer rows.Close()

		var servers []Server
		for rows.Next() {
			var s Server
			var description sql.NullString
			err = rows.Scan(&s.ID, &s.ServerName, &s.CodepubURL, &s.CodepubGitURL, &s.CodepubID, &description, &s.CreatedAt, &s.UpdatedAt)
			if err != nil {
				c.JSON(http.StatusInternalServerError, Response{Code: 500, Message: err.Error()})
				return
			}
			if description.Valid {
				s.Description = description.String
			} else {
				s.Description = ""
			}
			servers = append(servers, s)
		}

		c.JSON(http.StatusOK, Response{Code: 0, Message: "Success", Data: servers})
		return
	}

	if name == "" {
		c.JSON(http.StatusBadRequest, Response{Code: 400, Message: "Missing name parameter"})
		return
	}

	if onlyCodepubID == "true" {
		row := db.QueryRow("SELECT codepub_id FROM servers WHERE server_name = ?", name)
		var codepubID string
		err := row.Scan(&codepubID)
		if err != nil {
			if err == sql.ErrNoRows {
				c.JSON(http.StatusNotFound, Response{Code: 404, Message: "Server not found"})
			} else {
				c.JSON(http.StatusInternalServerError, Response{Code: 500, Message: err.Error()})
			}
			return
		}

		data := map[string]string{
			"codepub_id": codepubID,
		}

		c.JSON(http.StatusOK, Response{Code: 0, Message: "Success", Data: data})
		return
	}

        if onlyCodepubGitURL == "true" {
                row := db.QueryRow("SELECT codepub_git_url FROM servers WHERE server_name = ?", name)
                var codepubGitURL string
                err := row.Scan(&codepubGitURL)
                if err != nil {
                        if err == sql.ErrNoRows {
                                c.JSON(http.StatusNotFound, Response{Code: 404, Message: "Server not found"})
                        } else {
                                c.JSON(http.StatusInternalServerError, Response{Code: 500, Message: err.Error()})
                        }
                        return
                }

                data := map[string]string{
                        "codepub_git_url": codepubGitURL,
                }

                c.JSON(http.StatusOK, Response{Code: 0, Message: "Success", Data: data})
                return
        }



	row := db.QueryRow("SELECT codepub_git_url, codepub_id, codepub_url FROM servers WHERE server_name = ?", name)
	var codepubGitURL, codepubID, codepubURL string
	err := row.Scan(&codepubGitURL, &codepubID, &codepubURL)
	if err != nil {
		if err == sql.ErrNoRows {
			c.JSON(http.StatusNotFound, Response{Code: 404, Message: "Server not found"})
		} else {
			c.JSON(http.StatusInternalServerError, Response{Code: 500, Message: err.Error()})
		}
		return
	}

	data := map[string]string{
		"codepub_git_url": codepubGitURL,
		"codepub_id":      codepubID,
		"codepub_url":     codepubURL,
	}

	c.JSON(http.StatusOK, Response{Code: 0, Message: "Success", Data: data})
}

func createServer(c *gin.Context) {
	var input struct {
		Name          string `json:"name" binding:"required"`
		CodepubGitURL string `json:"codepub_git_url" binding:"required"`
		CodepubID     string `json:"codepub_id" binding:"required"`
		CodepubURL    string `json:"codepub_url" binding:"required"`
	}
	if err := c.ShouldBindJSON(&input); err != nil {
		c.JSON(http.StatusBadRequest, Response{Code: 400, Message: err.Error()})
		return
	}

	now := time.Now()

	_, err := db.Exec(`INSERT INTO servers (server_name, codepub_git_url, codepub_id, codepub_url, created_at, updated_at) 
	VALUES (?, ?, ?, ?, ?, ?)`,
		input.Name, input.CodepubGitURL, input.CodepubID, input.CodepubURL, now, now)
	if err != nil {
		c.JSON(http.StatusInternalServerError, Response{Code: 500, Message: err.Error()})
		return
	}

	c.JSON(http.StatusOK, Response{Code: 0, Message: "Create Success"})
}

func updateServer(c *gin.Context) {
	var input struct {
		Name          string `json:"name" binding:"required"`
		CodepubGitURL string `json:"codepub_git_url" binding:"required"`
		CodepubID     string `json:"codepub_id" binding:"required"`
		CodepubURL    string `json:"codepub_url" binding:"required"`
	}
	if err := c.ShouldBindJSON(&input); err != nil {
		c.JSON(http.StatusBadRequest, Response{Code: 400, Message: err.Error()})
		return
	}

	now := time.Now()

	res, err := db.Exec(`UPDATE servers SET codepub_git_url=?, codepub_id=?, codepub_url=?, updated_at=? WHERE server_name=?`,
		input.CodepubGitURL, input.CodepubID, input.CodepubURL, now, input.Name)
	if err != nil {
		c.JSON(http.StatusInternalServerError, Response{Code: 500, Message: err.Error()})
		return
	}

	rowsAffected, _ := res.RowsAffected()
	if rowsAffected == 0 {
		c.JSON(http.StatusNotFound, Response{Code: 404, Message: "Server not found"})
		return
	}

	c.JSON(http.StatusOK, Response{Code: 0, Message: "Update Success"})
}

func deleteServer(c *gin.Context) {
	name := c.Query("name")
	if name == "" {
		c.JSON(http.StatusBadRequest, Response{Code: 400, Message: "Missing name parameter"})
		return
	}

	res, err := db.Exec("DELETE FROM servers WHERE server_name = ?", name)
	if err != nil {
		c.JSON(http.StatusInternalServerError, Response{Code: 500, Message: err.Error()})
		return
	}

	rowsAffected, _ := res.RowsAffected()
	if rowsAffected == 0 {
		c.JSON(http.StatusNotFound, Response{Code: 404, Message: "Server not found"})
		return
	}

	c.JSON(http.StatusOK, Response{Code: 0, Message: "Delete Success"})
}

3. 新建脚本文件getservice.sh

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
#!/bin/bash

export PATH=/var/jenkins_home/ext/bin:/data/jenkins/data/jenkins_home/ext/bin:$PATH

case $1 in
java)
curl -sSL "http://172.100.100.2:8082/server?only_name=true"  | jq -r '.data.[]' | grep -v "view-"
;;

view)
curl -sSL "http://172.100.100.2:8082/server?only_name=true"  | jq -r '.data.[]' | grep "view-"
;;

all)
curl -sSL "http://172.100.100.2:8082/server?only_name=true"  | jq -r '.data.[]'
;;

*)
echo "usage $0 java|view"
;;

esac

4. 配置jenkins任务

  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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
<?xml version='1.1' encoding='UTF-8'?>
<flow-definition plugin="workflow-job@1520.v56d65e3b_4566">
  <actions>
    <org.jenkinsci.plugins.pipeline.modeldefinition.actions.DeclarativeJobAction plugin="pipeline-model-definition@2.2254.v2a_978de46f35"/>
    <org.jenkinsci.plugins.pipeline.modeldefinition.actions.DeclarativeJobPropertyTrackerAction plugin="pipeline-model-definition@2.2254.v2a_978de46f35">
      <jobProperties/>
      <triggers/>
      <parameters/>
      <options/>
    </org.jenkinsci.plugins.pipeline.modeldefinition.actions.DeclarativeJobPropertyTrackerAction>
  </actions>
  <description>java-allinone-build</description>
  <keepDependencies>false</keepDependencies>
  <properties>
    <hudson.model.ParametersDefinitionProperty>
      <parameterDefinitions>
        <org.biouno.unochoice.ChoiceParameter plugin="uno-choice@2.8.7">
          <name>Server_Name</name>
          <randomName>choice-parameter-16588714714434</randomName>
          <visibleItemCount>1</visibleItemCount>
          <script class="org.biouno.unochoice.model.GroovyScript">
            <secureScript plugin="script-security@1373.vb_b_4a_a_c26fa_00">
              <script>tags = []
text = &quot;/var/jenkins_home/ext/bin/getservice.sh java&quot;.execute().text
text.eachLine {
 line, count -&gt;if (count == 0) {
   tags.push(line+&apos;:selected&apos;) 
}else{
  tags.push(line) 
}}
return tags</script>
              <sandbox>false</sandbox>
            </secureScript>
            <secureFallbackScript plugin="script-security@1373.vb_b_4a_a_c26fa_00">
              <script></script>
              <sandbox>true</sandbox>
            </secureFallbackScript>
          </script>
          <projectName>java-allinone-build</projectName>
          <projectFullName>JAVA/java-allinone-build</projectFullName>
          <choiceType>PT_SINGLE_SELECT</choiceType>
          <filterable>true</filterable>
          <filterLength>1</filterLength>
        </org.biouno.unochoice.ChoiceParameter>
        <org.biouno.unochoice.CascadeChoiceParameter plugin="uno-choice@2.8.7">
          <name>Codepub_Id</name>
          <randomName>choice-parameter-17667421817191</randomName>
          <visibleItemCount>1</visibleItemCount>
          <script class="org.biouno.unochoice.model.GroovyScript">
            <secureScript plugin="script-security@1373.vb_b_4a_a_c26fa_00">
              <script>import java.net.URL
import java.net.HttpURLConnection
import java.io.BufferedReader
import java.io.InputStreamReader
import groovy.json.JsonSlurper

def apiUrl = &quot;http://172.100.100.2:8082/server?name=${Server_Name}&amp;only_codepub_id=true&quot;

def url = new URL(apiUrl)
def connection = url.openConnection() as HttpURLConnection

connection.setRequestMethod(&quot;GET&quot;)
connection.setRequestProperty(&quot;Accept&quot;, &quot;application/json&quot;)
connection.connect()

if (connection.responseCode == 200) {
    def reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))
    StringBuilder response = new StringBuilder()
    String line
    while ((line = reader.readLine()) != null) {
        response.append(line)
    }
    reader.close()

    def branchesJson = new groovy.json.JsonSlurper().parseText(response.toString())

    // 提取分支名称列表
    def codepubId = branchesJson.data.codepub_id

    // 将分支名称作为文本字符串返回,每行一个分支
    return [codepubId] as List&lt;String&gt;

} else {
    // 如果请求失败,返回一个默认值或者错误消息
    return &quot;Failed to fetch branches: ${connection.responseCode} - ${connection.responseMessage}&quot; as List&lt;String&gt;
}</script>
              <sandbox>false</sandbox>
            </secureScript>
            <secureFallbackScript plugin="script-security@1373.vb_b_4a_a_c26fa_00">
              <script></script>
              <sandbox>true</sandbox>
            </secureFallbackScript>
          </script>
          <projectName>java-allinone-build</projectName>
          <projectFullName>JAVA/java-allinone-build</projectFullName>
          <parameters class="linked-hash-map"/>
          <referencedParameters>Server_Name</referencedParameters>
          <choiceType>PT_SINGLE_SELECT</choiceType>
          <filterable>false</filterable>
          <filterLength>1</filterLength>
        </org.biouno.unochoice.CascadeChoiceParameter>
        <org.biouno.unochoice.CascadeChoiceParameter plugin="uno-choice@2.8.7">
          <name>Codepub_Git_URL</name>
          <randomName>choice-parameter-19233489482989</randomName>
          <visibleItemCount>1</visibleItemCount>
          <script class="org.biouno.unochoice.model.GroovyScript">
            <secureScript plugin="script-security@1373.vb_b_4a_a_c26fa_00">
              <script>import java.net.URL
import java.net.HttpURLConnection
import java.io.BufferedReader
import java.io.InputStreamReader
import groovy.json.JsonSlurper

def apiUrl = &quot;http://172.100.100.2:8082/server?name=${Server_Name}&amp;only_codepub_git_url=true&quot;

def url = new URL(apiUrl)
def connection = url.openConnection() as HttpURLConnection

connection.setRequestMethod(&quot;GET&quot;)
connection.setRequestProperty(&quot;Accept&quot;, &quot;application/json&quot;)
connection.connect()

if (connection.responseCode == 200) {
    def reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))
    StringBuilder response = new StringBuilder()
    String line
    while ((line = reader.readLine()) != null) {
        response.append(line)
    }
    reader.close()

    def branchesJson = new groovy.json.JsonSlurper().parseText(response.toString())

    // 提取分支名称列表
    def codepubGitURL = branchesJson.data.codepub_git_url

    // 将分支名称作为文本字符串返回,每行一个分支
    return [codepubGitURL] as List&lt;String&gt;

} else {
    // 如果请求失败,返回一个默认值或者错误消息
    return &quot;Failed to fetch branches: ${connection.responseCode} - ${connection.responseMessage}&quot; as List&lt;String&gt;
}</script>
              <sandbox>false</sandbox>
            </secureScript>
            <secureFallbackScript plugin="script-security@1373.vb_b_4a_a_c26fa_00">
              <script></script>
              <sandbox>true</sandbox>
            </secureFallbackScript>
          </script>
          <projectName>java-allinone-build</projectName>
          <projectFullName>JAVA/java-allinone-build</projectFullName>
          <parameters class="linked-hash-map"/>
          <referencedParameters>Server_Name</referencedParameters>
          <choiceType>PT_SINGLE_SELECT</choiceType>
          <filterable>false</filterable>
          <filterLength>1</filterLength>
        </org.biouno.unochoice.CascadeChoiceParameter>
        <org.biouno.unochoice.CascadeChoiceParameter plugin="uno-choice@2.8.7">
          <name>gitbranch</name>
          <description>git分支选取</description>
          <randomName>choice-parameter-16588716472009</randomName>
          <visibleItemCount>1</visibleItemCount>
          <script class="org.biouno.unochoice.model.GroovyScript">
            <secureScript plugin="script-security@1373.vb_b_4a_a_c26fa_00">
              <script>import java.net.URL
import java.net.HttpURLConnection
import java.io.BufferedReader
import java.io.InputStreamReader
import groovy.json.JsonSlurper

def apiUrl = &quot;https://openapi-rdc.aliyuncs.com/oapi/v1/codeup/organizations/实例ID/repositories/${Codepub_Id}/branches&quot;

def url = new URL(apiUrl)
def connection = url.openConnection() as HttpURLConnection

connection.setRequestMethod(&quot;GET&quot;)
connection.setRequestProperty(&quot;Accept&quot;, &quot;application/json&quot;)
connection.setRequestProperty(&quot;x-yunxiao-token&quot;, &quot;TOKEN&quot;) // ← 修改点
connection.connect()

if (connection.responseCode == 200) {
    def reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))
    StringBuilder response = new StringBuilder()
    String line
    while ((line = reader.readLine()) != null) {
        response.append(line)
    }
    reader.close()

    def branchesJson = new groovy.json.JsonSlurper().parseText(response.toString())

    // 提取分支名称列表
    def branchNames = branchesJson.collect { it.name }

    // 将分支名称作为文本字符串返回,每行一个分支
    return branchNames as List&lt;String&gt;

} else {
    // 如果请求失败,返回一个默认值或者错误消息
    return &quot;Failed to fetch branches: ${connection.responseCode} - ${connection.responseMessage}&quot; as List&lt;String&gt;
}</script>
              <sandbox>false</sandbox>
            </secureScript>
            <secureFallbackScript plugin="script-security@1373.vb_b_4a_a_c26fa_00">
              <script></script>
              <sandbox>true</sandbox>
            </secureFallbackScript>
          </script>
          <projectName>java-allinone-build</projectName>
          <projectFullName>JAVA/java-allinone-build</projectFullName>
          <parameters class="linked-hash-map"/>
          <referencedParameters>Codepub_Id</referencedParameters>
          <choiceType>PT_SINGLE_SELECT</choiceType>
          <filterable>false</filterable>
          <filterLength>1</filterLength>
        </org.biouno.unochoice.CascadeChoiceParameter>
      </parameterDefinitions>
    </hudson.model.ParametersDefinitionProperty>
  </properties>
  <definition class="org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition" plugin="workflow-cps@4106.v7a_8a_8176d450">
    <script>//适用于传统项目(编译时需要选择相应的环境配置)
pipeline {
        agent {
            label &apos;build=dev&apos;
        }

        //全局变量
        environment { 
            //gitee代码仓库地址以及项目名称
         Gitee_Registry_URL= &quot;${env.Codepub_Git_URL}&quot;
         SERVER_NAME= &quot;${env.Server_Name}&quot;
         REGISTRY = &quot;dev-repo.example.io&quot;
         IMAGE_NAME = &quot;${env.Server_Name}&quot;
         TAG = new java.text.SimpleDateFormat(&quot;yyyyMMddHHmmss&quot;).format(new Date())  // 当前时间戳
         K8S_NAMESPACE = &quot;dev&quot;
         DEPLOYMENT_NAME = &quot;${env.Server_Name}&quot;
         GIT_BRANCH=&quot;${env.gitbranch}&quot;
         PORT=&quot;80&quot;
         ENVFILE=&quot;dev&quot;
         TZ = &apos;Asia/Shanghai&apos;
         JAVA_HOME = &quot;/usr/lib/jvm/java-17-openjdk-amd64&quot;
         MAVEN_HOME = &quot;/opt/apache-maven-3.9.9&quot;
         PATH = &quot;$JAVA_HOME/bin:$NODE_HOME/bin:$PATH&quot;
         
        }

    options {
        timestamps() // 启用Timestamper插件
        timeout(time: 10, unit: &apos;MINUTES&apos;)
    }
    
    
    stages {
        stage (&apos;拉取代码&apos;){
            steps {
                dir(&quot;${SERVER_NAME}&quot;){
                echo &quot;开始从 ${Gitee_Registry_URL} 拉取代码...&quot;
                // //清空当前目录
                // deleteDir()
                checkout scmGit(branches: [[name: &quot;*/${GIT_BRANCH}&quot;]], extensions: [], userRemoteConfigs: [[credentialsId: &apos;Pull-Code_Gitee_fandaoshuai&apos;, url: &quot;$Gitee_Registry_URL&quot;]])
                echo &quot;代码同步完成&quot;
            }
            }
        }
        

        stage(&apos;编译打包&apos;){
            steps {
                dir(&quot;${SERVER_NAME}&quot;){
                echo &quot;开始编译&quot;
                  sh &quot;${MAVEN_HOME}/bin/mvn clean install&quot;
            }
            }
        }
        
        
        stage(&apos;制作容器镜像&apos;){
            steps {
                dir(&quot;${SERVER_NAME}&quot;){
                echo &quot;制作容器镜像&quot;
                script {
                    def gitCommitId = sh(script: &apos;git rev-parse --short HEAD&apos;, returnStdout: true).trim()
                    def currentDate = sh(script: &apos;date +%Y%m%d&apos;, returnStdout: true).trim()
                    IMAGE_TAG=&quot;${currentDate}.${gitCommitId}&quot;
                    echo &quot;imgtag:  ${IMAGE_TAG}&quot;

                sh &quot;&quot;&quot;
cat &gt; Dockerfile &lt;&lt;EOF
FROM ${REGISTRY}/eclipse-temurin:17.0.14_7-jdk-noble-01
ENV PYROSCOPE_APPLICATION_NAME=${SERVER_NAME}
ENV PYROSCOPE_SERVER_ADDRESS=http://172.20.118.175:4040
ENV PYROSCOPE_LABELS=&quot;hostname=${SERVER_NAME},version=2.0.0,environment=dev&quot;
ARG ENVFILE
ARG SERVER_NAME
ARG PORT
COPY target/${SERVER_NAME}.jar /${SERVER_NAME}.jar
EXPOSE ${PORT}
CMD java -server -Djava.security.egd=file:/dev/./urandom -javaagent:/tools/pyroscope.jar -XX:MaxRAMPercentage=50 -XX:InitialRAMPercentage=50 -XX:MinHeapFreeRatio=0 -XX:MaxHeapFreeRatio=100 -XX:MaxMetaspaceSize=384m -XX:ReservedCodeCacheSize=256m -XX:+UnlockDiagnosticVMOptions -XX:+UnlockExperimentalVMOptions -Dfile.encoding=utf-8 --add-opens=java.base/java.text=ALL-UNNAMED --add-opens=java.base/java.lang=ALL-UNNAMED --add-opens=java.base/sun.reflect.generics.reflectiveObjects=ALL-UNNAMED --add-opens=java.base/java.math=ALL-UNNAMED --add-opens=java.base/java.util=ALL-UNNAMED --add-opens=java.base/java.util.concurrent=ALL-UNNAMED -jar /${SERVER_NAME}.jar --server.port=${PORT} --spring.profiles.active=${ENVFILE}
EOF
                &quot;&quot;&quot;
                 sh &quot;echo ${IMAGE_TAG} &amp;&amp; docker build . -t ${REGISTRY}/${SERVER_NAME}:${IMAGE_TAG} &amp;&amp; docker push ${REGISTRY}/${SERVER_NAME}:${IMAGE_TAG} &amp;&amp; docker rmi ${REGISTRY}/${SERVER_NAME}:${IMAGE_TAG}&quot;
                }
                }
            }
}
            

        stage(&apos;部署到Kubernetes&apos;) {
            steps {
                script {
                    // 更新 Kubernetes 部署中的镜像
                    sh &quot;&quot;&quot;
                    kubectl set image deployment/${DEPLOYMENT_NAME} ${DEPLOYMENT_NAME}=${REGISTRY}/${IMAGE_NAME}:${IMAGE_TAG} --namespace=${K8S_NAMESPACE}
                    kubectl rollout status deployment/${DEPLOYMENT_NAME} --namespace=${K8S_NAMESPACE}
                    &quot;&quot;&quot;
                }
            }
        }
        
   }
}</script>
    <sandbox>true</sandbox>
  </definition>
  <triggers/>
  <disabled>false</disabled>
</flow-definition>

5. PS

由于云效本身有些仓库的命名不规范以及调用接口可能会触发频率限制,通过自建一个服务管理的程序用于返回项目名称及项目地址 更符合项目命名规范要求.