Search code examples
jenkinsjenkins-pipeline

Hide password in Jenkinsfile


My Jenkinsfile (Declarative Pipeline) content as follows,

pipeline {
    agent any

    stages {
        stage('Checkout') {
            steps {
                git url: '[email protected]:org/repository.git'
            }
        }
        
        stage('Script') {
            steps {
                sh 'script.sh' 
            }
        }
    }   

In my script.sh i have username and password in below format

#!/bin/bash

USERNAME="user"
PASSWD="mypassword-here"

Through Declarative pipeline(Jenkinsfile), I'm trying to hide the password which is in my script.sh file.

In my jenkins Global credentials page, already created kind as Username with password then updated my script.sh as below

#!/bin/bash

USERNAME="user"
PASSWD="$MY_CREDS_PSW"

But it is not working. Can i know how do i add my jenkins Global credentials created as Kind-ID in my script to hide the password?


Solution

  • you can make use of the withCredentials block. Here's an updated version of your Jenkinsfile:

        pipeline {
        agent any
    
        stages {
            stage('Checkout') {
                steps {
                    git url: '[email protected]:org/repository.git'
                }
            }
    
            stage('Script') {
                steps {
                    withCredentials([usernamePassword(credentialsId: 'YOUR_CREDENTIALS_SpeciifcID', passwordVariable: 'PASSWORDD', usernameVariable: 'USERNAME')]) {
                        sh 'script.sh'
                    }
                }
            }
        }
    }
    

    In the above code, replace 'YOUR_CREDENTIALS_SpecificId' with the actual ID of your Jenkins Global credentials that you created. The withCredentials block allows you to inject the username and password from your Jenkins Global credentials into the environment variables USERNAME and PASSWORDD within the scope of the sh step.

    In your script.sh, you van add USERNAME PASSWORD