You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何向Jenkins传递参数?从同仓库文件传参至Jenkinsfile并打印参数值

从同一GitHub仓库的文件传递参数到Jenkinsfile并打印的方案

我来给你梳理几种可行的方案,都是基于同一GitHub仓库内的文件来传递参数到Jenkinsfile的,你可以根据自己的文件类型选合适的:

1. 从JSON配置文件读取参数

假设你的仓库里有一个config.json配置文件,内容如下:

{
  "app_version": "1.2.3",
  "environment": "production"
}

你可以用jq工具(需要确保Jenkins构建代理上安装了jq)来解析JSON并提取参数,Jenkinsfile示例如下:

pipeline {
  agent any
  stages {
    stage('读取JSON文件中的参数') {
      steps {
        script {
          // 读取并解析config.json,提取app_version字段
          def appVersion = sh(
            script: 'jq -r ".app_version" config.json',
            returnStdout: true
          ).trim()
          
          // 打印获取到的参数值
          echo "从config.json读取到的app_version参数值:${appVersion}"
          
          // 把参数存入环境变量,方便后续阶段使用
          env.APP_VERSION = appVersion
        }
      }
    }
    stage('在后续阶段使用参数') {
      steps {
        echo "后续阶段使用的版本参数:${env.APP_VERSION}"
      }
    }
  }
}

2. 从YAML配置文件读取参数

如果你的配置文件是YAML格式(比如config.yaml),内容如下:

app_version: 1.2.3
environment: production

可以使用yq工具(推荐使用mikefarah/yq版本)来解析,Jenkinsfile示例:

pipeline {
  agent any
  stages {
    stage('读取YAML文件中的参数') {
      steps {
        script {
          def appVersion = sh(
            script: 'yq e ".app_version" config.yaml',
            returnStdout: true
          ).trim()
          
          echo "从config.yaml读取到的app_version参数值:${appVersion}"
          env.APP_VERSION = appVersion
        }
      }
    }
  }
}

3. 从Properties文件读取参数

对于Java风格的Properties文件(比如config.properties),内容如下:

app_version=1.2.3
environment=production

可以直接用Groovy内置的Properties类读取,不需要额外工具:

pipeline {
  agent any
  stages {
    stage('读取Properties文件中的参数') {
      steps {
        script {
          def props = new Properties()
          file('config.properties').withInputStream { stream ->
            props.load(stream)
          }
          def appVersion = props.getProperty('app_version')
          
          echo "从config.properties读取到的app_version参数值:${appVersion}"
          env.APP_VERSION = appVersion
        }
      }
    }
  }
}

4. 从普通文本文件读取单行参数

如果参数是存放在一个纯文本文件里(比如version.txt,内容只有一行1.2.3),读取方式更简单:

pipeline {
  agent any
  stages {
    stage('读取文本文件中的参数') {
      steps {
        script {
          def appVersion = readFile('version.txt').trim()
          echo "从version.txt读取到的版本号:${appVersion}"
          env.APP_VERSION = appVersion
        }
      }
    }
  }
}

注意事项

  • 确保Jenkins构建代理上安装了所需工具(比如jq、yq),如果没有,可以在构建前通过apt-get install jq(Linux)或brew install jq(Mac)安装,或者使用预装了这些工具的容器化代理。
  • 如果目标文件不在仓库根目录,要使用正确的相对路径(比如./configs/config.json)。
  • 读取参数后记得用trim()去除多余的换行符或空格,避免参数值异常。

内容的提问来源于stack exchange,提问作者Joe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:21:47