skip to Main Content

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/"
        }
    }
}
}

2

Answers


  1. 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.

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search