Jenkins Kubernetes 插件:如何从 Dockerfile 构建映像并在映像内运行步骤

Lar*_*lke 4 jenkins docker kubernetes jenkins-pipeline

我正在使用 Jenkins kubernetes-plugin。是否可以从 Dockerfile 构建 docker 映像,然后在创建的映像中运行步骤?该插件需要在 pod 模板中指定一个映像,因此我的第一次尝试是使用 docker-in-docker 但该步骤docker.image('jenkins/jnlp-slave').inside() {..}失败:

pipeline {
  agent {
    kubernetes {
      //cloud 'kubernetes'
      label 'mypod'
      yaml """
apiVersion: v1
kind: Pod
spec:
  containers:
  - name: docker
    image: docker:1.11
    command: ['cat']
    tty: true
    volumeMounts:
    - name: dockersock
      mountPath: /var/run/docker.sock
  volumes:
  - name: dockersock
    hostPath:
      path: /var/run/docker.sock
"""
    }
  }
  stages {
    stage('Build Docker image') {
      steps {
        git 'https://github.com/jenkinsci/docker-jnlp-slave.git'
        container('docker') {
          sh "docker build -t jenkins/jnlp-slave ."
          docker.image('jenkins/jnlp-slave').inside() {
            sh "whoami"
          }
        }
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

失败:

WorkflowScript: 31: Expected a symbol @ line 31, column 11.
             docker.image('jenkins/jnlp-slave').inside() {
Run Code Online (Sandbox Code Playgroud)

Lar*_*lke 5

正如马特在评论中指出的那样:

pipeline {
  agent {
    kubernetes {
      //cloud 'kubernetes'
      label 'mypod'
      yaml """
apiVersion: v1
kind: Pod
spec:
  containers:
  - name: docker
    image: docker:1.11
    command: ['cat']
    tty: true
    volumeMounts:
    - name: dockersock
      mountPath: /var/run/docker.sock
  volumes:
  - name: dockersock
    hostPath:
      path: /var/run/docker.sock
"""
    }
  }
  stages {
    stage('Build Docker image') {
      steps {
        git 'https://github.com/jenkinsci/docker-jnlp-slave.git'
        container('docker') {
          script {
            def image = docker.build('jenkins/jnlp-slave')
            image.inside() {
              sh "whoami"
            }
          }
        }
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)