Kubernetes: Mount a file in your Pod using a ConfigMap

Lately I’ve been learning Go and this week I started a side project named kube-sherlock . The purpose of this small program is to list any pod that does not have the labels that your organization requires.

For kube-sherlock I created a dockerfile were both the program (kube-sherlock) and the default configuration (config.yaml) are placed in the app folder:

 1FROM golang:1.11.5 AS build
 2WORKDIR /src
 3ADD go.mod go.sum ./
 4RUN go get -v
 5ADD kube-sherlock.go config.yaml ./
 6RUN CGO_ENABLED=0 GOOS=linux go build -a -ldflags '-w'
 7
 8FROM alpine:3.7
 9COPY --from=build src/config.yaml app/config.yaml
10COPY --from=build src/kube-sherlock app/kube-sherlock
11WORKDIR /app
12CMD ./kube-sherlock
13
14# Metadata
15ARG BUILD_DATE
16ARG VCS_REF
17LABEL org.label-schema.build-date=$BUILD_DATE \
18    org.label-schema.name="kube-sherlock" \
19    org.label-schema.description="Check if labels are applied to your containers" \
20    org.label-schema.url="https://github.com/cmendible/kube-sherlock" \
21    org.label-schema.vcs-ref=$VCS_REF \
22    org.label-schema.vcs-url="https://github.com/cmendible/kube-sherlock" \
23    org.label-schema.schema-version="0.1"

So what if you want to replace the default configuration?

You can achieve this with the help of a ConfigMap, creating a new config.yaml with your custom values:

 1apiVersion: v1
 2kind: ConfigMap
 3metadata:
 4  name: sherlock-config
 5  namespace: default
 6data:
 7  config.yaml: |
 8    namespaces:
 9      - default
10    labels:
11      - "app"
12      - "owner"    

Note: I’m using the name of the file as the key.

And then create a pod definition, referencing the ConfigMap:

 1apiVersion: v1
 2kind: Pod
 3metadata:
 4  name: kube-sherlock
 5spec:
 6  serviceAccountName: kube-sherlock
 7  containers:
 8    - name: kube-sherlock
 9      image: cmendibl3/kube-sherlock:0.1
10      volumeMounts:
11      - name: config-volume
12        mountPath: /app/config.yaml
13        subPath: config.yaml
14  volumes:
15    - name: config-volume
16      configMap:
17        name: sherlock-config
18  restartPolicy: Never

Note: the volume references the ConfigMap (sherlock-config), the volume mount specifies the mountPath as the file you want to replace (/app/config.yaml) and the subPath property is used to reference the file by key (config.yaml)

Hope it helps.

Learn More

Storage options for applications in Azure Kubernetes Service (AKS)


NetConf Barcelona - Decoupling your Application with .NET Core, Azure and Events
Meetup MadridDotNet - El estado del ecosistema del desarrollador por @cmendibl3
comments powered by Disqus