如何设置 Jenkins 管道以使用未提交给 GitHub 的 secrets.properties 文件

How to set up a Jenkins pipeline to use a secrets.properties file that isn't committed to GitHub

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

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

我在 Jenkins 中设置了一个凭证并将其 Kind 设置为 Secret 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'
                }
            }
        }
    }
}

首先对您的管道发表一些评论。

管道重复了很多步骤,因为您 know the life cycle 在 Maven 中?如果你调用 mvn compile 然后调用 mvn test 你将重复几个步骤,包括 compile 更糟糕的是使用 mvn package 也会重复几个步骤......包括 testcompile 所以先简化为 mvn package.

此外,您应该使用这样的 setup for credentials to be done outside 工作区:

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