1. Pipeline用到的语法: Groovy
2. 全局变量查看地址:
${YOUR_JENKINS_URL}/pipeline-syntax/globals
Pipelines由多个step组成,当一个step运行成功时继续运行下一个步骤。 当任何一个step执行失败时,Pipeline 的执行结果也为失败。
超时、重试、完成时动作相关文档: https://www.jenkins.io/zh/doc/pipeline/tour/running-multiple-steps/#%E8%B6%85%E6%97%B6%E9%87%8D%E8%AF%95%E5%92%8C%E6%9B%B4%E5%A4%9A
3. 明确环境变量设置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
// 镜像版本根据日期时间命名
def createVersion() {
return new Date().format('yyyyMMddHHmm')
}
environment {
// NAMESPACE对应镜像仓库中的命名空间
NAMESPACE = ''
IMAGE_NAME = ''
ARTIFACT_BASE = ''
ARTIFACT_IMAGE = "${ARTIFACT_BASE}/${NAMESPACE}/${IMAGE_NAME}"
_VERSION = createVersion()
}
|
4. pull代码,相关变量会在新建构建时指定(页面操作)
1
2
3
4
5
6
7
8
9
10
11
12
|
stages {
stage('检出') {
steps {
checkout([
$class: 'GitSCM', branches: [[name: env.GIT_BUILD_REF]],
userRemoteConfigs: [[
url: env.GIT_REPO_URL,
credentialsId: env.CREDENTIALS_ID
]]
])
}
}
|
5. npm构建
1
2
3
4
5
6
7
8
9
|
stage('构建') {
steps {
echo '构建中...'
sh 'npm install'
sh 'npm run build'
echo '构建完成,开始收集构建产物.'
sh 'ls'
}
}
|
6. mvn构建
1
2
3
4
5
6
7
|
stage('构建') {
steps {
echo '构建中...'
sh 'mvn deploy -Dmaven.test.skip=true -s ./settings-tmp.xml'
echo '构建完成.'
}
}
|
生成settings-tmp.xml文件
stage('生成Setting.xml') {
steps {
echo '开始生成settings.xml...'
writeFile(file: 'settings-tmp.xml', text: '''
<settings>
<servers>
<server>
.............
''')
echo '生成settings.xml完成'
}
}
打包镜像并推送到制品库,注意42行copy的文件
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
|
stage('打包镜像并推送到制品库') {
steps {
echo '生成nginx.conf.'
writeFile(file: 'nginx.conf', text: '''
user nginx;
worker_processes 1;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main \'$remote_addr - $remote_user [$time_local] "$request" \'
\'$status $body_bytes_sent "$http_referer" \'
\'"$http_user_agent" "$http_x_forwarded_for"\';
access_log /var/log/nginx/access.log main;
keepalive_timeout 65;
server {
listen 80;
server_name localhost;
location / {
root /app/;
index index.html;
try_files $uri $uri/ /index.html;
}
}
}
''')
echo '生成nginx.conf.完成'
writeFile(file: 'Dockerfile', text: '''
FROM nginx
RUN mkdir -p /app
COPY nginx.conf /etc/nginx/nginx.conf
COPY ./dist /app
EXPOSE 80
''')
echo '生成DockerFile.完成,开始构建镜像'
sh 'ls'
echo '当前版本:${_VERSION}'
script {
docker.withRegistry("https://${ARTIFACT_BASE}", "credentials") {
docker.build("${ARTIFACT_IMAGE}:${_VERSION}").push()
echo '打包镜像完成.'
}
}
}
}
|