Abort build after current step is finished

I am using multi branch build with the pipeline described in a Jenkinsfile.
There are few steps in the build:

  • run tests
  • deploy to dev
  • deploy to stage

Is there a way to abort/stop the build after current step is fully executed? For example, while deploy to dev is on going, I would like to schedule to abort after the deployment is fully finished successfully. And it won’t deploy to stage.

I tried to use user prompt (input) with timeout: After timeout, it’ll proceed to the next step. And during timeout, user gets to click Abort. This gives user enough time to abort before the next step starts.

        stage('Proceed to stag?') {
            steps {
                script {
                    try {
                        timeout(time: 4, unit: 'MINUTES') {
                            input(message: 'Go')
                        }
                    } catch (err) {
                        if ('SYSTEM' == err.getCauses()[0].getUser().toString()) {
                            echo('timeout')
                        } else {
                            throw err;
                        }
                    }
                }
            }
        }

But I cannot call err.getCauses() due to security issue:

org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use method org.jenkinsci.plugins.workflow.steps.FlowInterruptedException getCauses

I cannot change security settings in orgs jenkins. And using try-catch like that seems like a wrong approach to what I’m trying to achieve.

Hello,
You need to approve your pendding script.
Navigate to Manage Jenkins > In-process Script Approval to approve your script

P/S: I tried to run your script. It take two time approval