How to mask dynamic password which generate to a variable in Jenkins pipeline

Steps:

-> Install the mask password plugin for Jenkins Controller

-> Now go to your pipeline code and the below line in the pipeline

maskPasswords(varMaskRegexes: [], varPasswordPairs: [[password: "$NEW_PASSWORD", var: 'NEW_PASSWORD']])

Note: The password value needs to be in the above format, e.g. ( “$NEW_PASSWORD”) and the var value needs to be your password variable name, e.g. (“NEW_PASSWORD”).

Reason: The mask plugin checks the variable used in the pipeline by var value and masks the password by password value which we dynamically generate.

-> Here NEW_PASSWORD is the password variable which I need to mask, replace it with your value, and save.

-> Here is the pipeline example which adds a user without the shell access in the Linux instance

pipeline {
    agent {
    node {
        label 'gcp'
      }
    }

    stages {
        stage('User Creation') {
            steps {
                script {
                    // Password Generator
                    NEW_PASSWORD = sh(
                        script: 'openssl passwd -crypt password',
                        returnStdout: true
                    ).trim()

                    env.NEW_PASSWORD = NEW_PASSWORD 

                    maskPasswords(varMaskRegexes: [], varPasswordPairs: [[password: "$NEW_PASSWORD", var: 'NEW_PASSWORD']]) {

                    sh '''
                        # User creation
                        useradd -s /sbin/nologin "$NEW_USERNAME"
                        [ $? -eq 0 ] && echo "User has been added to system!" || echo "Failed to add a user!"
 
                        # Setting the password for the user
                        echo "$NEW_USERNAME:$NEW_PASSWORD" | chpasswd
                        echo "User password has been created"

                        # Check if password change was successful
                        if [ $? -eq 0 ]; then
                            echo "Password has been set for the user!"
                        else
                            echo "Failed to set the password."
                        fi
                    ''' 
                    } 
                }
            }
        }
      }
  }

-> Run the pipeline and after the pipeline is completed check the logs, where your password is masked

Join the Conversation

Your email address will not be published. Required fields are marked *