Home > database >  Jenkins declarative pipeline: if-else statement inside agent directive
Jenkins declarative pipeline: if-else statement inside agent directive

Time:09-09

I've tried to use different agent for different environments (dev/prod) using if-else inside agent directive. But I'm getting errors if I use the below pipeline script. Any help is much appreciated!!

pipeline {
agent {
    if (env.ENVIRONMENT == 'prod') {
        label {
            label "EC2-1"
            customWorkspace "/home/ubuntu/eks-prod-backend/"
        }
    }
    else if (env.ENVIRONMENT == 'dev') {
         label {
            label "EC2-2"
            customWorkspace "/home/ubuntu/eks-dev-backend/"
        }
    }
}
}

CodePudding user response:

This is the approach I would suggest. Define a variable before the "pipeline" block, for example:

def USED_LABEL = env.ENVIRONMENT == 'prod' ? "EC2-1" : "EC2-2"
def CUSTOM_WORKSPACE = env.ENVIRONMENT == 'prod' ? "/home/ubuntu/eks-prod-backend/" : "/home/ubuntu/eks-dev-backend/"

Then, just use it like this:

pipeline {
agent {
    label USED_LABEL
    customWorkspace CUSTOM_WORKSPACE
}

}

I am not sure if label inside label is needed, but you hopefully get the point. Use variables specified before the pipeline execution.

CodePudding user response:

Maybe something like this could help you in case you have only two environments ?

pipeline {
   agent {
        label {
            label env.ENVIRONMENT == 'prod' ? "EC2-1" : "EC2-2"
            customWorkspace env.ENVIRONMENT == 'prod' ? "/home/ubuntu/eks-prod-backend/" : "/home/ubuntu/eks-dev-backend/"
        }
    }
    stages {
        stage("Build") {
            steps {
                echo "Hello, World!"
            }
        }
    }
}

Otherwise, you can check this thread, this will perhaps help you.

  • Related