Doctor
Doctor

Reputation: 7966

Need a working Kubectl binary inside an image

My goal is to have a pod with a working Kubectl binary inside.

Unfortunatly every kubectl image from docker hub I booted using basic yaml resulted in CrashLoopbackOff or else.

Has anyone got some yaml (deployment, pod, etc) that would get me my kubectl ?


I tried a bunch of images with this basic yaml there:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: kubectl-demo
  labels:
    app: deploy
    role: backend
spec:
  replicas: 1
  selector:
    matchLabels:
      app: deploy
      role: backend
  template:
    metadata:
      labels:
        app: deploy
        role: backend
    spec:
      containers:
      - name: kubectl-demo
        image: <SOME_IMAGE>
        ports:
        - containerPort: 80

Thx

Upvotes: 2

Views: 3517

Answers (2)

suren
suren

Reputation: 8786

Or, you can do this. It works in my context, with kubernetes on VMs, where I know where is kubeconfig file. You would need to make the necessary changes, to make it work in your environment.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: kubectl
spec:
  replicas: 1
  selector:
    matchLabels:
      role: kubectl
  template:
    metadata:
      labels:
        role: kubectl
    spec:
      containers:
      - image: viejo/kubectl
        name: kubelet
        tty: true
        securityContext:
          privileged: true
        volumeMounts:
        - name: kube-config
          mountPath: /root/.kube/
      volumes:
      - name: kube-config
        hostPath:
          path: /home/$USER/.kube/
      affinity:
        nodeAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
            nodeSelectorTerms:
            - matchExpressions:
              - key: node-role.kubernetes.io/master
                operator: Exists
      tolerations:
      - effect: NoSchedule
        key: node-role.kubernetes.io/master
        operator: Exists

This is the result:

$ kubectl get po
NAME                      READY   STATUS    RESTARTS   AGE
kubectl-cb8bfc6dd-nv6ht   1/1     Running   0          70s
$ kubectl exec kubectl-cb8bfc6dd-nv6ht -- kubectl get no
NAME                     STATUS   ROLES    AGE   VERSION
kubernetes-1-17-master   Ready    master   16h   v1.17.3
kubernetes-1-17-worker   Ready    <none>   16h   v1.17.3

Upvotes: 2

acid_fuji
acid_fuji

Reputation: 6853

As Suren already explained in the comments that kubectl is not a daemon so kubectl will run, exit and cause the container to restart.

There are a couple of workarounds for this. One of these is to use sleep command with infinity argument. This would keep the Pod alive, prevent it from restarting and allow you to exec into it.

Here`s an example how to do that:

spec:
 containers:
 - image: bitnami/kubectl
   command:
   - sleep 
   - "infinity"
   name: kctl

Let me know if this helps.

Upvotes: 1

Related Questions