Lawliet
Lawliet

Reputation: 1592

How do I lock a specific node in jenkins before executing a stage from Jenkins Pipeline script?

I have two nodes added in Jenkins,

- master
- node-1

Here is my pipeline script, I would like to lock all the executors on "node-1" before executing anything on "master"

node("master") {
  stage("stage-1") {
    // here lock node-1 
    //Execute script
  }
}

Is there a way to achieve this? (ie: lock node-1)

Upvotes: 1

Views: 905

Answers (1)

Patrice M.
Patrice M.

Reputation: 4319

My strategy is to mark the node offline as soon as your buyild job catches an executor, and then wait for all the other executors to complete. At this stage, your executor is still active, but the other executors can't get a new build since it's offline, so the node is all for yourself. When you are done, you can markl the node online again. This requires some serious admin approval for the script.

For instance:

    final int sleeptimeSeconds = 10
    final String agentname = 'node-1'
    echo "Waiting for an executor for ${agentname}..."
    node(agentname) {
        try {
            timeout(time: timeoutminutes, unit: 'MINUTES') {
                markAgentOnlineOfOffline(agentname, false)
                sleep 5

                Computer computer = Jenkins.getInstance().getComputer(agentname)
                echo "Waiting for other executors to complete on ${agentname}..."
                while (computer.countBusy() > 1) {
                    sleep sleeptimeSeconds
                }
                echo "Ready to do work on '${agentname}' in exclusive mode..."

                ...
            }
        } catch (e) {
            markAgentOnlineOfOffline(agentname, true)
            throw e
        }
    }

    def markAgentOnlineOfOffline(String nodeName, boolean online) {
        ...
    }

That last function markAgentOnlineOfOffline can be implemented in a logical (e.g. I use the "offline" label myself, which my jobs reject (li.e. the label requirement includes !offline). But you could use the Jenkins api to mark the node truly offline.

Upvotes: 1

Related Questions