首页 > 其他分享 >Docker+Jenkins+Pipline如何获取git插件环境变量(提交sha、分支等)以及Jenkinsfile中获取sh执行结果(获取git最近提交信息)

Docker+Jenkins+Pipline如何获取git插件环境变量(提交sha、分支等)以及Jenkinsfile中获取sh执行结果(获取git最近提交信息)

时间:2024-06-15 09:54:14浏览次数:6  
标签:GIT script 获取 git 提交 println def

场景

Docker中部署Jenkins+Pipline流水线基础语法入门:

https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/139672283

上面介绍了环境搭建以及Pipeline的Jenkinsfile的常用写法。

如果需要通过Jenkins插件获取git相关的信息,比如上一次提交的SHA,分支名称等信息,然后

需要输出上一次git提交的message的相关信息,即需要执行git log等的相关sh指令,并获取指令

返回的结果并输出。

注:

博客:
https://blog.csdn.net/badao_liumang_qizhi

实现

1、Jenkinsfile中如何执行Groovy语言脚本

参考官方文档说明:

https://www.jenkins.io/zh/doc/book/pipeline/syntax/

需要添加script块

官方示例:

pipeline {
    agent any
    stages {
        stage('Example') {
            steps {
                echo 'Hello World'

                script {
                    def browsers = ['chrome', 'firefox']
                    for (int i = 0; i < browsers.size(); ++i) {
                        echo "Testing the ${browsers[i]} browser"
                    }
                }
            }
        }
    }
}

Jenkinsfile中使用Groovy的异常处理try-catch官方示例

node {
    stage('Example') {
        try {
            sh 'exit 1'
        }
        catch (exc) {
            echo 'Something failed, I should sound the klaxons!'
            throw
        }
    }
}

2、Jenkinsfile中如何获取Jenkins安装Git插件后相关git信息。

需要参考Git-Plugin官方插件说明文档,直接可通过环境变量获取

https://wiki.jenkins.io/JENKINS/Git-Plugin.html

 

插件所提供的环境变量如下

GIT_COMMIT - SHA of the current
GIT_BRANCH - Name of the remote repository (defaults to origin), followed by name of the branch currently being used, e.g. "origin/master" or "origin/foo"
GIT_LOCAL_BRANCH - Name of the branch on Jenkins. When the "checkout to specific local branch" behavior is configured, the variable is published.  If the behavior is configured as null or **, the property will contain the resulting local branch name sans the remote name.
GIT_PREVIOUS_COMMIT - SHA of the previous built commit from the same branch (not set on first build on a branch)
GIT_PREVIOUS_SUCCESSFUL_COMMIT - SHA of the previous successfully built commit from the same branch (not set on first build on a branch)
GIT_URL - Repository remote URL
GIT_URL_N - Repository remote URLs when there are more than 1 remotes, e.g. GIT_URL_1, GIT_URL_2
GIT_AUTHOR_NAME and GIT_COMMITTER_NAME - The name entered if the "Custom user name/e-mail address" behaviour is enabled; falls back to the value entered in the Jenkins system config under "Global Config user.name Value" (if any)
GIT_AUTHOR_EMAIL and GIT_COMMITTER_EMAIL - The email entered if the "Custom user name/e-mail address" behaviour is enabled; falls back to the value entered in the Jenkins system config under "Global Config user.email Value" (if any)

使用示例:

        stage('获取提交信息') {
            steps {
                script {
                    try {
                        def gitPreviousCommit = env.GIT_PREVIOUS_COMMIT
                        println("gitPreviousCommit: ${gitPreviousCommit}")
                        def gitCommit = env.GIT_COMMIT
                        println("gitCommit: ${gitCommit}")
                        def gitBranch = env.GIT_BRANCH
                        println("gitBranch: ${gitBranch}")
                    } catch (Exception ex) {
                        println("获取提交信息异常: ${ex}")
                    }
                }
            }
        }

3、Pipeline中使用Jenkinsfile获取script块中执行sh的结果

首先git中获取最近一次提交信息的sh指令为

git log -1 --pretty=format:'%h - %an, %ar : %s'

如何在script中获取该指令执行的结果并输出

                        def commit = sh(returnStdout: true, script: "git log -1 --pretty=format:'%h - %an, %ar : %s'").trim()
                        println("获取提交信息: ${commit}")

其中script后面跟的是具体sh指令,其它格式固定,commit是自定义的变量

完整示例:

        stage('获取提交信息') {
            steps {
                script {
                    try {
                        def gitPreviousCommit = env.GIT_PREVIOUS_COMMIT
                        println("gitPreviousCommit: ${gitPreviousCommit}")
                        def gitCommit = env.GIT_COMMIT
                        println("gitCommit: ${gitCommit}")
                        def gitBranch = env.GIT_BRANCH
                        println("gitBranch: ${gitBranch}")
                        def commit = sh(returnStdout: true, script: "git log -1 --pretty=format:'%h - %an, %ar : %s'").trim()
                        println("获取提交信息: ${commit}")
                    } catch (Exception ex) {
                        println("获取提交信息异常: ${ex}")
                    }
                }
            }
        }

完整Jenkinsfile示例:

pipeline {
    agent any
 tools {
        maven 'maven'
        jdk   'jdk'
    }
    stages {
        stage('获取提交信息') {
            steps {
                script {
                    try {
                        def gitPreviousCommit = env.GIT_PREVIOUS_COMMIT
                        println("gitPreviousCommit: ${gitPreviousCommit}")
                        def gitCommit = env.GIT_COMMIT
                        println("gitCommit: ${gitCommit}")
                        def gitBranch = env.GIT_BRANCH
                        println("gitBranch: ${gitBranch}")
                        def commit = sh(returnStdout: true, script: "git log -1 --pretty=format:'%h - %an, %ar : %s'").trim()
                        println("获取提交信息: ${commit}")
                    } catch (Exception ex) {
                        println("获取提交信息异常: ${ex}")
                    }
                }
            }
        }
  stage('编译构建') {
            steps {
                echo '编译构建'
                //sh 'mvn clean package -DskipTests'
            }
        }
    }
 post {
        always {
            echo '构建结束,结果:'
        }
  success {
            echo '构建成功'
        }
  failure {
            echo '构建失败'
        }
    }
}

示例运行结果

 

标签:GIT,script,获取,git,提交,println,def
From: https://www.cnblogs.com/badaoliumangqizhi/p/18249019

相关文章

  • 利用青龙面板自动做京东任务获取京豆,解放双手
     前言通过脚本自动化完成京东的各种小游戏,活动,任务等,赚取京豆红包等奖励,免去手动操作的繁琐,100京豆=1块钱,全自动签到,农场浇水,自动领京豆,简直不要太爽。那么如何实现呢?方法一:可以选择直接上车,登陆后即可实现自动挂机,自动做任务领京豆。点击直接打开登陆后就行了,目前登陆一次......
  • 新网站如何把链接提交给百度搜索引擎
    新网站如何把链接提交给百度搜索引擎 很多新手或者刚接触的人,搭建好了网站,并没有百度蜘蛛或者其他的搜索引擎蜘蛛来抓取爬行,所以对于这样的新站,我们首先的是要提交给百度,不能坐等百度来找我们。工具/原料爱站工具网站链接数据百度站长工具方法......
  • C# 获取路径的方法
    在ASP.NET中专用属性:获取用户信息:Page.User获取服务器电脑名:Page.Server.ManchineName获取客户端电脑名:Page.Request.UserHostName获取客户端电脑IP:Page.Request.UserHostAddress在网络编程中的通用方法:当前电脑名称:System.Net.Dns.GetHostName()根据电脑名取出全部IP......
  • git pull的使用方法
    `gitpull`是Git中的一个常用命令,它结合了`fetch`和`merge`两个操作,用于从远程仓库拉取最新的更改,并将其合并到本地仓库的当前分支中。这个命令可以帮助你保持本地代码与远程仓库同步。###基本语法```bashgitpull[options][<remote>[<refspec>]]```###常见......
  • GIT版本管理规范
    版本管理规范文档编写中1.Git版本管理1.1分支命名先来一张典中典分支生命周期以上生命周期仅作参考,不同开发团队可能有不同的规范,可自行灵活定义。例如我们团队在开发时,至少需要保证以下流程:develop分支和hotfix分支,必须从master分支检出由deve......
  • 基于cJSON及心知天气模块化实现获取城市气象信息(现在、未来)
    V1.02024年6月14日发布于博客园目录序言功能描述运行结果示范注意!代码weather_api.hweather_api.cdemo.ccJSON.hcJSON.c参考链接序言功能描述用于请求心知天气的信息,现在的信息,未来n天的气象信息(免费版仅能3天).使用域名通过TCP连接到心知天气服务器,采用cJSON进......
  • 【Azure Developer】记录一段验证AAD JWT Token时需要设置代理获取openid-configurati
    问题描述如果在使用.NET代码对AADJWTToken进行验证时候,如果遇见无法访问 Unabletoobtainconfigurationfrom:'https://login.partner.microsoftonline.cn/<commonoryourtenantid>/v2.0/.well-known/openid-configuration‘,可以配置 HttpClientHandler.Proxy代理。......
  • 6、Git之团队协作机制
    6.1、团队内协作6.1.1、创建本地库如上图所示,一个名叫刘备的人,在本地电脑中创建了一个项目,并使用git来维护。6.1.2、推送本地库到代码托管中心如上图所示,刘备想让别人也能看到自己本地库中的内容,就通过push命令,将本地库复制上传到代码托管中心,形成远程库。关于代码托......
  • Superset二次开发之基于GitLab OpenAPI 查询项目的提交记录中修改的文件
    背景:Superset二次开发,在处理版本升级的过程中,需要手动迁移代码,如何在Superset项目众多的文件中,记录修改过的文件,迁移代码时只需重点关注这些文件修改的内容即可,但是针对项目中多次的commit信息,每个commit又涉及不同的文件,如何快速梳理出这些二开工作中修改的文件,是我们......
  • git clone github报错解决方法,亲测有效!
    报错如下:gitclonehttps://github.com/pingcap/tidb.gitCloninginto'tidb'...remote:Enumeratingobjects:331426,done.remote:Countingobjects:100%(1769/1769),done.remote:Compressingobjects:100%(1549/1549),done.error:RPCfailed;curl......