Automated IP Whitelisting in MongoDB Atlas

Doing thing easy

Featured image

I was away for a time, my last blog was on December and it is now May, a lot of things happened, I got married, I travel South Asia for a Month, got my dream job and now it’s time to continue writing stuff. Live is good.

Introduction

MongoDB Atlas is a cloud-based database service that provides a secure and scalable way to manage your data. To ensure security, MongoDB Atlas has a default deny-all inbound traffic policy. This means that you need to whitelist IP addresses that need access to your database. In this blog, we will show you how to whitelist a MongoDB Atlas IP using Bash.

More context on MongoDB Network

In MongoDB connection strings, the “+srv” option indicates that the connection should use a DNS seed list to discover the addresses of the MongoDB servers. Here’s an explanation of how it works:

  1. DNS Seed List:
    • When using the “+srv” option, MongoDB drivers utilize a DNS seed list to find the addresses of the MongoDB servers. This seed list typically consists of one or more DNS hostnames.
    • The DNS seed list allows for dynamic discovery of MongoDB server addresses without hardcoding IP addresses or hostnames in the connection string.
  2. SRV Records:
    • The DNS seed list typically points to one or more SRV (Service) records in the DNS server. These SRV records provide the necessary information for connecting to the MongoDB deployment.
    • Each SRV record contains details such as the hostname, port, and priority of MongoDB servers.
  3. Connection Process:
    • When a MongoDB client connects using a “+srv” connection string, it first resolves the DNS seed list to obtain the SRV records.
    • The client then uses the information from the SRV records to establish connections to the MongoDB servers.
  4. Benefits:
    • Using DNS seed lists and SRV records offers flexibility in managing MongoDB deployments. Administrators can update server addresses in the DNS records without needing to modify client configurations.
    • It enables features such as automatic failover and load balancing, as clients can dynamically discover the available MongoDB servers.
  5. Example Connection String:
    • Here’s an example of a MongoDB connection string using the “+srv” option:

        mongodb+srv://myCluster.mongodb.net/myDatabase
      
    • In this connection string, “myCluster.mongodb.net” is the DNS seed list. The MongoDB client resolves this hostname to obtain the SRV records for connecting to the MongoDB servers in the “myCluster” deployment.

Prerequisites

Step 1: Get the IP address

First, you need to get the IP address you want to whitelist. You can do this by running the following command:

curl ifconfig.me

This will give you your current public IP address, which is the one that goes to the internet and retrieves the packages from the servers you reach out to.

Step 2: Create a API key

To whitelist an IP address, you need to create an API key in MongoDB Atlas. To do this, follow these steps:

Step 3: Whitelist the IP address

Now that you have your API key, you can whitelist the IP address using the following command:

curl -X POST \
  https://cloud.mongodb.com/api/atlas/v1.0/projects/<PROJECT_ID>/apiKeys/<API_KEY>/whitelist \
  -H 'Content-Type: application/json' \
  -d '{"comment":"My IP","cidrBlock":"<IP_ADDRESS>/32"}'

Replace <PROJECT_ID> with your MongoDB Atlas project ID, <API_KEY> with your API key, and <IP_ADDRESS> with the IP address you want to whitelist.

Putting all together

The following script allows to whitelist the IP of the runner in Azure DevOps, then execute the script and lastly, remove the IP from the Network Access:

PROJECT_ID="myproject"
PUBLIC_API="mongo-public-api-key"
MONGO_KEY="mongo-private-api-key"
RUNNER_IP=$(curl -s https://ifconfig.me)
echo "##vso[task.setvariable variable=RUNNER_IP]$RUNNER_IP"
JSON_DATA='[{"ipAddress": "'"$RUNNER_IP"'", "comment": "Runner Azure DevOps"}]'
echo "$JSON_DATA"
URL="https://cloud.mongodb.com/api/atlas/v1.0/groups/$PROJECT_ID/accessList"
USER_CREDENTIALS=$(jq -n --arg public_api "$PUBLIC_API" --arg secret_api "$MONGO_KEY" '{user_credentials: "\($public_api):\($secret_api)"}' | jq -r '.user_credentials')
# Whitelist the IP 
curl --user "$USER_CREDENTIALS" --digest --header 'Accept: application/json' --header 'Content-Type: application/json' --include --request POST "$URL" --data "$JSON_DATA"
echo "Running Migrate Script"
./migrate -path migrations -database "$MONGODB_CONNECTION_STRING" up
# Remove IP after migration scripts works
URL2="https://cloud.mongodb.com/api/atlas/v1.0/groups/$PROJECT_ID/accessList/$RUNNER_IP%2F32"
echo "$URL2"
curl --user "$USER_CREDENTIALS" --digest --include --request DELETE "$URL2"

Conclusion

Whitelisting an IP address in MongoDB Atlas is a straightforward process using Bash. By following these steps, you can ensure that only authorized IP addresses have access to your database. Remember to replace the placeholders with your actual values.

Note: Make sure to keep your API key secure and do not share it with anyone.

I hope this helps! Let me know if you have any questions.

Build On!