This Ansible playbook automates the installation of MongoDB 5.0.3 on Ubuntu 24.04, using the Ubuntu 22.04 (Jammy Jellyfish) repository for compatibility.
- Ubuntu 24.04 target system
- Ansible installed on the control machine
- Sudo privileges on the target system
inventory.ini: Contains the target hosts (localhost in this case)mongodb_install.yml: The main playbook that installs MongoDB 5.0.3mongodb_test.yml: A playbook to test the MongoDB installationvars/mongodb_vars.yml: Contains configurable variables for MongoDB installationtemplates/mongod.conf.j2: Template for MongoDB configuration file.env.template: Template for environment variables (copy to .env and customize)load_env.sh: Script to load environment variables from .env file- Various utility scripts for managing MongoDB (see Utility Scripts Summary)
The easiest way to install MongoDB is to use the provided installation script:
./install_mongodb.shThis script will:
- Check if Ansible is installed and install it if necessary
- Run the MongoDB installation playbook
- Provide instructions for verifying the installation
Alternatively, you can run the playbook directly:
ansible-playbook -i inventory.ini mongodb_install.ymlTo customize the MongoDB installation, modify the variables in vars/mongodb_vars.yml before running the playbook.
- Adds the MongoDB GPG key
- Adds the MongoDB 5.0 repository
- Updates apt cache
- Installs libssl1.1 dependency (required for MongoDB 5.0.x on Ubuntu 24.04)
- Installs MongoDB 5.0.3 packages
- Creates necessary directories for MongoDB data and logs
- Pins the MongoDB version to prevent accidental upgrades
- Configures MongoDB using the template
- Enables and starts the MongoDB service
- Verifies the MongoDB installation by checking the version
Note: The order of tasks is important. The MongoDB packages must be installed before creating the data and log directories with the mongodb user as owner, since the mongodb user is created during package installation.
Important: This playbook includes a custom systemd service file for MongoDB to ensure proper startup. The configuration also sets
fork: falsein the MongoDB configuration file, which is required for proper operation with systemd.
The easiest way to check the status of your MongoDB installation is to use the provided status script:
./mongodb_status.shThis script will provide a comprehensive overview of your MongoDB installation, including:
- Installation status and version
- Service status (running or stopped)
- Configuration details (port, bind IP, data directory, etc.)
- Server status information
- List of databases
- Connection information
You can also verify manually by:
-
Checking the service status:
systemctl status mongod
-
Connecting to MongoDB:
mongosh
-
Checking the MongoDB version:
mongod --version
To verify your MongoDB installation, you can use the provided test script:
./test_mongodb.shThis script will:
- Check if MongoDB is installed
- Run the test playbook
- Report on the success or failure of the tests
Alternatively, you can run the test playbook directly:
ansible-playbook -i inventory.ini mongodb_test.ymlThe test playbook will:
- Check if the MongoDB service is running
- Verify the MongoDB version
- Test the connection to MongoDB
- Create a test database and collection
- Insert a test document and retrieve it
Basic configuration parameters can be modified in the vars/mongodb_vars.yml file:
- MongoDB version: 5.0.3
- MongoDB port: 27017
- Bind IP: 127.0.0.1 (localhost only)
- Data directory: /var/lib/mongodb
- Log directory: /var/log/mongodb
- Configuration file: /etc/mongod.conf
For sensitive information like admin credentials, you can use environment variables. This project includes a .env.template file that you can copy to .env and customize:
cp .env.template .envThen edit the .env file to set your credentials:
# MongoDB Environment Variables
MONGODB_ADMIN_USER=admin
MONGODB_ADMIN_PASS=your_secure_password_here
MONGODB_PORT=27017
MONGODB_BIND_IP=127.0.0.1
MONGODB_BACKUP_DIR=/tmp/mongodb_backups
The .env file is loaded by the utility scripts to access these environment variables. This approach keeps sensitive information like passwords out of your repository, as the .env file is included in .gitignore.
The following scripts use environment variables from the .env file:
secure_mongodb.sh: Uses admin credentials for setting up authenticationmanage_users.sh: Uses admin credentials for user management operationsmonitor_mongodb.sh: Uses admin credentials for monitoring (if authentication is enabled)backup_mongodb.sh: Uses backup directory and admin credentialsrestore_mongodb.sh: Uses admin credentials for restore operations (if authentication is enabled)
To create backups of your MongoDB databases, you can use the provided backup script:
./backup_mongodb.shBy default, this script will back up all databases to /tmp/mongodb_backups/[timestamp].
You can customize the backup with the following options:
--dir PATH: Specify a custom backup directory--db NAME: Backup only a specific database--help: Show usage information
Example:
./backup_mongodb.sh --dir /home/user/mongodb_backups --db myappThe backup script will:
- Create a timestamped backup directory
- Get a list of all databases (or use the specified database)
- Use mongodump to create compressed backups
- Create a backup info file with details about the backup
To restore MongoDB databases from a backup, you can use the provided restore script:
./restore_mongodb.sh --path /path/to/backupThe restore script supports the following options:
--path PATH: Specify the backup directory path (required)--db NAME: Restore only a specific database--drop: Drop existing collections before restoring--help: Show usage information
Example:
./restore_mongodb.sh --path /tmp/mongodb_backups/20250521_120000 --db myapp --dropThe restore script will:
- Verify the backup directory exists
- Display information about the backup
- Restore the databases using mongorestore
- Report on the success or failure of the restore operation
To update MongoDB to a newer version, you can use the provided update script:
./update_mongodb.shThis script will:
- Show the current MongoDB version
- Ask for the new version you want to install
- Update the configuration files
- Run the installation playbook with the new version
- Automatically revert changes if the update fails
The script handles both minor version updates (e.g., 5.0.3 to 5.0.4) and major version updates (e.g., 5.0.3 to 6.0.0) by updating the repository information as needed.
If you need to remove MongoDB from your system, you can use the provided uninstall script:
./uninstall_mongodb.shThis script will:
- Ask for confirmation before proceeding
- Stop the MongoDB service
- Remove all MongoDB packages
- Remove the MongoDB repository and GPG key
- Delete MongoDB data and log directories
- Clean up the system
Warning: This will completely remove MongoDB and all its data from your system. Make sure you have a backup of any important data before running this script.
To secure your MongoDB installation, you can use the provided security script:
./secure_mongodb.shBy default, this script will:
- Enable authentication
- Create an admin user with full privileges
- Configure MongoDB to only accept connections from localhost (127.0.0.1)
You can customize the security settings with the following options:
--no-auth: Disable authentication--admin-user USER: Set admin username (will prompt if not provided)--admin-pass PASS: Set admin password (will prompt if not provided)--enable-tls: Enable TLS/SSL for encrypted connections--bind-ip IP: Set bind IP address (default: 127.0.0.1)--help: Show usage information
Example:
./secure_mongodb.sh --admin-user admin --bind-ip 0.0.0.0After running the script, you'll need to authenticate when connecting to MongoDB:
mongosh --authenticationDatabase admin -u <username> -p <password>Once you've secured your MongoDB installation with authentication, you can use the user management script to create, delete, and list users:
./manage_users.shThe script supports the following actions:
- Creating a new user:
./manage_users.sh --create --username myuser --password mypass --database mydb --roles readWrite,dbAdmin --admin-user admin --admin-pass adminpass- Deleting a user:
./manage_users.sh --delete --username myuser --database mydb --admin-user admin --admin-pass adminpass- Listing all users:
./manage_users.sh --list --admin-user admin --admin-pass adminpassAvailable options:
--create: Create a new user--delete: Delete an existing user--list: List all users--username USER: Username for the operation--password PASS: Password for the new user--database DB: Database for the user (default: admin)--roles ROLES: Comma-separated list of roles (e.g., readWrite,dbAdmin)--admin-user USER: Admin username for authentication--admin-pass PASS: Admin password for authentication--help: Show usage information
Common MongoDB roles include:
read: Read-only access to a databasereadWrite: Read and write access to a databasedbAdmin: Database administration tasksuserAdmin: User administration for a databaseclusterAdmin: Cluster administration tasksreadAnyDatabase: Read-only access to all databasesreadWriteAnyDatabase: Read and write access to all databasesuserAdminAnyDatabase: User administration for all databasesdbAdminAnyDatabase: Database administration for all databases
To monitor the performance of your MongoDB installation, you can use the provided monitoring script:
./monitor_mongodb.shBy default, this script will collect performance metrics every 5 seconds for a total of 10 samples and display them on the console.
You can customize the monitoring with the following options:
--interval SECONDS: Interval between checks in seconds (default: 5)--count NUMBER: Number of checks to perform (default: 10)--admin-user USER: Admin username for authentication (if authentication is enabled)--admin-pass PASS: Admin password for authentication (if authentication is enabled)--output FORMAT: Output format: console, json, csv (default: console)--file PATH: Output file path (if not specified, output to console)--help: Show usage information
Example:
./monitor_mongodb.sh --interval 10 --count 30 --output csv --file mongodb_metrics.csvThe monitoring script collects the following metrics:
- Connection statistics (current, available, total created)
- Memory usage (resident, virtual, mapped)
- Network traffic (bytes in/out, number of requests)
- Operation counters (insert, query, update, delete, getmore, command)
- Global lock queue (total, readers, writers)
- Database statistics (collections, objects, data size)
This information can be useful for:
- Identifying performance bottlenecks
- Monitoring resource usage
- Capacity planning
- Troubleshooting issues
This project includes several utility scripts to help you manage your MongoDB installation:
| Script | Description | Usage |
|---|---|---|
install_mongodb.sh |
Installs MongoDB 5.0.3 | ./install_mongodb.sh |
mongodb_status.sh |
Checks the status of MongoDB | ./mongodb_status.sh |
test_mongodb.sh |
Tests the MongoDB installation | ./test_mongodb.sh |
backup_mongodb.sh |
Creates a backup of MongoDB databases | ./backup_mongodb.sh [options] |
restore_mongodb.sh |
Restores MongoDB from a backup | ./restore_mongodb.sh --path /path/to/backup [options] |
update_mongodb.sh |
Updates MongoDB to a newer version | ./update_mongodb.sh |
uninstall_mongodb.sh |
Removes MongoDB from the system | ./uninstall_mongodb.sh |
secure_mongodb.sh |
Configures security settings for MongoDB | ./secure_mongodb.sh [options] |
manage_users.sh |
Creates, deletes, and lists MongoDB users | ./manage_users.sh --action [options] |
monitor_mongodb.sh |
Monitors MongoDB performance metrics | ./monitor_mongodb.sh [options] |
All scripts are designed to work together and provide a complete solution for managing MongoDB on Ubuntu 24.04.