How to overwrite file in pods container in Kubernetes deployment file?

11/30/2020

I want to overwrite the file on the pod container. Right now I have elasticsearch.yml at location /usr/share/elasticsearch/config.

I was trying to achieve that with initContainer at kubernetes deployment file, so I added something like:

        - name: disabled-the-xpack-security
          image: busybox
          command: 
          - /bin/sh 
          - -c 
          - |
            sleep 20
            rm /usr/share/elasticsearch/config/elasticsearch.yml 
            cp /home/x/IdeaProjects/BD/infra/istio/kube/elasticsearch.yml /usr/share/elasticsearch/config/
          securityContext:
            privileged: true

But this doesn't work, error looks like:

rm: can't remove '/usr/share/elasticsearch/config/elasticsearch.yml': No such file or directory
cp: can't stat '/home/x/IdeaProjects/BD/infra/istio/kube/elasticsearch.yml': No such file or directory

I was trying to use some echo "some yaml config" >> elasticsearch.yml, but this kind of workarounds doesn't work, because I was able to keep proper yaml formatting.

Do you have any suggestions, how can I do this?

-- Ice
elasticsearch
kubernetes

2 Answers

11/30/2020

As stated by Arman in the comments, you can create a ConfigMap with the contents of /home/x/IdeaProjects/BD/infra/istio/kube/elasticsearch.ymland mount it as a volume in the deployment.

To create the config map from your file you can run:

kubectl create configmap my-es-config --from-file=/home/x/IdeaProjects/BD/infra/istio/kube/elasticsearch.yml

This will create a ConfigMap inside your kubernetes cluster with the yaml file.

You can then use that and add the volume mount to your deployment as:

  containers:
    - name: elasticsearch
      image: k8s.gcr.io/busybox
      .
      .
      .
      volumeMounts:
      - name: config-volume
        mountPath: /usr/share/elasticsearch/config/
  volumes:
    - name: config-volume
      configMap:
        name: my-es-config

Notes

  • It is recommended to create your ConfigMap as yaml as well. More information here
  • Mounting a configmap directly on /usr/share/elasticsearch/config/, will replace everything inside that path and place the config file from the configmap. If that causes an issue, you might want to mount it at another location and then copy it.
-- Hazim
Source: StackOverflow

3/31/2021

Note if you don't want to override everything in the mounted directory you could mount the file only using "subPath" in whatever directory you want.

https://kubernetes.io/docs/concepts/storage/volumes/#using-subpath

-- ThaSami
Source: StackOverflow