首页 > 解决方案 > 如何找出 Jenkins 克隆我的仓库的位置

问题描述

当 Jenkins 在我的服务器中克隆我的仓库时,它将项目放在哪里?在构建之后,它会自动删除所有内容,还是我应该在我的 Jenkinsfile 中添加一些东西来做到这一点?

我正在尝试使用以下方法列出文件:

pipeline {
    agent any

    stages {
        stage('just testing') {
            steps {
                ls -l
            }
        }
    }
}

但它返回无效的语法。我也试过了sh "ls -l"

非常感谢。

标签: jenkins

解决方案


当您运行 Jenkinsfile 并且它是从源存储库中获取时,Jenkins 会自动为该作业动态创建一个工作区,并且默认情况下它会将您项目中的任何其他文件放入该工作区。

在您的示例中,您使用了“agent any”,然后在您的阶段使用 Linux 特定命令(如“sh 'ls -l”)列出文件。首先要注意的是,“agent any”可以在 Jenkins 服务器上配置的任何从属服务器上运行,因此它可能在 Linux 或 Windows 从属服务器上运行,具体取决于配置。因此,如果尝试在 Windows 从站上运行,“sh”步骤可能会失败。您可以使用带有标签的代理来更具体地选择这样的节点/从站(可用的标签取决于您的 Jenkins 从站配置):

agent {
    label "LINUX"
}

构建后,它不会自动删除所有内容,因为它会为 Jenkins 主服务器上的每个作业构建保留工作区。您可以通过 2 种方式解决此问题:

1)使用管道中的选项部分来丢弃旧版本:

  options {
    // Keep 4 builds maximum
    buildDiscarder(logRotator(numToKeepStr: '4'))
  }

2)使用后处理程序“always”部分进行清理:

  post {
    always {
      deleteDir()
    }
  }

这是一个可能有助于您入门的管道:

pipeline {

  agent any

  options {
    buildDiscarder(logRotator(numToKeepStr: '4'))
  }

  stages {

    stage('List files in repo on Unix Slave') {

      when {
        expression { isUnix() == true }
      }

      steps {      
        echo "Workspace location: ${env.WORKSPACE}"    
        sh 'ls -l'
      }
    }

    stage('List files in repo on Windows Slave') {

      when {
        expression { isUnix() == false }
      }

      steps {      
        echo "Workspace location: ${env.WORKSPACE}"  
        bat 'dir'
      }
    }
  }

  post {
    always {
      deleteDir()
    }
  }
}

这是我在编辑了一些 Git 喋喋不休后得到的输出:

Pipeline] node
Running on master in /var/jenkins_home/jobs/macg33zr/jobs/testRepo/branches/master/workspace
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Declarative: Checkout SCM)
Cloning the remote Git repository
Cloning with configured refspecs honoured and without tags
Cloning repository https://github.com/xxxxxxxxxx

[Pipeline] }
[Pipeline] // stage
[Pipeline] withEnv
[Pipeline] {
[Pipeline] stage
[Pipeline] { (List files in repo on Unix Slave)
[Pipeline] isUnix
[Pipeline] echo
Workspace location: /var/jenkins_home/jobs/macg33zr/jobs/testRepo/branches/master/workspace
[Pipeline] sh
[workspace] Running shell script
+ ls -l
total 8
-rw-r--r-- 1 jenkins jenkins 633 Oct  1 22:07 Jenkinsfile
-rw-r--r-- 1 jenkins jenkins  79 Oct  1 22:07 README.md
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (List files in repo on Windows Slave)
Stage 'List files in repo on Windows Slave' skipped due to when conditional
[Pipeline] isUnix
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Declarative: Post Actions)
[Pipeline] deleteDir
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline

推荐阅读