求可在Jenkins中创建掩码密码对的有效Groovy脚本
Fix for Jenkins Mask Password Pair Groovy Script
Let's break down why your original script wasn't working, then fix it up properly:
What went wrong in your code
- You created a new instance of
MaskPasswordsConfiginstead of modifying the existing global singleton (which is what Jenkins actually uses for its configuration) - You didn't add the password pair to the existing list of global pairs
- No output statements were included, so you couldn't see if the script ran successfully
- You didn't trigger a Jenkins configuration reload to ensure changes take effect
Corrected Groovy Script
import com.michelin.cio.hudson.plugins.maskpasswords.MaskPasswordsConfig import com.michelin.cio.hudson.plugins.maskpasswords.MaskPasswordsBuildWrapper.VarPasswordPair // Get the actual global MaskPasswords configuration singleton def maskPasswordsConfig = MaskPasswordsConfig.getInstance() def existingPairs = maskPasswordsConfig.getGlobalVarPasswordPairs() // Create your new password pair def newPwdPair = new VarPasswordPair("PWD", "myPassword") // Check if the variable already exists to avoid duplicates def exists = existingPairs.any { it.variable == newPwdPair.variable } if (!exists) { existingPairs.add(newPwdPair) maskPasswordsConfig.setGlobalVarPasswordPairs(existingPairs) maskPasswordsConfig.save() // Force Jenkins to reload its configuration Jenkins.instance.save() println "Successfully added password pair: ${newPwdPair.variable}" println "Total global password pairs now: ${existingPairs.size()}" } else { println "Password pair for variable '${newPwdPair.variable}' already exists!" }
Key Improvements
- Uses the existing global config singleton (
MaskPasswordsConfig.getInstance()) instead of creating a new unused instance - Adds duplicate check to avoid adding the same variable multiple times
- Includes
printlnstatements so you can see clear feedback in the Jenkins Script Console - Calls
Jenkins.instance.save()to ensure the configuration changes are persisted and reloaded immediately - Properly updates the existing list of password pairs instead of replacing the config entirely
How to test
- Go to Jenkins → Manage Jenkins → Script Console
- Paste the corrected script and run it
- You should see success/duplicate messages in the console output
- Verify the password pair was added by checking Manage Jenkins → Configure System → Mask Passwords section
内容的提问来源于stack exchange,提问作者mweish
相关产品推荐
相关产品推荐

