apiVersion: v1
kind: Secret
metadata:
  name: mongodb-secret
type: Opaque
# admin / admin123
data:
  mongo-root-username: YWRtaW4=
  mongo-root-password: YWRtaW4xMjM=
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: mongo-initdb
data:
  createuser.sh: |
    mongo <<EOF
    use admin
    db.createUser(
      {
        user: "myuser",
        pwd: "mypasswd",
        roles: [
           { role: "readWrite", db: "sales" }
        ]
      }
    )
    EOF
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: mongodb-server
  labels:
    app: mongodb
spec:
  replicas: 1
  selector:
    matchLabels:
      app: mongodb
  template:
    metadata:
      labels:
        app: mongodb
    spec:
      containers:
      - name: mongodb
        image: mongo:4.4
        ports:
          - containerPort: 27017
        env:
          - name: MONGO_INITDB_ROOT_USERNAME
            valueFrom:
              secretKeyRef:
                name: mongodb-secret
                key: mongo-root-username
          - name: MONGO_INITDB_ROOT_PASSWORD
            valueFrom:
              secretKeyRef:
                name: mongodb-secret
                key: mongo-root-password
        volumeMounts:
        - name: mongo-initdb
          mountPath: /docker-entrypoint-initdb.d
      volumes:
      - name: mongo-initdb
        configMap:
          name: mongo-initdb
---
apiVersion: v1
kind: Service
metadata:
  name: mongodb-service
spec:
  selector:
    app: mongodb
  ports:
    - protocol: TCP
      port: 27017
      targetPort: 27017
