The mechanism you should follow to allow Kubernetes to maintain line breaks in a ConfigMap, so that it actually shows newlines in a file, rather than \n, when it gets written in a pod is to have the ConfigMap created with a literal block scalar (|).
This is how you need to do it so that it works:
1. Use Literal Block Scalar (|) in YAML
Making use of | as a separator should normally preserve new lines. However, the system of Kubernetes can be seen to disrupt the data when it receives it from the pod. This was the problem.
Thus the ConfigMap should be specified like this in YAML:
yaml
codeapiVersion:v1
kind:ConfigMap
metadata:
name:example-config
data:
my-data.txt:|
some = foo
foo = some
2. Ensure No Extra Characters or Quotes
The correct approach is to avoid single or double quotes around your text as they might be parsed incorrectly or quote you have not intended. By executing the | operation, the multiline data is processed only as itself.
3. Mount the ConfigMap as a Volume
If you do not have a ConfigMap mounted as a volume already, make sure the ConfigMap is represented as a volume inside the pod. This seems to be quite a useful option when comparing to using ENV variables. There is a need to preserve the original form of the data, hence accessing it as environment variables is not a good choice.
Here is an example of pod spec:
yaml
apiVersion:v1
kind:Pod
metadata:
name:example-pod
spec:
containers:
-name:example-container
image:alpine
command: [ "sleep", "3600" ]
volumeMounts:
-name:config-volume
mountPath:/etc/config
volumes:
-name:config-volume
configMap:
name:example-config
Through /etc/config/my-data.txt the developer should check the result, and it should be totally in the nature of the text, instead of \n.
4. Verify Encoding
If all the above-mentioned options do not help, then try this one. Make sure that neither your editor nor YAML processor converts real newlines into \n. These tools sometimes can make this mistake in the case of improper configurations on an editor or CI pipeline.