Michael
Michael

Reputation: 591

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

I have a Springboot/Maven based application that uses a secrets.properties file to store tokens. The file contains a key/value pair as IEX_CLOUD_TOKEN=MY_TOKEN.

After running my Jenkins pipeline, I get the error shown below. It makes sense that it's failing because secrets.properties is not in GitHub. How can I set up the pipeline to use my token when it's needed by the application?

I set up a credential in Jenkins and set it's Kind to Secret file. I then added a withCredentials script to my Jenkinsfile. However, I still get the error message below.

Error Message

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

Jenkinsfile

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'
                }
            }
        }
    }
}

Upvotes: 0

Views: 1530

Answers (1)

khmarbaise
khmarbaise

Reputation: 97399

First several comments about your pipeline.

The pipeline duplicates a lot of steps because you know the life cycle in Maven? If you call mvn compile and afterwards mvn test you will repeat several steps including compile even worse using mvn package also repets several steps...including test and compile so first simplify it to mvn package.

Furthermore you should use a setup for credentials to be done outside the workspace like this:

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

Upvotes: 2

Related Questions