【尚硅谷】Jenkins教程(從配置到實戰)

課程鏈接:

01-Jenkins教程簡介_嗶哩嗶哩_bilibili

課程筆記:

https://files.cnblogs.com/files/henuliulei/Jenkins.zip?t=1696162767&download=true

Jenkins

Jenkins,原名 Hudson,2011 年改爲現在的名字。它是一個開源的實現持續集成的軟件工具。

官方網站

https://www.jenkins.io/

jenkins的作用如下圖所示:自動去git上拉取代碼,然後構建打包生成jar包,然後部署。實現持續集成CI,持續部署CD。

 

GitLab安裝使用

官方網站:https://about.gitlab.com/

安裝所需最小配置

內存至少4G

https://docs.gitlab.cn/jh/install/requirements.html

在ssh下安裝

官方安裝文檔:https://gitlab.cn/install/?version=ce

1 安裝依賴

sudo yum install -y curl policycoreutils-python openssh-server perl
sudo systemctl enable sshd
sudo systemctl start sshd

2 配置鏡像

curl -fsSL https://packages.gitlab.cn/repository/raw/scripts/setup.sh | /bin/bash

3 開始安裝

sudo EXTERNAL_URL="http://192.168.44.103" yum install -y gitlab-jh

除非您在安裝過程中指定了自定義密碼,否則將隨機生成一個密碼並存儲在 /etc/gitlab/initial_root_password 文件中(出於安全原因,24 小時後,此文件會被第一次 gitlab-ctl reconfigure 自動刪除,因此若使用隨機密碼登錄,建議安裝成功初始登錄成功之後,立即修改初始密碼)。使用此密碼和用戶名 root 登錄。

gitlab常用命令

gitlab-ctl start                  # 啓動所有 gitlab 組件;
gitlab-ctl stop                   # 停止所有 gitlab 組件;
gitlab-ctl restart               # 重啓所有 gitlab 組件;
gitlab-ctl status                 # 查看服務狀態;
gitlab-ctl reconfigure           # 啓動服務;
vi /etc/gitlab/gitlab.rb         # 修改默認的配置文件;
gitlab-ctl tail                   # 查看日誌;

在docker下安裝

https://docs.gitlab.cn/jh/install/docker.html

安裝所需最小配置

  • 內存至少4G

  • 系統內核至少在3.10以上 uname -r 命令可查看系統內核版本

安裝docker

  1. 更新yum源

yum update

  1. 安裝依賴

yum install -y yum-utils device-mapper-persistent-data lvm2

  1. 添加鏡像

//國外鏡像
yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
//阿里鏡像
https://mirrors.aliyun.com/docker-ce/linux/centos/gpg
yum-config-manager --add-repo http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
  1. 查看源中可使用版本

 yum list docker-ce --showduplicates | sort -r
  1. 安裝指定版本

yum install docker
  1. 配置開機啓動項

systemctl start docker
systemctl enable docker
docker version

使用容器安裝gitlab

1.添加容器

docker run --detach \
 --hostname 192.168.44.103 \
 --publish 443:443 --publish 80:80 \
 --name gitlab \
 --restart always \
 --volume $GITLAB_HOME/config:/etc/gitlab:Z \
 --volume $GITLAB_HOME/logs:/var/log/gitlab:Z \
 --volume $GITLAB_HOME/data:/var/opt/gitlab:Z \
 --shm-size 256m \
registry.gitlab.cn/omnibus/gitlab-jh:latest

2.啓動容器

docker start gitlab

 

3.查看已存在的容器

docker ps -a

4.進入容器

docker exec -it  gitlab /bin/bash

訪問

http://192.168.44.101

當首次運行出現502錯誤的時候排查兩個原因

  1. 虛擬機內存至少需要4g

  2. 稍微再等等刷新一下可能就好了

 

管理員賬號登錄

用戶名:root

密碼存在下面文件中,登錄後需要改密碼不然24小時之後會失效

cat /etc/gitlab/initial_root_password

Jenkins安裝

官方文檔介紹非常詳細

https://www.jenkins.io

安裝需求

機器要求:

256 MB 內存,建議大於 512 MB

10 GB 的硬盤空間(用於 Jenkins 和 Docker 鏡像)

需要安裝以下軟件:

Java 8 ( JRE 或者 JDK 都可以)

Docker (導航到網站頂部的Get Docker鏈接以訪問適合您平臺的Docker下載)

 

安裝JDK

1 檢索可用包

yum search java|grep jdk

2 安裝

yum install java-1.8.0-openjdk

 

首次啓動war包會在/root/.jenkins生成配置文件

待完全啓動成功後 訪問服務器8080端口完成配置

初始化後的密碼:

Jenkins initial setup is required. An admin user has been created and a password generated.
Please use the following password to proceed to installation:

4e67bbe261da476abdc63c5b51311646

This may also be found at: /root/.jenkins/secrets/initialAdminPassword

密碼文件使用後會自動刪除

Maven安裝

官網

https://maven.apache.org/

下載後複製到Jenkins所在服務器解壓縮即可

Jenkins + Git + Maven 自動化部署配置

 

1 Git配置

 

 

2 Maven配置

 

3 Pom.xml配置

 

git安裝

yum install -y git

 

javahome配置(可選)

/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.322.b06-1.el7_9.x86_64


export JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.322.b06-1.el7_9.x86_64
export JRE_HOME=$JAVA_HOME/jre
PATH=$PATH:$JAVA_HOME/bin:$JRE_HOME/bin
export JAVA_HOME JRE_HOME CLASS_PATH PATH

jdk
/etc/alternatives/jre_openjdk
source /etc/profile 立即生效

 

報錯找不到jdk?

默認yum安裝java的時候會顯示安裝的是openjdk1.8 實則實際上只安裝了jre
yum install -y java-devel

Maven阿里雲鏡像

修改/usr/local/maven/conf/settings.xml

 
<?xml version="1.0" encoding="UTF-8"?>

<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.
-->

<!--
 | This is the configuration file for Maven. It can be specified at two levels:
 |
 |  1. User Level. This settings.xml file provides configuration for a single user,
 |                 and is normally provided in ${user.home}/.m2/settings.xml.
 |
 |                 NOTE: This location can be overridden with the CLI option:
 |
 |                 -s /path/to/user/settings.xml
 |
 |  2. Global Level. This settings.xml file provides configuration for all Maven
 |                 users on a machine (assuming they're all using the same Maven
 |                 installation). It's normally provided in
 |                 ${maven.conf}/settings.xml.
 |
 |                 NOTE: This location can be overridden with the CLI option:
 |
 |                 -gs /path/to/global/settings.xml
 |
 | The sections in this sample file are intended to give you a running start at
 | getting the most out of your Maven installation. Where appropriate, the default
 | values (values used when the setting is not specified) are provided.
 |
 |-->
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
  <!-- localRepository
   | The path to the local repository maven will use to store artifacts.
   |
   | Default: ${user.home}/.m2/repository
  <localRepository>/path/to/local/repo</localRepository>
  -->
  <localRepository>${user.home}/.m2/repository</localRepository>
  <!-- interactiveMode
   | This will determine whether maven prompts you when it needs input. If set to false,
   | maven will use a sensible default value, perhaps based on some other setting, for
   | the parameter in question.
   |
   | Default: true
  <interactiveMode>true</interactiveMode>
  -->

  <!-- offline
   | Determines whether maven should attempt to connect to the network when executing a build.
   | This will have an effect on artifact downloads, artifact deployment, and others.
   |
   | Default: false
  <offline>false</offline>
  -->

  <!-- pluginGroups
   | This is a list of additional group identifiers that will be searched when resolving plugins by their prefix, i.e.
   | when invoking a command line like "mvn prefix:goal". Maven will automatically add the group identifiers
   | "org.apache.maven.plugins" and "org.codehaus.mojo" if these are not already contained in the list.
   |-->
  <pluginGroups>
    <!-- pluginGroup
     | Specifies a further group identifier to use for plugin lookup.
    <pluginGroup>com.your.plugins</pluginGroup>
    -->
    <pluginGroup>org.mortbay.jetty</pluginGroup>
  </pluginGroups>

  <!-- proxies
   | This is a list of proxies which can be used on this machine to connect to the network.
   | Unless otherwise specified (by system property or command-line switch), the first proxy
   | specification in this list marked as active will be used.
   |-->
  <proxies>
    <!-- proxy
     | Specification for one proxy, to be used in connecting to the network.
     |
    <proxy>
      <id>optional</id>
      <active>true</active>
      <protocol>http</protocol>
      <username>proxyuser</username>
      <password>proxypass</password>
      <host>proxy.host.net</host>
      <port>80</port>
      <nonProxyHosts>local.net|some.host.com</nonProxyHosts>
    </proxy>
    -->
  </proxies>

  <!-- servers
   | This is a list of authentication profiles, keyed by the server-id used within the system.
   | Authentication profiles can be used whenever maven must make a connection to a remote server.
   |-->
  <servers>
    <!-- server
     | Specifies the authentication information to use when connecting to a particular server, identified by
     | a unique name within the system (referred to by the 'id' attribute below).
     | 
     | NOTE: You should either specify username/password OR privateKey/passphrase, since these pairings are 
     |       used together.
     |
    <server>
      <id>deploymentRepo</id>
      <username>repouser</username>
      <password>repopwd</password>
    </server>
    -->
    
    <!-- Another sample, using keys to authenticate.
    <server>
      <id>siteServer</id>
      <privateKey>/path/to/private/key</privateKey>
      <passphrase>optional; leave empty if not used.</passphrase>
    </server>
    -->
    <server>
        <id>releases</id>
        <username>ali</username>
        <password>ali</password>
      </server>
      <server>
        <id>Snapshots</id>
        <username>ali</username>
        <password>ali</password>
      </server>
  </servers>

  <!-- mirrors
   | This is a list of mirrors to be used in downloading artifacts from remote repositories.
   |
   | It works like this: a POM may declare a repository to use in resolving certain artifacts.
   | However, this repository may have problems with heavy traffic at times, so people have mirrored
   | it to several places.
   |
   | That repository definition will have a unique id, so we can create a mirror reference for that
   | repository, to be used as an alternate download site. The mirror site will be the preferred
   | server for that repository.
   |-->
  <mirrors>
    <!-- mirror
     | Specifies a repository mirror site to use instead of a given repository. The repository that
     | this mirror serves has an ID that matches the mirrorOf element of this mirror. IDs are used
     | for inheritance and direct lookup purposes, and must be unique across the set of mirrors.
     |
    <mirror>
      <id>mirrorId</id>
      <mirrorOf>repositoryId</mirrorOf>
      <name>Human Readable Name for this Mirror.</name>
      <url>http://my.repository.com/repo/path</url>
    </mirror>
     -->
    <mirror>
      <!--This sends everything else to /public -->
      <id>nexus</id>
      <mirrorOf>*</mirrorOf> 
      <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
    </mirror>
    <mirror>
      <!--This is used to direct the public snapshots repo in the 
          profile below over to a different nexus group -->
      <id>nexus-public-snapshots</id>
      <mirrorOf>public-snapshots</mirrorOf> 
      <url>http://maven.aliyun.com/nexus/content/repositories/snapshots/</url>
    </mirror>
    <mirror>
      <!--This is used to direct the public snapshots repo in the 
          profile below over to a different nexus group -->
      <id>nexus-public-snapshots1</id>
      <mirrorOf>public-snapshots1</mirrorOf> 
      <url>https://artifacts.alfresco.com/nexus/content/repositories/public/</url>
    </mirror>
  </mirrors>

  <!-- profiles
   | This is a list of profiles which can be activated in a variety of ways, and which can modify
   | the build process. Profiles provided in the settings.xml are intended to provide local machine-
   | specific paths and repository locations which allow the build to work in the local environment.
   |
   | For example, if you have an integration testing plugin - like cactus - that needs to know where
   | your Tomcat instance is installed, you can provide a variable here such that the variable is
   | dereferenced during the build process to configure the cactus plugin.
   |
   | As noted above, profiles can be activated in a variety of ways. One way - the activeProfiles
   | section of this document (settings.xml) - will be discussed later. Another way essentially
   | relies on the detection of a system property, either matching a particular value for the property,
   | or merely testing its existence. Profiles can also be activated by JDK version prefix, where a
   | value of '1.4' might activate a profile when the build is executed on a JDK version of '1.4.2_07'.
   | Finally, the list of active profiles can be specified directly from the command line.
   |
   | NOTE: For profiles defined in the settings.xml, you are restricted to specifying only artifact
   |       repositories, plugin repositories, and free-form properties to be used as configuration
   |       variables for plugins in the POM.
   |
   |-->
   <profiles> 
    <profile>
      <id>development</id>
      <repositories>
        <repository>
          <id>central</id>
          <url>http://central</url>
          <releases><enabled>true</enabled><updatePolicy>always</updatePolicy></releases>
          <snapshots><enabled>true</enabled><updatePolicy>always</updatePolicy></snapshots>
        </repository>
      </repositories>
     <pluginRepositories>
        <pluginRepository>
          <id>central</id>
          <url>http://central</url>
          <releases><enabled>true</enabled><updatePolicy>always</updatePolicy></releases>
          <snapshots><enabled>true</enabled><updatePolicy>always</updatePolicy></snapshots>
        </pluginRepository>
      </pluginRepositories>
    </profile>
    <profile>
      <!--this profile will allow snapshots to be searched when activated-->
      <id>public-snapshots</id>
      <repositories>
        <repository>
          <id>public-snapshots</id>
          <url>http://public-snapshots</url>
          <releases><enabled>false</enabled></releases>
          <snapshots><enabled>true</enabled><updatePolicy>always</updatePolicy></snapshots>
        </repository>
      </repositories>
     <pluginRepositories>
        <pluginRepository>
          <id>public-snapshots</id>
          <url>http://public-snapshots</url>
          <releases><enabled>false</enabled></releases>
          <snapshots><enabled>true</enabled><updatePolicy>always</updatePolicy></snapshots>
        </pluginRepository>
      </pluginRepositories>
    </profile>
  </profiles>
 
   <activeProfiles>
    <activeProfile>development</activeProfile>
    <activeProfile>public-snapshots</activeProfile>
   </activeProfiles>

  <!-- activeProfiles
   | List of profiles that are active for all builds.
   |
  <activeProfiles>
    <activeProfile>alwaysActiveProfile</activeProfile>
    <activeProfile>anotherAlwaysActiveProfile</activeProfile>
  </activeProfiles>
  -->
</settings>

Jenkins會把拉取構建的jar包發送到指定的服務器上,此時需要指定要發送的服務器的位置,需要進行publish over ssh配置

1 安裝插件

在Configure System菜單裏 往下來

2 添加一臺目標服務器

 

 

 

超時機制

輸出命令時一定要注意不要讓窗口卡主,不然Jenkins會認爲認爲一直沒完成

shell的日誌輸出

nohup java -jar /root/xxoo/demo*.jar >mylog.log 2>&1 &

 

數據流重定向

數據流重定向就是將某個命令執行後應該要出現在屏幕上的數據傳輸到其他地方

標準輸入(stdin):代碼爲0,使用<或<<; 標準輸出(stdout):代碼爲1,使用>或>>; 標準錯誤輸出(stderr):代碼爲2,使用2>或2>>

> 覆蓋寫 >> 追加寫

 

運行前清理

配置殺死之前運行的進程(之前運行的服務,因爲再次運行這個服務,端口會衝突,而且服務版本比較久,所以運行新的服務之前要殺死舊的進程和刪除老文件)

自動化構建(使用gitlab鉤子)教程

 

 訪問這個地址便可以觸發自動化構建

 但是如果換個瀏覽器無法觸發,因爲需要登入纔行,通過安裝下面插件實現匿名觸發調用

需要更新地址如下:

 

 在我們的項目地址下配置鉤子

 設置支持對本地網絡服務請求

 此時,我們推送最新的代碼,便可以觸發項目自動構建。

教程如下

16-GitLab鉤子自動構建項目_嗶哩嗶哩_bilibili

構建新的腳本要刪除舊的腳本和進程,可以在pre steps中配置

 

編寫腳本x.sh

#!/bin/bash

#刪除歷史數據
rm -rf xxoo

appname=$1
#獲取傳入的參數,這個參數是正在跑的進程的名字的部分匹配字符,根據這個參數得到進程。
echo "arg:$1"


#獲取正在運行的jar包pid,這個是模糊匹配
pid=`ps -ef | grep $1 | grep 'java -jar' | awk '{printf $2}'`

echo $pid

#如果pid爲空,提示一下,否則,執行kill命令
if [ -z $pid ];
#使用-z 做空值判斷
        then
                echo "$appname not started"

        else
               kill -9 $pid
                echo "$appname stoping...."
#-w是全值匹配
check=`ps -ef | grep -w $pid | grep java` 
if [ -z $check ];

        then
                echo "$appname pid:$pid is stop"
        else
                echo "$appname stop failed"

fi


fi

幾種構建方式

  • 快照依賴構建/Build whenever a SNAPSHOT dependency is built

    • 當依賴的快照被構建時執行本job

  • 觸發遠程構建 (例如,使用腳本)

    • 遠程調用本job的restapi時執行本job

  • job依賴構建/Build after other projects are built

    • 當依賴的job被構建時執行本job

  • 定時構建/Build periodically

    • 使用cron表達式定時構建本job

  • 向GitHub提交代碼時觸發Jenkins自動構建/GitHub hook trigger for GITScm polling

    • Github-WebHook出發時構建本job

  • 定期檢查代碼變更/Poll SCM

    • 使用cron表達式定時檢查代碼變更,變更後構建本job

19-Poll SCM觸發構建_嗶哩嗶哩_bilibili

 

觸發遠程構建/gitlab上改動自動構建

代碼改動自動可以使用gitlab的webhook回調鉤子調起Jenkins的啓動任務接口

在構建觸發器中配置接口和token

 

 

定時構建

Jenkins cron表達式

標準cron

https://crontab.guru

Jenkins cron不是標準的cron表達式

第一個 * 表示每個小時的第幾分鐘,取值0~59

H * * * *
H:每小時執行一次

第二顆 * 表示小時,取值0~23

* 15 * * * 表示每天下午3點
* 1 * * * 表示每天凌晨1點

第三顆 * 表示一個月的第幾天,取值1~31
* 1 5 * * 表示每月5日凌晨1點

第四顆 * 表示第幾月,取值1~12
* 15 5 1 * 表示每年幾月執行

第五顆 * 表示一週中的第幾天,取值0~7,其中0和7代表的都是週日

“/”

表示每隔多長時間,比如 */10 * * * * 表示 每隔10分鐘

“H”

hash散列值,以job名取值,獲取到以job名爲入參的唯一值,相同名稱值也相同,這個偏移量會和實際時間相加,獲得一個真實的運行時間

意義在於:不同的項目在不同的時間運行,即使配置的值是一樣的,比如 都是15 * * * * ,表示每個小時的第15分鐘開始執行任務,那麼會造成同一時間內在Jenkins中啓動很多job,換成H/15 * * * *,那麼在首次啓動任務時,會有隨機值參與進來,有的會在17分鐘啓動 有的會在19分鐘啓動,隨後的啓動時間也是這個值。這樣就能錯開相同cron值的任務執行了。

H的值也可以設置範圍

 

H * * * *表示一小時內的任意時間

*/10 * * * *每10分鐘

H/10 * * * *每10分鐘,可能是7,17,27,起始時間hash,步長不變

45 3 * * 1-6 每個週一至週六,凌晨3點45 執行1次

45 3-5 * * 1-6 每個週一至週六,凌晨3點45 ,凌晨4點45,凌晨5點45 各執行1次

H(40-48) 3-5 * * 1-6 在40~48之間取值 其他同上

45 3-5/2 * * 1-6 每個週一至週六,凌晨3點45 ,凌晨5點45 各執行1次

45 0-6/2 * * 1-6 * * 1-6 0點開始,每間隔2小時執行一次 0:45、2:45、4:45

源碼變更構建

使用Poll SCM 方式與Build periodically一樣

會主動定期檢查代碼託管服務器上是否有變化,一旦發生變化執行job構建

測試報告郵件通知

使用163免費郵箱發送郵件時注意密碼填認證碼,也就是發送手機短信後給的那個,不要用登錄郵箱的密碼

類似下面。。

KDWJUWDQBWMOYGDC

###

自動化部署到docker容器中

24-自動化部署構建Docker鏡像運行jar_嗶哩嗶哩_bilibili

配置刪除舊文件和服務

 

腳本dockerfile和代碼一起上傳

 構建jar包後,jar包從構建服務器上傳到測試運行服務器上

 同時dockerfile也進行上傳並運行生成鏡像文件並運行

 

 

docker外掛目錄

docker run -d -p 8080:8080 --name demo-out -v /root/jarfile/demo-1-0.0.1-SNAPSHOT.jar:/app.jar openjdk:11 java -jar app.jar

 

打包到容器內

 

  1. 準備一臺測試服務器 docker環境

  2. 準備支持jdk的鏡像

 

FROM openjdk:11
COPY . /usr/src/myapp
WORKDIR /usr/src/myapp
RUN javac Main.java
CMD ["java", "Main"]

 

 

  1. 把jar包打包到容器內

dockerfile

FROM openjdk:11
EXPOSE 8080

WORKDIR /root

ADD jarfile/demo*.jar /root/app.jar
ENTRYPOINT ["java","-jar","/root/app.jar"]

 

打包鏡像

docker build -t demo .

 

配置國內鏡像

修改/etc/docker/daemon.json文件,沒有的話創建一個

寫入

{
  "registry-mirrors": [
      "https://ustc-edu-cn.mirror.aliyuncs.com",
      "http://hub-mirror.c.163.com",
      "https://registry.aliyuncs.com"
  ]
}

重啓服務

systemctl daemon-reload
systemctl restart docker
 

Jenkins集羣/併發構建

 

集羣化構建可以有效提升構建效率,尤其是團隊項目比較多或是子項目比較多的時候,可以併發在多臺機器上執行構建。

 

 

流水線 pipeline

流水線既能作爲任務的本身,也能作爲Jenkinsfile

使用流水線可以讓我們的任務從ui手動操作,轉換爲代碼化,像docker的dockerfile一樣,從shell命令到配置文件,更適合大型項目,可以讓團隊其他開發者同時參與進來,同時也可以編輯開發Jenkinswebui不能完成的更復雜的構建邏輯,作爲開發者可讀性也更好。

 

 

完整語法

5個必備的組成部分

pipeline:整條流水線
agent:指定執行器
stages:所有階段
stage:某一階段,可有多個
steps:階段內的每一步,可執行命令
 

測試腳本

基礎框架

pipeline {
    agent any

    stages {
        stage('拉取代碼') {
            steps {
            
                echo '拉取代碼完成'
               
            }

        }
        stage('執行構建') {
            steps {
                echo '執行構建完成'


            }

        }
    }
    
    post {
        
        always {
            
            echo "完成"
            
        }
        
        failure {
            
            echo "失敗"
        }
    }
}

階段視圖 Stage View

blue ocean可視化界面

全新的流水線控制ui,可重複執行某階段代碼

插件中心搜索blue ocean安裝即可

post

流水線完成後可執行的任務

  • always 無論流水線或者階段的完成狀態。

  • changed 只有當流水線或者階段完成狀態與之前不同時。

  • failure 只有當流水線或者階段狀態爲"failure"運行。

  • success 只有當流水線或者階段狀態爲"success"運行。

  • unstable 只有當流水線或者階段狀態爲"unstable"運行。例如:測試失敗。

  • aborted 只有當流水線或者階段狀態爲"aborted "運行。例如:手動取消。

agent

可以指定執行節點

label 指定運行job的節點標籤

any 不指定,由Jenkins分配

pipeline {
    agent {
        node {
            label "jenkins-02"
        }
        
    }

    stages {
        stage('拉取代碼') {
            steps {
          
                sh """
                    sleep 10
                            
                   """

                echo '拉取代碼完成'
               
            }

        }
        stage('執行構建') {
            steps {
                echo '執行構建完成'


            }

        }
    }
    
    post {
        
        always {
            
            echo "完成"
            
        }
        
        failure {
            
            echo "失敗"
        }
    }
}

pipeline中執行自動化構建部署

 

pipeline {
    agent any

    tools {
        
        maven "maven3"
        
    }
    stages {
        stage("拉取代碼") {
            steps {
                
                
                git branch: 'main', credentialsId: 'gitlab', url: 'http://192.168.44.103/root/java-project.git'
                echo '拉取成功'
            }
        }

        stage("執行構建") {
            steps {
                
            //    sh "mvn --version"
                sh """ 
                cd demo-1
                
                mvn clean package
                """
                
                echo '構建完成'
            }

        }
        
        
        stage("clean test server"){
            
            steps{
                
sshPublisher(publishers: [sshPublisherDesc(configName: 'testserver', transfers: [sshTransfer(cleanRemote: false, excludes: '', execCommand: '''rm -rf *

docker stop demo
docker rm demo
docker rmi demo
''', execTimeout: 120000, flatten: false, makeEmptyDirs: false, noDefaultExcludes: false, patternSeparator: '[, ]+', remoteDirectory: '', remoteDirectorySDF: false, removePrefix: '', sourceFiles: '/root')], usePromotionTimestamp: false, useWorkspaceInPromotion: false, verbose: false)])
            }
        }
        
        
        
        
        
        stage("發送jar包到測試服務器") {
            steps {
                
                sshPublisher(publishers: [sshPublisherDesc(configName: 'testserver', transfers: [sshTransfer(cleanRemote: false, excludes: '', execCommand: '', execTimeout: 120000, flatten: false, makeEmptyDirs: false, noDefaultExcludes: false, patternSeparator: '[, ]+', remoteDirectory: '/jarfile', remoteDirectorySDF: false, removePrefix: 'demo-1/target', sourceFiles: '**/demo*.jar'), sshTransfer(cleanRemote: false, excludes: '', execCommand: '''docker build -t demo .
docker run -d -p 8080:8080 --name demo demo''', execTimeout: 120000, flatten: false, makeEmptyDirs: false, noDefaultExcludes: false, patternSeparator: '[, ]+', remoteDirectory: '/', remoteDirectorySDF: false, removePrefix: 'demo-1/docker', sourceFiles: 'demo-1/docker/dockerfile')], usePromotionTimestamp: false, useWorkspaceInPromotion: false, verbose: false)])
                
                
                echo 'jar send over!'
            }

        }

    }
}

聲明式流水線

好處

  • 更像是在Jenkins web ui中的操作

  • 可讀性比較高

  • 可以使用blue ocean自動生成

  • 支持語法檢查

壞處

  • 代碼邏輯能力比腳本式弱,不能完成特別複雜的任務

 

腳本式流水線

好處

  • 更少的代碼和弱規範要求

  • 更靈活的自定義代碼操作

  • 不受約束,可以構建特別複雜的工作流和流水線

壞處

  • 讀寫對編程要求比較高

  • 比聲明式流水線代碼更復雜

  •  

     

     

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章