Search code examples
jenkinsjenkins-pluginsjenkins-pipeline

How to pass credential binding in environment directive conditionally


This doesn't work:

environment {
    Pass = "${blah == 'yes' ? credentials('somecred') : credentials('otherCred')}"

I can set an env var to credentials() directly but when trying to use the ternary statement inside of the string interpolator like above it doesn't pass the actual creds, it passes a stringified object.

Is there a one-liner for doing this in the environment{} directive?

Jenkins lets you sneak the string interpolator into the environment block to evaluate code, is there another Groovy construct I can use here that will work?


Solution

  • jenkins pipeline dsl makes me weep

    # Define outside of pipeline block
    def MYENV_VAR = somevar == 'yes' ? 'cred-id-1' : 'cred-id-2'
    
    pipeline {
        agent any
    
        environment {
                MYENV = credentials("${MYENV_VAR}")