CLI Tool for MongoDB® - Installation & Use

See how to leverage command line interface (CLI) functionality for our hosting for MongoDB® service. This ScaleGrid tool allows you to perform the same actions you can through the console from the command line.

The CLI tool is written in Python and published as a Python package, and the package simply needs to be installed into your machine from the Package Index. The CLI currently supports generic, Mongo-specific and Redis-specific commands, and support for other database types will be added in the future versions.

MongoDB® CLI Tool Installation

  1. This package requires Python>=3.6, and you can follow these steps to install Python.

  2. Installing the package is straightforward – run pip install scalegrid_cli.

  1. You must login to your ScaleGrid account before you can perform any of the actions. This can be done by running sg-cli login from the CLI.

  2. You will be prompted to enter your email address, password and 2FA code. Upon successful authentication, a cookie will be setup for the session and you will be logged in.

Now that you can perform actions on your MongoDB® clusters from the CLI, you can list all the MongoDB®® clusters in your account by running sg-cli mongo list-clusters. If you have any MongoDB® clusters in your account, the output will look something like below:

To logout from your account, run sg-cli logout.

CLI Command Examples

The following actions can be performed from the command line.

Help Commands

Description: Help menu
Full Command (usage):

sg-cli --help

Output (expected):
ScaleGrid Help Menu

Usage:
    sg-cli [mongo] <command> [<args>...]

Options:
    -v, --verbose  Increase verbosity
    -h, --help     Show this menu
    -V --version   Show version

Commands:
    (mongo) add-firewall-rules
    (mongo) build-index
    check-job-status
    (mongo) compact
    (mongo) create-alert-rule
    (mongo) create-cloud-profile
    (mongo) create-cluster
    (mongo) create-follower-cluster
    (mongo) delete-backup
    delete-alert-rule
    delete-cloud-profile
    (mongo) delete-cluster
    (mongo) get-active-alerts
    (mongo) get-cluster-credentials
    (mongo) list-alert-rules
    (mongo) list-backups
    list-cloud-profiles
    (mongo) list-clusters
    login
    logout
    (mongo) patch-os
    (mongo) pause-cluster
    (mongo) peek-at-backup
    (mongo) resolve-alerts
    (mongo) restore-backup
    (mongo) resume-cluster
    (mongo) scale-up
    (mongo) set-backup-schedule
    (mongo) start-backup
    update-cloud-profile-keys
    wait-until-job-done

Help commands:
    sg-cli -h
    sg-cli <command> -h
    sg-cli (mongo) -h
    sg-cli [mongo] <command> -h

You can also run sg-cli -h from the for a detailed help menu for the particular command.

Example:

sg-cli mongo add-firewall-rules -h

Login Command

Description: Login to your ScaleGrid account
Full Command: (You will be prompted for your password and 2FA code)

sg-cli login --email <YourEmailAddress>

Output:

INFO Connection successful, setting up cookie
INFO Cookie created successfully

Create Cloud Profile Command

Description: Create a cloud profile
AWS Full Command:

sg-cli mongo create-cloud-profile --aws --cloud-profile-name AWSMongoTestCP --region uswest1 --access-key <> --secret-key <> --vpc-id vpc-e0359578 --vpc-cidr 172.31.0.0/16 --subnet-id subnet-3254d7d1 --subnet-cidr 172.31.0.0/20 --security-group-name aws-private-sg --security-group-id sg-987r5l26

Azure Full Command:

sg-cli mongo create-cloud-profile --azure --cloud-profile-name AzureMongoTestCP --region eastus --subscription-id <> --subnet-name subnet1-eastus --vnet-name vnet-aksd2497 --vnet-resource-group eastustest
 --security-group-name azure-private-sg

Output:

INFO New cloud profile ID: 3738. Keep this ID and use it to perform commands on your cloud profile once it is created.
INFO To get more information about your cloud profile once it is created, run the list-cloud-profiles command.
INFO Use your action ID to monitor the job status.
INFO Action ID: 1385126

Create MongoDB® Cluster Command

Description: Create a Standalone Cluster or Replica Set
Full Command:

sg-cli mongo create-cluster --cluster-name TestCluster --shard-count 1 --replica-count 1 --size micro --version v366 --machine-list ['AWSMongoTestCP'] --compression-algo snappy

Output:

INFO Cluster creation started successfully
INFO New cluster ID: 99999. Keep this ID and use it to perform commands on your cluster once it is created.
INFO To get more information about your cluster once it is created, run the list-clusters command.
INFO Use your action ID to monitor the job status.
INFO Action ID: 1385127

Get MongoDB® Cluster Credentials Command

Description: Get the username and password for the root database user
Full Command:

sg-cli mongo get-cluster-credentials --cluster-name TestCluster

Output:

INFO Username: admin
INFO Password: KQYttYmANutDjP76T

List MongoDB® Clusters Command

Description: Get a list of all your clusters of a specified database type
Full Command:

sg-cli mongo list-clusters

Output:

{
    "name": "TestCluster",
    "id": 99999,
    "clusterType": "Standalone",
    "shared": false,
    "status": "Running",
    "size": "Micro",
    "diskSizeGB": 10,
    "usedDiskSizeGB": 1,
    "versionStr": "v3.6.6",
    "displayMachinePoolName": "AWSMongoTestCP",
    "monitoringServerData": [
        {
        "id": 12345,
            "name": "SG-TestCluster-12345.servers.mongodirector.com",
            "shardName": "Shard-0",
            "type": "Primary"
        }
    ],
    "encryptionEnabled": false,
    "sslEnabled": false,
    "engine": "wiredtiger",
    "compressionAlgo": "snappy"
}

MongoDB® Build Index Command

Description: Create an index for a collection in a database in your cluster
Full Command:

sg-cli mongo build-index --cluster-name TestCluster --db-name local --coll-name startup_log --index "[{'key':1},{name:'testIndex'}]"

Output:

INFO Index build started successfully
INFO Use your action ID to monitor the job status.
INFO Action ID: 1385128

Start Backup Command

Description: Create a backup of a cluster
Full Command:

sg-cli mongo start-backup --cluster-name TestCluster --backup-name BatchBackup

Output:

INFO TestCluster backup started successfully
INFO Use your action ID to monitor the job status.
INFO Action ID: 1385129

List Backups Command

Description: Get a list of backups of a specified cluster
Full Command:

sg-cli mongo list-backups --cluster-name TestCluster

Output:

{
    "comment": null,
    "created": 1569312557000,
    "entityId": 1029720,
    "geoLocation": null,
    "id": 1029720,
    "location": "{\"ID\":\"snap-041359c0a85160854\",\"region\":\"uswest1\",\"sizeInGB\":10}",
    "longlocation": null,
    "name": "BatchBackup",
    "object_id": 99999,
    "object_type": "MongoCluster",
    "persistent": true,
    "size": 0,
    "type": "ONDEMAND",
    "updated": 1569312557000
}

Restore Backup Command

Description: Restore a backup
Full Command:

sg-cli mongo restore-backup --cluster-name TestCluster --backup-name BatchBackup

Output:

INFO BatchBackup restore started successfully
INFO Use your action ID to monitor the job status.
INFO Action ID: 1385134

Set Backup Schedule Command

Description: Change the backup schedule of a cluster
Full Command:

sg-cli mongo set-backup-schedule --cluster-name TestCluster --enabled --interval 24 --hour 0 --limit 2

Output:

INFO Backup schedule changed successfully

Create Alert Rule Command

Description: Create an alert rule for a particular cluster
Full Command:

sg-cli mongo create-alert-rule --cluster-name TestCluster --type metric --operator lt --threshold 100 --notifications email --metric cpu_user --duration two

Output:

{
    "alertRuleDescription": "CPU - User (%) less than 100%",
    "averageType": "TWO",
    "clusterId": 99999,
    "created": "2019-09-24 13:40:29.617000",
    "databaseType": "MONGODB",
    "enabled": true,
    "id": 781,
    "metric": "CPU_USER",
    "notifications": [
        "EMAIL"
    ],
    "operator": "LT",
    "ruleMetricName": "CPU - User (%)",
    "threshold": 100.0,
    "type": "METRIC"
}
INFO Alert rule created successfully

Peek at Backup Command

Description: Create a new standalone cluster from a past backup
Full Command:

sg-cli mongo peek-at-backup --cluster-name TestCluster --backup-name BatchBackup --new-name BatchPeek

Output:

INFO Peek started successfully
INFO Use your action ID to monitor the job status.
INFO Action ID: 1385139

MongoDB® Create Follower Cluster Command

Description: Create a follower cluster
Full Command:

sg-cli mongo create-follower-cluster --target-name BatchPeek --source-name TestCluster --interval 24

Output:

INFO Follower relationship between clusters BatchPeek and TestCluster created successfully

Get Active Alerts Command

Description: Get all active alerts on a particular cluster
Full Command:

sg-cli mongo get-active-alerts --cluster-name TestCluster

Output:

{
    "alertDescription": "CPU - User (%) went below 100%",
    "clusterID": 99999,
    "created": "2019-09-24 13:42:05",
    "dismissComment": null,
    "dismissedDate": null,
    "id": 82579,
    "machineName": "SG-TestCluster-12345.servers.mongodirector.com",
    "state": "ACTIVE",
    "userAlertRuleId": 781
}

Resolve Alerts Command

Description: Dismiss alerts for a particular cluster
Full Command:

sg-cli mongo resolve-alerts --cluster-name TestCluster --alert-id-list 82579

Output:

INFO Alerts resolved successfully

List Alert Rules Command

Description: List all the alert rules for a particular cluster
Full Command:

sg-cli mongo list-alert-rules --cluster-name TestCluster

Output:

{
    "alertRuleDescription": "CPU - User (%) less than 100%",
    "averageType": "TWO",
    "clusterId": 99999,
    "created": "2019-09-24 13:40:29",
    "databaseType": "MONGODB",
    "enabled": true,
    "id": 781,
    "metric": "CPU_USER",
    "notifications": [re
        "EMAIL"
    ],
    "operator": "LT",
    "ruleMetricName": "CPU - User (%)",
    "threshold": 100.0,
    "type": "METRIC"
}

Delete Alert Rule Command

Description: Delete an alert rule from a particular cluster
Full Command:

sg-cli delete-alert-rule --alert-rule-id 781

Output:

INFO Alert rule deleted successfully

Scale Up Command

Description: Increase the size of your cluster
Full Command:

sg-cli mongo scale-up --cluster-name TestCluster --size Small

Output:

INFO Scale up started successfully
INFO Use your action ID to monitor the job status.
INFO Action ID: 1385210

MongoDB® Compact Command

Description: Defragment the data in your cluster to improve performance
Full Command:

sg-cli mongo compact --cluster-name TestCluster

Output:

INFO Compact started successfully
INFO Use your action ID to monitor the job status.
INFO Action ID: 1385216

Pause Cluster Command

Description: Pause a cluster
Full Command:

sg-cli mongo pause-cluster --cluster-name TestCluster

Output:

INFO Pause started successfully
INFO Use your action ID to monitor the job status.
INFO Action ID: 1385217

Resume Cluster Command

Description: Resume a cluster
Full Command:

sg-cli mongo resume-cluster --cluster-name TestCluster

Output:

INFO Resume started successfully
INFO Use your action ID to monitor the job status.
INFO Action ID: 1385220

Patch OS Command

Description: Patch your OS with the most recent updates
Full Command:

sg-cli mongo patch-os --cluster-name BatchPeek

Output:

INFO OS Patch started successfully
INFO Use your action ID to monitor the job status.
INFO Action ID: 1385224

Delete Cluster Command

Description: Delete an old cluster
Full Command:

sg-cli mongo delete-cluster --cluster-name TestCluster

Output:

INFO Cluster delete started successfully
INFO Use your action ID to monitor the job status.
INFO Action ID: 1385232

Add Firewall Rules Command

Description: Add a list of IP CIDR to the firewall rules of your cluster
Full Command:

sg-cli mongo add-firewall-rules --cluster-name TestCluster --cidr-list 10.20.0.0/16,10.30.0.0/20

Output:

INFO Firewall rules added successfully

Delete Backup Command

Description: Delete an old backup
Full Command:

sg-cli mongo delete-backup --cluster-name TestCluster --backup-name BatchBackup

Output:

INFO Backup Delete started successfully
INFO Use your action ID to monitor the job status.
INFO Action ID: 1385237

Update Cloud Profile Keys Command

Description: Update Keys in AWS Cloud Profile
Full Command:

sg-cli update-cloud-profile-keys --cloud-profile-name AWSMongoTestCP --access-key <> --secret-key <>

Output:

INFO AWS cloud profile keys updated successfully

List Cloud Profiles Command

Description: Get a list of all your cloud profiles
Full Command:

sg-cli list-cloud-profiles

Output:

{
	"providerMachinePoolName": "SYSTEM2 (AWS) - US East (N. Virginia)",
	"regionDesc": "US East (N. Virginia)",
	"region": "useast1",
	"id": 3113,
	"dbType": "MONGODB",
	"type": "EC2",
	"created": "2019-03-30 06:51:10",
	"owner": "[email protected]",
	"status": "Running",
	"shared": true
}
{
	"providerMachinePoolName": "SYSTEM (AWS) - US East (Ohio)",
	"regionDesc": "US East (Ohio)",
	"region": "useast2",
	"id": 1678,
	"dbType": "MONGODB",
	"type": "EC2",
	"created": "2017-01-08 02:04:02",
	"owner": "[email protected]",
	"status": "Running",
	"shared": true
}

Delete Cloud Profile Command

Description: Delete a cloud profile
Full Command:

sg-cli delete-cloud-profile --cloud-profile-name AWSMongoTestCP

Output:

INFO Cloud profile delete started successfully
INFO Use your action ID to monitor the job status.
INFO Action ID: 1385243

Logout Command

Description: Logout of your ScaleGrid account
Full Command:

sg-cli logout

Output:

INFO Cookie removed, logging out…

Test The Commands

The below workflow can be run in a batch file to test out all the commands supported by the CLI - login, create cloud profile, create cluster, get cluster credentials, etc. Assign the necessary values to each flag to ensure that the commands run successfully. The command prompt closes if there is an error in a call and you can find the full traceback in the log file in your home path.

@echo off
:: Set values for the below variables so they can be used later in the commands
set cpname=<CloudProfileName>
set clustername=<ClusterName>
set peekedclustername=<PeekAtBackupClusterName>
set backupname=<BackupName>
set accesskey=<AWSAccessKey>
set secretkey=<AWSSecretKey>

:: To get the help menu
sg-cli --help

:: To login to your ScaleGrid account
sg-cli login --email <YourEmailAddress>

:: To create an AWS cloud profile, enter the value for each flag
sg-cli mongo create-cloud-profile --aws --cloud-profile-name %cpname% --region uswest1 --access-key %accesskey% --secret-key %secretkey% --vpc-id <VPCID> --vpc-cidr x.x.x.x/x --subnet-id <SubnetID> --subnet-cidr x.x.x.x/x --security-group-name <SGName> --security-group-id <SGID>
CALL :wait

:: To create a MongoDB cluster, enter the name of the cloud profile being created in the previous step
sg-cli mongo create-cluster --cluster-name %clustername% --shard-count 1 --replica-count 1 --size micro --version v366 --machine-list ['%cpname%'] --compression-algo snappy
CALL :wait

:: To get admin credentials for newly created cluster
sg-cli mongo get-cluster-credentials --cluster-name %clustername%

:: To list the MongoDB clusters in your account
sg-cli mongo list-clusters

:: To build index in your MongoDB cluster
sg-cli mongo build-index --cluster-name %clustername% --db-name local --coll-name startup_log --index "[{'key':1},{name:'testIndex'}]"
CALL :wait

:: To start a manual backup on your MongoDB cluster
sg-cli mongo start-backup --cluster-name %clustername% --backup-name %backupname%
CALL :wait

:: To list the backups of your MongoDB cluster
sg-cli mongo list-backups --cluster-name %clustername%

:: To restore your MongoDB cluster using the previously taken backup
sg-cli mongo restore-backup --cluster-name %clustername% --backup-name %backupname%

:: To enable scheduled backup for your MongoDB cluster, at 00:00 everyday, with an interval of 24 hours and a maximum retention of 2 scheduled backups
sg-cli mongo set-backup-schedule --cluster-name %clustername% --enabled --interval 24 --hour 0 --limit 2

:: To disable scheduled backup
sg-cli mongo set-backup-schedule --cluster-name %clustername%

:: To create an alert rule for your MongoDB cluster, the below rule will trigger an alert whenever the CPU is greater than 80% for a duration of 2 minutes
sg-cli mongo create-alert-rule --cluster-name %clustername% --type metric --operator gt --threshold 80 --notifications email --metric cpu_user --duration two
CALL :getAlertRule

:: To create a peek at backup cluster for your MongoDB cluster
sg-cli mongo peek-at-backup --cluster-name %clustername% --backup-name %backupname% --new-name %peekedclustername%
CALL :wait

:: To create a follower cluster using the peek at backup cluster created in the previous step, with a 24 hour interval between each sync with source cluster
sg-cli mongo create-follower-cluster --target-name %peekedclustername% --source-name %clustername% --interval 24

:: To get active alert rules for your MongoDB cluster
sg-cli mongo get-active-alerts --cluster-name %clustername%
CALL :getAlert

:: To manually resolve alerts for your MongoDB cluster
sg-cli mongo resolve-alerts --cluster-name %clustername% --alert-id-list %alertID%

:: To list all alert rules for your MongoDB cluster
sg-cli mongo list-alert-rules --cluster-name %clustername%

:: To delete an alert rule for your MongoDB cluster, uncomment the command to run
:: sg-cli delete-alert-rule --alert-rule-id %ruleID%

:: To scale up your MongoDB cluster
sg-cli mongo scale-up --cluster-name %clustername% --size Small
CALL :wait

:: To run the compact operation on your MongoDB cluster
sg-cli mongo compact --cluster-name %clustername%
CALL :wait

:: To pause your MongoDB cluster
sg-cli mongo pause-cluster --cluster-name %clustername%
CALL :wait

:: To resume your MongoDB cluster
sg-cli mongo resume-cluster --cluster-name %clustername%
CALL :wait

:: To patch the OS of your MongoDB cluster
sg-cli mongo patch-os --cluster-name %peekedclustername%
CALL :wait

:: To delete your MongoDB peek at backup cluster, uncomment the command to run
:: sg-cli mongo delete-cluster --cluster-name %peekedclustername%
CALL :wait

:: To add a list of IP CIDRs to whitelist to your MongoDB cluster
sg-cli mongo add-firewall-rules --cluster-name %clustername% --cidr-list x.x.x.x/x,x.x.x.x/x

:: To delete the backup of your MongoDB cluster, uncomment the command to run
:: sg-cli mongo delete-backup --cluster-name %clustername% --backup-name %backupname%
CALL :wait

:: To permanently delete your MongoDB cluster, uncomment the command to run
:: sg-cli mongo delete-cluster --cluster-name %clustername%
CALL :wait

:: To update your cloud profile keys with new credentials, uncomment the command to run
:: sg-cli update-cloud-profile-keys --cloud-profile-name %cpname% --access-key xxxxxxxxxxxxxxxxxxxxx --secret-key xxxxxxxxxxxxxxxxxxxxx

:: To list all cloud profiles in your ScaleGrid account
sg-cli list-cloud-profiles

:: To delete a cloud profile from your ScaleGrid account, uncomment the command to run
:: sg-cli delete-cloud-profile --cloud-profile-name %cpname%

:: To logout from your ScaleGrid account
sg-cli logout

EXIT /B %ERRORLEVEL%

:: Calling the below function waits for the action to complete. It can be used for actions that are async operations, i.e., actions that return an action ID
:wait
@echo off
:: Log file is created inside the .sg directory of your home directory
for /f "tokens=11" %%i in (%UserProfile%\.sg\sg.log) do ^
set ID=%%i
@echo on
sg-cli wait-until-job-done --action-id %ID%
EXIT /B 0

:getAlertRule
@echo off
for /f "tokens=12" %%i in (%UserProfile%\.sg\sg.log) do ^
set ruleID=%%i
@echo on
EXIT /B 0

:getAlert
@echo off
for /f "tokens=11" %%i in (%UserProfile%\.sg\sg.log) do ^
set alertID=%%i
@echo on
EXIT /B 0