1

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/"
        }
    }
}
}
Naveen
  • 103
  • 1
  • 12

2 Answers2

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.

apasic
  • 58
  • 6
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.