使用Git中的代码运行Jenkins管道

J.D*_*Doe 20 git groovy jenkins jenkins-plugins jenkins-pipeline

我想在jenkins中使用git中的git管道脚本

#!groovy
pipeline {
    agent any

    stages {
        stage('Build') {
            steps {
                echo 'Building..'
            }
        }
        stage('Test') {
            steps {
                echo 'Testing..'
            }
        }
        stage('Deploy') {
            steps {
                echo 'Deploying....'
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我设置了Repository URL,在"Additional Behaviors"下添加了"Check out to a sub directory"并在那里写了我的子目录.

在"Script-Path"中我写道:mysubdirectory/Jenkinsfile

当我尝试运行它时,我得到以下错误:

java.io.FileNotFoundException
    at jenkins.plugins.git.GitSCMFile$3.invoke(GitSCMFile.java:167)
    at jenkins.plugins.git.GitSCMFile$3.invoke(GitSCMFile.java:159)
    at jenkins.plugins.git.GitSCMFileSystem$3.invoke(GitSCMFileSystem.java:162)
    at org.jenkinsci.plugins.gitclient.AbstractGitAPIImpl.withRepository(AbstractGitAPIImpl.java:29)
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.withRepository(CliGitAPIImpl.java:71)
    at jenkins.plugins.git.GitSCMFileSystem.invoke(GitSCMFileSystem.java:158)
    at jenkins.plugins.git.GitSCMFile.content(GitSCMFile.java:159)
    at jenkins.scm.api.SCMFile.contentAsString(SCMFile.java:338)
    at org.jenkinsci.plugins.workflow.cps.CpsScmFlowDefinition.create(CpsScmFlowDefinition.java:101)
    at org.jenkinsci.plugins.workflow.cps.CpsScmFlowDefinition.create(CpsScmFlowDefinition.java:59)
    at org.jenkinsci.plugins.workflow.job.WorkflowRun.run(WorkflowRun.java:262)
    at hudson.model.ResourceController.execute(ResourceController.java:97)
    at hudson.model.Executor.run(Executor.java:415)
Finished: FAILURE
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

如何从git正确运行Jenkins脚本?

小智 24

要从Git repo成功运行Jenkinsfile,Jenkinsfile应该可以在主目录路径中使用,但不能在子目录中使用.例如:

.
??? .setting
??? project
??? Jenkinsfile
Run Code Online (Sandbox Code Playgroud)

Jenkinsfile不应该在子目录中.

  • 除非你没有选择`Lightweight checkout`(取消选中),那么你可以将`Jenkinsfile`放在子目录中 (13认同)

Rob*_*les 5

Jenkins在寻找管道脚本时会进行2次检查.使用git,第一个通常是轻量级结账,只能获取Jenkins文件,而不是整个回购,但它是2个单独的结账.第二个结账是运行Jenkinsfile的真实结账.

它进行2次检查的原因是因为它必须首先查看Jenkins文件以查看您要执行的操作并验证语法等.如果您在脚本中跳过SCM签出,以便以后或以不同方式执行此操作,那么它需要知道不要做"真正的"结账.就此而言,理论上你可以从一个仓库中取出你的Jenkins文件,跳过SCM结账,然后拉出一个完全不同的仓库(或分支或标签)并针对它进行构建,但是使用第一个结账时的Jenkins文件.

因此,通过告诉Jenkins查看Jenkinsfile的子目录,您告诉它在原始检出中的某个地方查找实际上不存在的内容,因为您的Jenkins文件实际上位于您的git仓库的根目录中.

当第二个签出完成到子目录中时,您需要在Jenkins文件中考虑这一点,因为Jenkinsfile从工作区的根目录运行.您需要设置目录即dir("mysubdirectory"){},以查找构建文件等.