check
check

Reputation: 21

How do I set secrets in Jenkins Step

I am looking for a solution to inject secrets only during a Jenkins step:

application.properties:

spring.datasource.username=mySecretValue
spring.datasource.password=mySecretValue
...

Current State:

stage('Test') {
      agent {
          docker {
               image 'myregistry.com/maven:3-alpine'
                    reuseNode true
                }
       }
       steps {
                configFileProvider([configFile(fileId: 'maven-settings-my-services', variable: 'MAVEN_SETTINGS')]) {
                    sh 'mvn -s $MAVEN_SETTINGS verify'
                }
            }
...


Thanks!

Upvotes: 1

Views: 1935

Answers (2)

check
check

Reputation: 21

One way I did it, was to attach the secrets with the credentials-Plugin variable by variable:

 echo 'Attach properties for tests to property file:'
withCredentials([string(credentialsId: 'DB_PW', variable: 'SECRET_ENV')]) {
                sh 'echo spring.mydatabase.password=${SECRET_ENV} >> ./src/main/resources/application.properties'

Instead of "echo", "sed" would also an option to replace the empty value for the key instead of add the property to the end of the file.

The second way I did is to attach a complete property file, instead of a key/value pair. The property file contains all needed properties for the tests:

    echo 'Attach properties file for test runs:'   withCredentials([file(credentialsId: 'TEST_PROPERTIES', variable: 'APPLICATION_PROPERTIES')]) {    dir('$WORKSPACE') {
  sh 'sed s#'/src/main/resources/' application.properties > TEST_PROPERTIES'

In both cases the secrets has to be deleted atter the run, otherwise they can be viewed in plaintext under the Workspace folder.

Upvotes: 1

yong
yong

Reputation: 13712

Option 1) Add a password job parameter for that secret. But the job have to be run manually, because need someone to input the secret.

// write the secret to application.property at any stage that
// prior to test and deployment stage

sh "echo spring.datasource.password=${params.DB_PASSWORD} >> application.property"

Option 2) Add the secret as Jenkins String Text credential. But adding credential needs Jenkins administrator access and also need considering update in future.

stage('test or deployment') {
   environment {
      DB_PASSWORD = credentials('<credential_id_of_the_secret>')
   }
   steps {
      sh "echo spring.datasource.password=${env.DB_PASSWORD} >> application.property" 
   }
}

Upvotes: 1

Related Questions