<p>I have a Jenkins pipeline using the kubernetes plugin to run a <a href="https://github.com/docker-library/docker/blob/65fab2cd767c10f22ee66afa919eda80dbdc8872/18.09/dind/Dockerfile" rel="nofollow noreferrer">docker in docker</a> container and build images:</p>

<pre><code>pipeline {
  agent {
    kubernetes {
      label 'kind'
      defaultContainer 'jnlp'
      yaml """
apiVersion: v1
kind: Pod
metadata:
  labels:
    name: dind
... 
</code></pre>

<p>I also have a pool of persistent volumes in the jenkins namespace each labelled <code>app=dind</code>. I want one of these volumes to be picked for each pipeline run and used as <code>/var/lib/docker</code> in my dind container in order to cache any image pulls on each run. I want to have a pool and caches, not just a single one, as I want multiple pipeline runs to be able to happen at the same time. How can I configure this?</p>

<p>This can be achieved natively in kubernetes by creating a persistent volume claim as follows:</p>

<pre><code>apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: dind
spec:
  accessModes:
  - ReadWriteOnce
  resources:
    requests:
      storage: 10Gi
  selector:
    matchLabels:
      app: dind
</code></pre>

<p>and mounting it into the Pod, but I'm not sure how to configure the pipeline to create and cleanup such a persistent volume claim.</p>

dippynark
<p>First of all, I think the way you think it can be achieved natively in kubernetes - wouldn't work. You either have to re-use same PVC which will make build pods to access same PV concurrently, or if you want to have a PV per build - your PVs will be stuck in <code>Released</code> status and not automatically available for new PVCs.</p>
<p>There is more details and discussion available here <a href="https://issues.jenkins.io/browse/JENKINS-42422" rel="nofollow noreferrer">https://issues.jenkins.io/browse/JENKINS-42422</a>.</p>
<p>It so happens that I wrote two simple controllers - automatic PV releaser (that would find and make <code>Released</code> PVs <code>Available</code> again for new PVCs) and dynamic PVC provisioner (for Jenkins Kubernetes plugin specifically - so you can define a PVC as annotation on a Pod). Check it out here <a href="https://github.com/plumber-cd/kubernetes-dynamic-reclaimable-pvc-controllers" rel="nofollow noreferrer">https://github.com/plumber-cd/kubernetes-dynamic-reclaimable-pvc-controllers</a>. There is a full <code>Jenkinsfile</code> example here <a href="https://github.com/plumber-cd/kubernetes-dynamic-reclaimable-pvc-controllers/tree/main/examples/jenkins-kubernetes-plugin-with-build-cache" rel="nofollow noreferrer">https://github.com/plumber-cd/kubernetes-dynamic-reclaimable-pvc-controllers/tree/main/examples/jenkins-kubernetes-plugin-with-build-cache</a>.</p>
