user3292394
user3292394

Reputation: 649

How to check is Jenkins pram contains a character

I am trying to check if my Jenkins parameter contains a hostname. But when I use Regular Expressions to see if it contains the name it doesn't check.

I would guess I have an error in the way I am checking or how I have it wrapped in brackets.

Below is a sample of what I am working with

        stage('Release  1') {
            when {
                expression { params.SECRET_NAME != "" && params.STAGING_ENV != ("*some.host.name*") }
            }
            steps {
                    echo "Release 1"
                }
        }

        stage('Release 2') {
            when {
                expression {params.STAGING_ENV == ("*some.host.name*")  && params.SECRET_NAME == ("*+*") }
            }
            steps {
                    echo "Release 2"
                }
        }

    }

I want it to skip the stage in my Jenkins pipeline if it does not meet the conditions

Upvotes: 3

Views: 4139

Answers (1)

Dibakar Aditya
Dibakar Aditya

Reputation: 4203

Ok, you need multiple changes here, from inside out:

  1. Replace the * with .*. Simply put, in regex * denotes the same (set) of characters any number of times (abc* matches abccccc), whereas .* denotes any character any number of times (abc.* matches abccccc, abcdefg, abcadkhsdalksd, etc.).
  2. Remove the double quotes " surrounding the regex patterns; lest you want them to be interpreted as string literals.
  3. Wrap the regex patterns within delimiters, usually / to define the string boundary.
  4. The brackets () themselves are optional here.
  5. To match regular expressions, replace the equal operator == with the match operator ==~ (strict), which returns a boolean.
  6. There is no "NOT match" operator in Groovy. To invert the match, you need to invert the result of the entire expression.
  7. If the + in *+*should be a literal, then you must escape it as *\+*.

Stitching these together, your pipeline should look like:

stage('Release  1') {
    when {
        expression {
            params.SECRET_NAME != "" && !(params.STAGING_ENV ==~ /.*some.host.name.*/)
        }
    }
    steps {
        echo "Release 1"
    }
}
stage('Release 2') {
    when {
        expression {
            params.STAGING_ENV ==~ /.*some.host.name.*/  && params.SECRET_NAME ==~ /.*\+.*/
        }
    }
    steps {
        echo "Release 2"
    }
}

Further reading:

  1. http://docs.groovy-lang.org/latest/html/documentation/core-operators.html
  2. http://web.mit.edu/hackl/www/lab/turkshop/slides/regex-cheatsheet.pdf

Upvotes: 2

Related Questions