如何在Jenkins pipeline中使用Kubernetes插件的post步骤

4

我尝试使用Jenkins Kubernetes插件中的后续步骤。有人有想法吗?

java.lang.NoSuchMethodError: No such DSL method 'post' found among steps

我的流水线:

podTemplate(
        label: 'jenkins-pipeline',
        cloud: 'minikube',
        volumes: [
                hostPathVolume(mountPath: '/var/run/docker.sock', hostPath: '/var/run/docker.sock'),
        ]) {

    node('jenkins-pipeline') {
        stage('test') {
            container('maven') {
                println 'do some testing stuff'
            }
        }

        post {
            always {
                println "test"
            }
        }
    }
}
2个回答

2
截至目前,Post仅在声明性流水线中受支持。 如果您非常需要使用post,可以查看他们的声明性示例
pipeline {
  agent {
    kubernetes {
      //cloud 'kubernetes'
      label 'mypod'
      containerTemplate {
        name 'maven'
        image 'maven:3.3.9-jdk-8-alpine'
        ttyEnabled true
        command 'cat'
      }
    }
  }
  stages {
    stage('Run maven') {
      steps {
        container('maven') {
          sh 'mvn -version'
        }
      }
    }
  }
}

没有使用post的替代方案是什么? - Ben Keil
可能需要使用try/catch -- 请参考https://jenkins.io/doc/book/pipeline/syntax/#flow-control - mghicks
1
示例中没有展示使用 post {}.. 哦,好的,楼主使用的是脚本式流水线而不是声明式流水线。 - Morgan Christiansson
@mghicks,请展示一下如何在你的例子中使用post。 - Sam
@Sam 抱歉,我现在没有便捷的测试方法,但它应该与 https://www.jenkins.io/doc/book/pipeline/syntax/#post 或你的示例一样。 - mghicks

2
这个例子展示了如何使用Kubernetes插件的post步骤:
pipeline {
  agent {
    kubernetes {
      label "my-test-pipeline-${BUILD_NUMBER}"
      containerTemplate {
        name "my-container"
        image "alpine:3.15.0"
        command "sleep"
        args "99d"
      }
    }
  }
  stages {
    stage('Stage 1') {
      steps {
        container('my-container') {
          sh '''
            set -e
            echo "Hello world!"
            sleep 10
            echo "I waited"

            echo "forcing a fail"
            exit 1
          '''
        }
      }
    }
  }
  post {
    unsuccessful {
      container('my-container') {
        sh '''
          set +e
          echo "Cleaning up stuff here"
        '''
      }
    }
  }
}

这真的有效吗?在我的测试中,k8s代理在阶段结束时被销毁。我无法在后续活动中使用它。 - Laurent Pinson
没事了,我找到了问题所在。如果有人遇到类似的情况:如果你一开始使用的是 'agent none',然后创建了 k8s agent,请确保你的 post activities 在使用 K8s agent 的 stages 正下方,而不是使用 'agent none' 的 stages 下方。 - Laurent Pinson
在我的情况下,代理/容器确实被销毁,但另一个代理/容器会被启动来执行后续步骤。 - Sam

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接