Search code examples
pythonmongodbip

Pymongo: automatic IP


I am writing an application using Pymongo to access a database on MongoDb Atlas using some basic syntax such as:

import pymongo as pm

url = "mongodb+srv://user:[email protected].."

client = pm.MongoClient(url)

db  = client.get_database('name_db')

My problem is that every time I connect from a different IP I need to login manually to the mongoDB Atlas panel and add the new IP. Is there a pymongo function able to add the user IP automatically ? Sorry if the question is trivial, I am still new to the mongoDB world. Thank you!


Solution

  • If your user may have any IP-Address, then you must permit any IP-Address to connect, there is not much you can change. If you like to white-list certain IP's automatically, then it is the same as white-listing them by default.

    Is it really any IP? You can also white-list IP ranges, e.g. 180.120.32.0/24 for all IP's from 180.120.32.0 to 180.120.32.255

    Regarding you actual question: Yes, that's possible.

    Either with Atlas CLI (or see atlasapi):

     atlas accessLists create --currentIp
    

    or with Atlas API:

    curl --user "{PUBLIC-KEY}:{PRIVATE-KEY}" \
       --digest \
       --header "Accept: application/vnd.atlas.2024-05-30+json" \
       -X POST "https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/accessList" \
       --data '[ { "ipAddress": "180.120.32.120" } ]'
    

    To manage IP Access List entries, you must have Project Owner access to the project, which means you grant full admin privileges to your user. The user may do everything. For example drop the entire project or upgrade the cluster and you will have to pay 1000$ per day for your Atlas MongoDB. You should not grant this to your end-user!