<p>I have a use case where I need to mount the hostPath to a Pod, now the use case is to mount the container environment's sock file and as in the newer version of kubernetes, we have containerd instead of docker, I want to make this socket mounting dynamic, i.e check if docker socket file exists, mount that otherwise check for containerd socket file and mount that.</p>
<p>currently, I have this</p>
<pre><code>spec:
      volumes:
      - name: ctd-sock
        hostPath:
        path: &quot;/run/containerd/containerd1.sock&quot;
        type: Socket
</code></pre>
<p>I am not sure how to make it dynamic. I checked the <a href="https://kubernetes.io/docs/concepts/storage/volumes/#hostpath" rel="nofollow noreferrer">Official Documentation</a>, didn't find anything there.</p>

Ashwani
<p>I don't think there is a way to conditionally mount a volume using only the pod spec, like you found.  Well there is <code>type: FileOrCreate</code> which is sort of conditional, but I don't think that would apply in your case because it is a socket.</p>
<p>However, if you're willing to do some shell scripting, you might be able to dynamically create your yaml based on what container runtime you detect.</p>
<p>For example:</p>
<pre><code>cr=$(kubectl get node -o=jsonpath={.items[0].status.nodeInfo.containerRuntimeVersion})
if [[ $cr =~ &quot;containerd&quot; ]]; then 
  echo 'Cluster uses containerd'
  # TODO: Create your pod with containerd socket
elif [[ $cr =~ &quot;docker&quot; ]]; then
  echo 'Cluster uses docker'
  # TODO: Create your pod with docker socket
else 
  echo 'Cluster uses something else'
  # TODO: Handle however you want
fi
</code></pre>
<p>Maybe this isn't the pure Kubernetes answer you were hoping for, but practically, it might be your best bet.</p>
<p>If you are looking for something more advanced, you could create a <a href="https://kubernetes.io/docs/concepts/extend-kubernetes/api-extension/custom-resources/" rel="nofollow noreferrer">CRD</a> and <a href="https://kubernetes.io/docs/concepts/architecture/controller/" rel="nofollow noreferrer">controller</a> for this, and instead of creating a pod directly, you would create your CRD.  Then, in your controller, you would make it inspect the cluster and create a pod the way you need it based on the cluster's container runtime.</p>
