'How to check if string exists in array in a Jenkins Declarative pipeline step
I need to check if string exists in an array of strings, in a Jenkins Declarative pipeline step.
I cannot find any documentation on operators, except some groovy docs, which suggest using !in, but that does not work, so not sure if those apply here. This is what I tried and it is not working, !in is not regocnized:
def approvalResult
pipeline {
....
stage('Setup') {
steps {
script {
approvalResult = input message: 'Approve prod deployment',
submitter: '[email protected]',
submitterparameter: ''
echo "Build was approved by ${approvalResult}"
//approvalResult contains string with the user email who clicked approve
if(${approvalResult} !in ['[email protected]','[email protected]']){
error("This user is not approved to deploy to PROD.")
}
}
}
}
}
Solution 1:[1]
A functionally equivalent alternative for you is the contains method belonging to the list type. This will definitely work in Jenkins Pipeline Groovy:
if (!(['[email protected]','[email protected]'].contains(approvalResult))) {
error('This user is not approved to deploy to PROD.')
}
Solution 2:[2]
!in was added only in Groovy 3. Depending on how your Jenkins server and job is configured, your runtime groovy version might be <3. You can find out by:
println GroovySystem.version
Try the generic ! operator:
if(!(${approvalResult} in ['[email protected]','[email protected]'])){
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Matt Schuchard |
| Solution 2 | jingx |
