MongoDB wont connect to Python app in Kubernetes

8/24/2021

I have a python app that needs to connect to mongodb statefulset in kubernetes I made a chart for my app and mongodb as a dependency using helm. when the data needs to be written to the DB it send this error code:

pymongo.errors.OperationFailure: Authentication failed., full error: {'operationTime': Timestamp(1629805756, 1), 'ok': 0.0, 'errmsg': 'Authentication failed.', 'code': 18, 'codeName': 'AuthenticationFailed', '$clusterTime': {'clusterTime': Timestamp(1629805756, 1), 'signature': {'hash': b'\xde\x1e\t\x93:H\xd1\x9b\x9b\x15\xacu@S\xe9\x02\xd6#`\xae', 'keyId': 6999961677823213573}}}

The python configs for mongo:

from flask import Flask,request,render_template,jsonify
from pymongo import MongoClient
import os
from dotenv import load_dotenv, find_dotenv

load_dotenv(find_dotenv())
MONGODB_URI = os.getenv('MONGODB_URI')

app = Flask(__name__)
client = MongoClient(MONGODB_URI)
db = client.calocalcdb
collection = db.calocalc_collection
users = db.users

The mongo URI is in a secret file and the application should get it via env variable. the program fails on this line:

user_id = users.insert_one(user)

When i try to echo $MONGODB_URI from the application pod it returns nothing.

-- DlekaShelHaHaim
kubernetes
kubernetes-helm
mongodb
pymongo
python

1 Answer

8/24/2021

In your depoyment yaml you need something to map the secret to the environment variable; something like:

spec:
  template:
    spec:
      containers:
        env:
          - name: MONGODB_URI
            valueFrom:
              secretKeyRef:
                name: <secret name>
                key: <secret name> 
-- Belly Buster
Source: StackOverflow