## Generate a key
# openssl rand -base64 741 > mongodb-keyfile
## Create k8s secrets
# kubectl create secret generic mongo-key --from-file=mongodb-keyfile
---
apiVersion: v1
kind: Service
metadata:
name: mongo
labels:
name: mongo
namespace: metacenter
spec:
ports:
- port: 27017
targetPort: 27017
clusterIP: None
selector:
role: mongo
---
apiVersion: apps/v1beta1
kind: StatefulSet
metadata:
name: mongo
namespace: metacenter
spec:
serviceName: "mongo"
replicas: 1
template:
metadata:
labels:
role: mongo
environment: test
spec:
terminationGracePeriodSeconds: 10
containers:
- name: mongo
image: mongo:3.6.9
env:
- name: MY_POD_IP
valueFrom:
fieldRef:
fieldPath: status.podIP
command:
- /bin/sh
- -c
- >
if [ -f /data/db/admin-user.lock ]; then
mongod --bind_ip 127.0.0.1,$(MY_POD_IP) --replSet rs0 --clusterAuthMode keyFile --keyFile /etc/secrets-volume/mongodb-keyfile --setParameter authenticationMechanisms=SCRAM-SHA-1;
else
mongod --auth --bind_ip 127.0.0.1,$(MY_POD_IP);
fi;
lifecycle:
postStart:
exec:
command:
- /bin/sh
- -c
- >
if [ ! -f /data/db/admin-user.lock ]; then
sleep 5;
touch /data/db/admin-user.lock
if [ "$HOSTNAME" = "mongo-0" ]; then
mongo --eval 'db = db.getSiblingDB("admin"); db.createUser({ user: "admin", pwd: "<redacted>", roles: [{ role: "root", db: "admin" }]});';
fi;
mongod --shutdown;
fi;
ports:
- containerPort: 27017
volumeMounts:
- name: mongo-key
mountPath: "/etc/secrets-volume"
readOnly: true
- name: mongo-persistent-storage
mountPath: /data/db
- name: mongo-sidecar
image: cvallance/mongo-k8s-sidecar
env:
- name: MONGO_SIDECAR_POD_LABELS
value: "role=mongo,environment=test"
- name: KUBE_NAMESPACE
value: metacenter
- name: MONGODB_USERNAME
value: <redacted>
- name: MONGODB_PASSWORD
value: <redacted>
- name: MONGODB_DATABASE
value: <redacted>
- name: KUBERNETES_MONGO_SERVICE_NAME
value: mongo
volumes:
- name: mongo-key
secret:
defaultMode: 0400
secretName: mongo-key
volumeClaimTemplates:
- metadata:
name: mongo-persistent-storage
annotations:
volume.beta.kubernetes.io/storage-class: "fast"
spec:
accessModes: [ "ReadWriteOnce" ]
resources:
requests:
storage: 30Gi