Search code examples
jenkinsjenkins-pipeline

Jenkins pipeline Post-section doesn't recognize Agent properly


I have the following snippet of my Jenkins Pipeline script:

pipeline{
    
    agent none
    stages {  
    stage('First Stage'){
        agent { label 'AnotherAgent'}
        
        steps {
            ... Doing stuff
        }
    }
    ...More steps...
}

post {
    always{
        agent { label 'AnotherAgent'}
        xunit(tools: [ xUnitDotNet(pattern: 'path/to/logs*.xml') ])
    }
}

But when using this, I get the following error: hudson.AbortException: Attempted to execute a step that requires a node context while ‘agent none’ was specified. Be sure to specify your own ‘node { ... }’ blocks when using ‘agent none’.

Ok... I'll add the node there like this:

always{
    agent { node { label 'AnotherAgent'} }
    xunit(tools: [ xUnitDotNet(pattern: 'path/to/logs*.xml') ])
} 

And now I get this error:

 WorkflowScript: 48: Missing required parameter: "label" @ line 48, column 17.
       agent { node { label 'AnotherAgent'} }

So how can I define an agent in the post-section of the Jenkins Pipeline script? First part before the Post works just fine, but the issue arises in the Post-section.


Solution

  • First of all, you need to specify agent any not none at the top-level of pipeline if you didn't specify agent any in some stage. If so this will be failed and return the error you saw below; hudson.AbortException: Attempted to execute a step that requires a node context while ‘agent none’ was specified. Be sure to specify your own ‘node { ... }’ blocks when using ‘agent none’.

    Then in the post stage, you can define the node name with node(). So here's the full Jenkinsfile you can run

    pipeline{
        
        agent any
        stages {  
        stage('First Stage'){
            agent { label 'AnotherAgent'}
            
            steps {
                ... Doing stuff
            }
        }
        ...More steps...
    }
    
    post {
        always{
            node('AnotherAgent') { // let's stay your node name is "AnotherAgent"
               // run your command
            }
            
        }
    }