gaut
gaut

Reputation: 5958

Mongodb Authentication failed in Kubernetes (minikube)

Creating a mongodb from the below minikube deployment, I am not able to authenticate from the command line.

Basically I'd just want to list all databases because I suspect there is an issue with the connectivity to mongo-express.

I exec into the pod using kubectl exec -it mongodb-deployment-6b46455744-gfkzw -- /bin/bash,

mongo to start up the cli

db.auth("username", "password") gives MongoServerError: Authentication failed.

even though printenv gives

MONGO_INITDB_ROOT_PASSWORD=password
MONGO_INITDB_ROOT_USERNAME=username

any help?

apiVersion: apps/v1
kind: Deployment
metadata:
  name: mongodb-deployment
  labels:
    app: mongodb
spec:
  replicas: 1
  selector:
    matchLabels:
      app: mongodb
  template:
    metadata:
      labels:
        app: mongodb
    spec:
      containers:
      - name: mongodb
        image: mongo
        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
        - name: ME_CONFIG_MONGODB_ENABLE_ADMIN
          value: "true"
---
apiVersion: v1
kind: Service
metadata:
  name: mongodb-service
spec:
  selector:
    app: mongodb
  ports:
    - protocol: TCP
      port: 27017
      targetPort: 27017

Upvotes: 1

Views: 2259

Answers (2)

Miroslav Vojtuš
Miroslav Vojtuš

Reputation: 55

I had a very same issue.

In my case I was playing around with startup command and between deployments I have first enforced command mongod --bind_ip_all. As the db has been created in persistent volume without --auth flag, it did not created the necessary user entry.

You either need to delete you persistent volume (and deployment and pod) and recreate it from scratch. While removing the startup command and let it to init script. Do it only if you are ok with loosing data. I guess you do not have any so go for it.

Or if you want to preserve your data, open a shell to your pod with the mongodb and add the users as per doc manually https://www.mongodb.com/docs/manual/reference/method/db.createUser/. As the auth has not been enabled by --auth flag previously you should be able to login without credentials.

Upvotes: 0

gaut
gaut

Reputation: 5958

managed to connect using

mongosh --port 27017  --authenticationDatabase \
    "admin" -u "myUserAdmin" -p

from https://docs.mongodb.com/manual/tutorial/authenticate-a-user/#std-label-authentication-auth-as-user and docker hub page.

Upvotes: 1

Related Questions