Jenkins管道和Gradle项目,如何使用Jenkins Nexus插件获取GAV属性来部署工件?

时间:2017-10-05 22:06:25

标签: maven jenkins gradle jenkins-pipeline nexus

我最近从Maven转到了Gradle。到目前为止,我的Jenkins声明性管道包括一个阶段,我们生成打包的工件并将其发布到Nexus:

  pipeline {
    ...
    stages {
      stage ('Build Stage') {
        steps {
          ...
          sh "mvn clean deploy"
          ...
        }
      }

这样我们就可以使用我们的构建工具(Maven)使用其中一个插件(maven deploy plugin)来部署工件。使用Nexus Jenkins Plugin,我们可以解除这些对我有用的功能:Gradle负责构建,测试和打包工件,Jenkins Nexus插件会将其上传到Nexus。

重点是,在Jenkins Nexus Plugin documentation之后,我必须使用如下步骤:

nexusPublisher nexusInstanceId: 'localNexus', nexusRepositoryId: 'releases', packages: [[$class: 'MavenPackage', mavenAssetList: [[classifier: '', extension: '', filePath: 'buildmavenCoordinate: [artifactId: 'myproject'/lib/myproject-1.0.0.jar']], , groupId: 'com.codependent.myproject', packaging: 'jar', version: '1.0.0']]]

由于我想生成可重用的管道,我不想在步骤中硬编码以下属性:

  1. 的groupId
  2. 的artifactId
  3. 包装
  4. 版本
  5. 如果我使用Maven,我会使用readMavenPom step from the Pipeline Utility steps plugin将它们传递给nexusPublisher步骤:

    def pom = readMavenPom file: 'pom.xml'
    ...
    nexusPublisher ... mavenCoordinate: [artifactId: pom.artifactId
    ...
    

    我的问题是如何从管道中的Gradle配置中获取这四个参数。

    假设我的build.gradle如下:

    apply plugin: 'java'
    apply plugin: 'eclipse'
    
    sourceCompatibility = 1.8
    
    group = 'com.codependent.myproject'
    version = '1.0.0'
    jar {
        manifest {
            attributes 'Implementation-Title': 'Gradle Quickstart',
                       'Implementation-Version': version
        }
    }
    
    repositories {
        mavenCentral()
    }
    
    dependencies {
        compile group: 'commons-collections', name: 'commons-collections', version: '3.2.2'
        testCompile group: 'junit', name: 'junit', version: '4.+'
    }
    
    test {
        systemProperties 'property': 'value'
    }  
    ...
    

1 个答案:

答案 0 :(得分:0)

你在管道中使用Groovy吗? Gradle不提供解析POM文件的本机支持。我建议你在Groovy中使用XmlSlurper。

如果您的管道在Groovy中,您可以使用以下代码阅读这些属性:

def pom = new XmlSlurper().parse(new File('pom.xml'))
def version = pom.version
def artifactId = pom.artifactId
def groupId = pom.groupId

如果需要,可以直接检查此值打印变量:

println 'my pom version ' + pom.version
println 'my pom version ' + pom.artifactId
println 'my pom version ' + pom.groupId

有关XmlSlurper的更多信息:Official page of XmlSlurper

修改

如果你没有pom文件并且你有build.gradle文件,我建议你阅读这篇文章:

how to read a properties files and use the values in project gradle script?