首页 > 解决方案 > 如何设置 Jenkins 管道以使用未提交到 GitHub 的 secrets.properties 文件

问题描述

我有一个基于 Springboot/Maven 的应用程序,它使用secrets.properties文件来存储令牌。该文件包含一个键/值对作为IEX_CLOUD_TOKEN=MY_TOKEN.

运行我的 Jenkins 管道后,我收到如下所示的错误。它失败是有道理的,因为secrets.properties它不在 GitHub 中。如何设置管道以在应用程序需要时使用我的令牌?

我在 Jenkins 中设置了一个凭证并将其设置KindSecret file. 然后withCredentials我在我的Jenkinsfile. 但是,我仍然收到以下错误消息。

错误信息

context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanDefinitionStoreException: Failed to parse configuration class [edu.bu.cs673.stockportfolio.StockportfolioApplication]; nested exception is java.io.FileNotFoundException: class path resource [secrets.properties] cannot be opened because it does not exist

詹金斯文件

pipeline {
    agent any
    triggers {
        pollSCM '* * * * *' // 5 stars means poll the scm every minute
    }
    tools {
        maven 'Maven 3.6.3'
    }
    options {
        skipStagesAfterUnstable()
    }
    environment {
        IexCloudApiKey=credentials('IEXCloud')
    }
    stages {
        stage('Test') {
            steps {
                withCredentials([file(credentialsId: 'IEXCloud', variable: 'FILE')]) {

                    sh '''
                    cat $FILE > secrets.properties
                    mvn test
                    rm secrets.properties
                    '''
                }
            }
        }
        stage('Build') {
            steps {
                sh 'mvn -B -DskipTests clean package'
            }
            post {
                success {
                    junit 'target/surefire-reports/**/*.xml'
                }
            }
        }
    }
}

标签: mavenjenkinscontinuous-integration

解决方案


首先是关于您的管道的几条评论。

管道重复了很多步骤,因为您知道Maven中的生命周期?如果你打电话mvn compile,然后mvn test你会重复几个步骤,包括compile更糟糕的使用mvn package也重复几个步骤......包括test所以compile首先将其简化为mvn package.

此外,您应该使用在工作区之外完成的凭据设置,如下所示:

withCredentials([file(credentialsId: 'secret', variable: 'FILE')]) {
    dir('subdir') {
      sh 'use $FILE'
    }
}

推荐阅读