> This page location: /docs.md > /docs/development.md > /docs/atlas/atlas-ui/triggers.md > /docs/atlas/atlas-ui/triggers/scheduled-triggers.md

> For the complete MongoDB documentation index, see www.mongodb.com/docs/llms.txt

# Tutorial: Automate Clusters with Scheduled Triggers

In this tutorial, you will use Atlas scheduled Triggers to automate cluster management tasks by programmatically calling the Atlas Administration API.

This tutorial includes the following procedures:

- [Initial Setup](https://www.mongodb.com/docs/atlas/atlas-ui/triggers/scheduled-triggers-tutorial.md#std-label-scheduled-triggers-tutorial-setup): Create a [service account](https://www.mongodb.com/docs/atlas/api/api-authentication.md#std-label-service-accounts-overview) with [`Project Owner`](https://www.mongodb.com/docs/atlas/reference/user-roles.md#mongodb-authrole-Project-Owner) permissions to your existing Atlas project, store the service account credentials as Values and Secrets, then create reusable Functions that uses these credentials to call the [Update One Cluster in One Project](https://www.mongodb.com/docs/atlas/reference/api-resources-spec/v2/#operation/updateGroupCluster) endpoint.

  **Note:**

  If you prefer to use [API keys](https://www.mongodb.com/docs/atlas/api/api-authentication.md#std-label-api-keys-overview) instead of [service accounts](https://www.mongodb.com/docs/atlas/api/api-authentication.md#std-label-service-accounts-overview) to authenticate to the Atlas Administration API with [`Project Owner`](https://www.mongodb.com/docs/atlas/reference/user-roles.md#mongodb-authrole-Project-Owner) permissions, you can save API (Application Programming Interface) public and private keys as Values and Secrets to use in the Functions in this tutorial.

- [Pause and Resume Clusters on a Schedule](https://www.mongodb.com/docs/atlas/atlas-ui/triggers/scheduled-triggers-tutorial.md#std-label-scheduled-triggers-tutorial-pause-resume): Create scheduled Triggers to automatically pause clusters every evening and resume them every weekday morning.

- [Scale Clusters on a Schedule](https://www.mongodb.com/docs/atlas/atlas-ui/triggers/scheduled-triggers-tutorial.md#std-label-scheduled-triggers-tutorial-scale-clusters): Create scheduled Triggers to automatically scale a cluster up during peak hours and down afterwards.

## Required Permissions

To complete this tutorial, you need a user with [`Project Owner`](https://www.mongodb.com/docs/atlas/reference/user-roles.md#mongodb-authrole-Project-Owner) access to a MongoDB Atlas project.

## Initial Set Up

This initial set up only needs to be completed once, and allows you to create the scheduled Triggers on this page to automate cluster management tasks. Before performing this tutorial, ensure you have a MongoDB Atlas project with at least one cluster. This procedure performs the following set up tasks:

- Creates and saves credentials for an Atlas [service account](https://www.mongodb.com/docs/atlas/api/api-authentication.md#std-label-service-accounts-overview) that Triggers will use to call the Atlas Administration API with [`Project Owner`](https://www.mongodb.com/docs/atlas/reference/user-roles.md#mongodb-authrole-Project-Owner) permissions to your existing Atlas project.

- Creates a reusable Function called `getAuthHeaders` that generates an access token using the service account credentials and returns the appropriate authentication headers for calling the Atlas Administration API.

- Creates a reusable Function called `modifyCluster` that wraps the [Update One Cluster in One Project](https://www.mongodb.com/docs/atlas/reference/api-resources-spec/v2/#operation/updateGroupCluster) API.

1. Create a Service Account.

   To create a service account that your Triggers can use to call the Atlas Administration API with [`Project Owner`](https://www.mongodb.com/docs/atlas/reference/user-roles.md#mongodb-authrole-Project-Owner) permissions to your existing Atlas project:

   In Atlas, go to the Users page.

   If it's not already displayed, select your desired organization from the  Organizations menu in the navigation bar.

   Click All Projects in the sidebar under the Identity & Access section, and select your desired project.

   Click Project Identity & Access in the sidebar under the Security section.

   The [Users](https://cloud.mongodb.com/go?l=https%3A%2F%2Fcloud.mongodb.com%2Fv2%2F%3Cproject%3E%23%2Faccess) page displays.

   Click Create Application  Service Account.

   Enter the service account information.

   - Name: Name for your service account. (e.g., `TriggersServiceAccount`)

   - Description: (optional) Description for your service account. (e.g., Service account for Atlas Functions to call Atlas Administration API.)

   - Service Account Permissions: [`Project Owner`](https://www.mongodb.com/docs/atlas/reference/user-roles.md#mongodb-authrole-Project-Owner)

   Click Create.

   This creates the service account and automatically adds it to the project's parent organization with the permission [`Organization Member`.](https://www.mongodb.com/docs/atlas/reference/user-roles.md#mongodb-authrole-Organization-Member)

   Configure the API Access List.

   Add IP addresses to the API Access List if you want to restrict which IP addresses can call the Atlas Administration API with this service account.

   **Note:**

   If Require IP Access List for the Atlas
   Administration API is enabled for your organization, or if you added any IP addresses to your service account's API Access List, then every Atlas Administration API request must pass an IP access-list check.

   Atlas Triggers and Functions send outgoing HTTP requests from a specific set of outbound IP addresses. To enable your scheduled Triggers to call the Atlas Administration API and other external services, you must add these IP addresses to your service account's API Access List.

   For the full list of outbound IP addresses used by Atlas Functions, see [Function Security Outbound IP Access](https://www.mongodb.com/docs/atlas/atlas-ui/triggers/functions/security.md#std-label-atlas-mongodb-functions-security). You must add each IP address individually.

2. Store Service Account credentials as Values and Secrets.

   Create the following Values and Secrets to store your service account credentials:

   - `AtlasClientId` Value that contains your service account client ID.

   - `AtlasClientSecret` Secret that contains your service account client secret.

   - `AtlasClientSecret` Value that links to the Secret. This enables you to access the client secret value in your Functions, while still keeping it stored securely as a Secret.

   In Atlas, go to the Triggers page.

   If it's not already displayed, select the organization that contains your project from the  Organizations menu in the navigation bar.

   If it's not already displayed, select your project from the Projects menu in the navigation bar.

   In the sidebar, click Triggers under the Streaming Data heading.

   The [Triggers](https://cloud.mongodb.com/go?l=https%3A%2F%2Fcloud.mongodb.com%2Fv2%2F%3Cproject%3E%23%2Ftriggers) page displays.

   Navigate to the Values Page.

   Click the Linked App Service: Triggers link.

   In the sidebar, click Values under the Build heading.

   Store the client ID in a Value.

   Click Create a Value

   Enter `AtlasClientId` as the Value Name.

   Select the Value type.

   Select the Custom Content option and enter the client ID.

   **Note:**

   You must enter the client ID as a string value with quotes (`"<clientId>"`).

   Click Save.

   Store the client secret in a Secret and link it to a Value.

   **Note:**

   Secret values cannot be accessed directly, so you must create a second Value that links to the Secret.

   Click Create a Value.

   Enter `AtlasClientSecret` as the Value Name.

   Select the Value type.

   Select the Link to Secret option.

   Enter `AtlasClientSecret` and click Create
   "AtlasClientSecret" to name the Secret value.

   Paste the client secret into the Client Secret field that appears below the Secret name.

   Click Save to create both the Secret and the Value.

3. Create the `getAuthHeaders` Function.

   To create a reusable Function that retrieves an access token using the service account credentials and returns the appropriate authentication headers for calling the Atlas Administration API:

   Navigate to the Functions Page.

   1. In the sidebar, click Functions under the Build heading.

   2. Click Create a Function.

      The Settings tab displays by default.

   Enter `getAuthHeaders` as the Name for the Function.

   Set Private to `true`. This Function will only be called by other Functions in this tutorial.

   Leave the other configuration options in the Settings tab at their default values.

   Define the Function code.

   Click the Function Editor tab and paste the following code to define the Function:

   ```javascript
   /*
    * Generate API request headers with a new Service Account Access Token.
    */
   exports = async function getAuthHeaders() {

     // Get stored credentials
     clientId = context.values.get("AtlasClientId");
     clientSecret = context.values.get("AtlasClientSecret");

     // Throw an error if credentials are missing
     if (!clientId || !clientSecret) {
       throw new Error("Authentication credentials not found. Set AtlasClientId/AtlasClientSecret (service account auth credentials).");
     }

     // Define the argument for the HTTP request to get the access token
     const tokenUrl = "https://cloud.mongodb.com/api/oauth/token";
     const credentials = Buffer.from(`${clientId}:${clientSecret}`).toString("base64");

     const arg = {
       url: tokenUrl,
       headers: {
         "Authorization": [ `Basic ${credentials}` ],
         "Content-Type": [ "application/x-www-form-urlencoded" ]
       },
       body: "grant_type=client_credentials"
     }

     // The response body is a BSON.Binary object; parse it to extract the access token 
     const response = await context.http.post(arg);
     const tokenData = JSON.parse(response.body.text());
     const accessToken = tokenData.access_token;

     // Define the Accept header with the resource version from env var or default to latest stable
     const resourceVersion = context.environment.ATLAS_API_VERSION || "2025-03-12";
     const acceptHeader = `application/vnd.atlas.${resourceVersion}+json`;

     // Return the access token as headers for future API calls
     return {
      headers: {
        "Authorization": [ `Bearer ${accessToken}` ],
        "Accept": [ acceptHeader ],
        "Accept-Encoding": [ "bzip, deflate" ],
        "Content-Type": [ "application/json" ]
      }
     };
   }

   ```

4. Create the `modifyCluster` Function.

   To create a reusable Function that wraps the [Update One Cluster in One Project](https://www.mongodb.com/docs/atlas/reference/api-resources-spec/v2/#operation/updateGroupCluster) endpoint:

   From the Functions Page, click Create a Function.

   The Settings tab displays by default.

   Enter `modifyCluster` as the Name for the Function.

   Set Private to `true`. This Function will only be called by other Functions in this tutorial.

   Leave the other configuration options in the Settings tab at their default values.

   Define the Function code.

   Click the Function Editor tab and paste the following code to define the Function:

   ```javascript
   /*
    * Modifies the cluster as defined by the `body` parameter.
    * See https://www.mongodb.com/docs/atlas/reference/api-resources-spec/v2/#tag/Clusters/operation/updateCluster
    */
   exports = async function(projectID, clusterName, body) {

     // Easy testing from the console
     if (projectID === "Hello world!") {
       projectID   = "<projectId>";
       clusterName = "<clusterName>";
       body        = { paused: false };
     }

     // Retrieve headers to authenticate with a new access token, and define the request URL for the Atlas API endpoint
     const authHeaders = await context.functions.execute("getAuthHeaders");
     const requestUrl = `https://cloud.mongodb.com/api/atlas/v2/groups/${projectID}/clusters/${clusterName}`;

     // Build the argument for the HTTP request to the Atlas API to modify the cluster
     const arg = {
       url: requestUrl,
       headers: authHeaders.headers,
       body: JSON.stringify(body)
     };

     // The response body is a BSON.Binary object; parse it and return the modified cluster description
     const response = await context.http.patch(arg);
     if (response.body) {
        return EJSON.parse(response.body.text()); 
     } else {
        throw new Error(`No response body returned from Atlas API. Status code: ${response.status}`);
     }
   };
   ```

   **Note: Test code in the Function Editor.**

   The Function Editor automatically provides `"Hello world!"` as the first argument when you run a Function in the Testing Console. This code tests for that input and provides values to the parameters when `"Hello world!"` is received.

   To test the Function with your own input, replace the following placeholder values with your own information:

   - `<projectId>`

   - `<clusterName>`

   - In the `body` parameter, provide a payload containing the modifications you'd like to make to the cluster. The example code includes a payload that pauses a cluster.

## Pause and Resume Clusters on a Schedule

This procedure creates scheduled Triggers to automatically pause clusters every evening and resume them every weekday morning. This is useful for non-production clusters that don't need to run outside of business hours, or for any clusters that you want to automatically pause and resume on a schedule.

1. Create the `pauseClusters` Function.

   In Atlas, go to the Triggers page.

   If it's not already displayed, select the organization that contains your project from the  Organizations menu in the navigation bar.

   If it's not already displayed, select your project from the Projects menu in the navigation bar.

   In the sidebar, click Triggers under the Streaming Data heading.

   The [Triggers](https://cloud.mongodb.com/go?l=https%3A%2F%2Fcloud.mongodb.com%2Fv2%2F%3Cproject%3E%23%2Ftriggers) page displays.

   Navigate to the Functions Page

   Click the Linked App Service: Triggers link.

   In the sidebar, click Functions under the Build heading.

   Click Create a Function.

   The Settings tab displays by default.

   Enter `pauseClusters` as the Name for the Function.

   Set Private to `true`. This Function will only be called by the `pauseClusters` Trigger in this tutorial.

   Leave the other configuration options in the Settings tab at their default values.

   Define the Function code.

   Click the Function Editor tab and paste the following code to define the Function:

   ```javascript
   /*
    * Iterates over the provided projects and clusters, pausing those clusters.
    */
   exports = async function () {

     // Supply project IDs and cluster names to pause
     const projectIDs = [
       {
         id: "<projectIdA>",
         names: [ "<clusterNameA>", "<clusterNameB>" ]
       },
       {
         id: "<projectIdB>",
         names: [ "<clusterNameC>" ]
       }
     ];

     // Set desired state
     const body = { paused: true };

     // Pause each cluster and log the response
     for (const project of projectIDs) {
       for (const cluster of project.names) {
         const result = await context.functions.execute(
           "modifyCluster",
           project.id,
           cluster,
           body,
         );
         console.log("Cluster " + cluster + ": " + EJSON.stringify(result));
       }
     }

     return "Clusters Paused";
   };
   ```

   Replace the `projectIDs` array with your own project and cluster names.

   **Note:**

   To avoid hardcoding project and cluster names, you can use the [helper Functions](https://www.mongodb.com/docs/atlas/atlas-ui/triggers/scheduled-triggers-tutorial.md#std-label-scheduled-triggers-helper-functions) at the end of this tutorial to retrieve lists of projects and clusters from the Atlas Administration API and programmatically determine which clusters to pause and resume on a schedule.

2. Create the `pauseClusters` scheduled Trigger.

   From the Functions page, navigate to the Triggers page by clicking Triggers in the sidebar under the Build heading.

   Click Create a Trigger to open the Trigger configuration page.

   If you have an existing Trigger, click Add a
   Trigger

   Configure Trigger settings.

   In Trigger Details, set the following configuration:

   | Setting | Value |
   | --- | --- |
   | Trigger Type | Scheduled |
   | Schedule Type | Advanced. This allows you to specify a [CRON expression](https://www.mongodb.com/docs/atlas/app-services/triggers/scheduled-triggers.md#std-label-CRON-expressions) for the schedule. To run this every weekday evening at 6 PM US Eastern (which is 22:00 UTC), use the following CRON expression: `0 22 * * 1-5` |
   | Skip Events On Re-enable | On. This prevents the Trigger from executing on schedules that were queued while the Trigger was disabled. |
   | Event Type | Function. Select the `pauseClusters` Function from the dropdown. |
   | Trigger Name | `pauseClusters` |

   Click Save to create the Trigger.

   Your test clusters will now automatically pause every evening at 6 PM US Eastern.

3. Create the `resumeClusters` Function.

   Duplicate the `pauseClusters` Function into a new Function named `resumeClusters`.

   In the Function Editor tab, update the `paused` state to `false` in the Function code:

   ```javascript
   /*
    * Iterates over the provided projects and clusters, resuming those clusters.
    */
   exports = async function () {

     // Supply project IDs and cluster names to resume
     const projectIDs = [
       {
         id: "<projectIdA>",
         names: [ "<clusterNameA>", "<clusterNameB>" ]
       },
       {
         id: "<projectIdB>",
         names: [ "<clusterNameC>" ]
       }
     ];

     // Set desired state
     const body = { paused: false };

     // Resume each cluster and log the response
     for (const project of projectIDs) {
       for (const cluster of project.names) {
         const result = await context.functions.execute(
           "modifyCluster",
           project.id,
           cluster,
           body,
         );
         console.log("Cluster " + cluster + ": " + EJSON.stringify(result));
       }
     }

     return "Clusters Resumed";
   };
   ```

4. Create the `resumeClusters` scheduled Trigger.

   From the Functions page, navigate to the Triggers page by clicking Triggers in the sidebar under the Build heading.

   Configure Trigger settings.

   In Trigger Details, set the following configuration:

   | Setting | Value |
   | --- | --- |
   | Trigger Type | Scheduled |
   | Schedule Type | Advanced. This allows you to specify a [CRON expression](https://www.mongodb.com/docs/atlas/app-services/triggers/scheduled-triggers.md#std-label-CRON-expressions) for the schedule. To run this every weekday morning at 8 AM US Eastern (which is 12:00 UTC), use the following CRON expression: `0 12 * * 1-5` |
   | Skip Events On Re-enable | On. This prevents the Trigger from executing on schedules that were queued while the Trigger was disabled. |
   | Event Type | Function. Select the `resumeClusters` Function from the dropdown. |
   | Trigger Name | `resumeClusters` |

   Click Save to create the Trigger.

   Your test clusters will now pause every evening and resume every weekday morning automatically.

## Scale Clusters on a Schedule

This procedure creates scheduled Triggers to automatically scale a cluster up during peak hours and down afterwards. This is useful for clusters that have predictable usage patterns where you want to proactively scale before the workload increases, and scale down afterwards to save costs.

**Note:**

Atlas supports [Cluster Auto-Scaling](https://www.mongodb.com/docs/atlas/cluster-autoscaling.md#std-label-cluster-autoscaling) to automatically increase your cluster tier or storage capacity based on usage or predicted usage. However, if you have predictable peak usage windows, you can use scheduled Triggers to proactively scale your cluster before your workload increases.

1. Create the `scaleClusterUp` Function.

   In Atlas, go to the Triggers page.

   If it's not already displayed, select the organization that contains your project from the  Organizations menu in the navigation bar.

   If it's not already displayed, select your project from the Projects menu in the navigation bar.

   In the sidebar, click Triggers under the Streaming Data heading.

   The [Triggers](https://cloud.mongodb.com/go?l=https%3A%2F%2Fcloud.mongodb.com%2Fv2%2F%3Cproject%3E%23%2Ftriggers) page displays.

   Navigate to the Functions Page

   Click the Linked App Service: Triggers link.

   In the sidebar, click Functions under the Build heading.

   Click Create a Function.

   The Settings tab displays by default.

   Enter `scaleClusterUp` as the Name for the Function.

   Set Private to `true`. This Function will only be called by the `scaleClusterUp` Trigger in this tutorial.

   Leave the other configuration options in the Settings tab at their default values.

   Define the Function code.

   From the Create Function page, click the Function Editor tab and paste the following code to define your Function:

   ```javascript
   /*
    * Scales a single cluster up to a larger instance size.
    * This example scales an AWS cluster up to M30 in region US_EAST_1.
    */
   exports = async function() {
     // Supply project ID and cluster name...
     const projectID   = "<projectId>";
     const clusterName = "<clusterName>";

     // Set the desired instance size and topology...
     const body = {
       replicationSpecs: [
         {
           regionConfigs: [
             {
               electableSpecs: {
                 instanceSize: "M30", // for example, larger tier
                 nodeCount: 3
               },
               priority:     7,
               providerName: "AWS",
               regionName:   "US_EAST_1"
             }
           ]
         }
       ]
     };

     // Scale up the cluster and log the response
     const result = await context.functions.execute(
       "modifyCluster",
       projectID,
       clusterName,
       body
     );
     console.log(EJSON.stringify(result));

     return clusterName + " scaled up";
   };
   ```

   Replace the `<projectId>` and `<clusterName>` placeholders with your own project ID and cluster name, and adjust the `regionConfigs` array for your own topology.

   See the [Update One Cluster in One Project](https://www.mongodb.com/docs/atlas/reference/api-resources-spec/v2/#operation/updateGroupCluster) endpoint documentation for more details on the available fields you can include in the request body to modify your cluster's configuration.

2. Create the `scaleClusterUp` scheduled Trigger.

   From the Functions page, navigate to the Triggers page by clicking Triggers in the sidebar under the Build heading.

   Click Create a Trigger to open the Trigger configuration page.

   If you have an existing Trigger, click Add a
   Trigger

   Configure Trigger settings.

   In Trigger Details, set the following configuration:

   | Setting | Value |
   | --- | --- |
   | Trigger Type | Scheduled |
   | Schedule Type | Advanced. This allows you to specify a [CRON expression](https://www.mongodb.com/docs/atlas/app-services/triggers/scheduled-triggers.md#std-label-CRON-expressions) for the schedule. To run this every morning at 8 AM US Eastern (which is 13:00 UTC), use the following CRON expression: `0 13 * * *` |
   | Skip Events On Re-enable | On. This prevents the Trigger from executing on schedules that were queued while the Trigger was disabled. |
   | Event Type | Function. Select the `pauseClusters` Function from the dropdown. |
   | Trigger Name | `scaleClusterUp` |

   Click Save to create the Trigger.

   Your test clusters will now automatically scale up every morning at 8 AM US Eastern.

3. Create the `scaleClusterDown` Function.

   Duplicate the `scaleClusterUp` Function into a new Function named `scaleClusterDown`.

   In the Function Editor tab, paste and adjust the following code to scale your cluster down to the specified configuration:

   ```javascript
   /*
    * Scales a single cluster down to a smaller instance size.
    * This example scales an AWS cluster down to M10 in region US_EAST_1.
    */
   exports = async function() {
     const projectID   = "<projectId>";
     const clusterName = "<clusterName>";

     const body = {
       replicationSpecs: [
         {
           regionConfigs: [
             {
               electableSpecs: {
                 instanceSize: "M10", // for example, smaller tier
                 nodeCount: 3
               },
               priority:     7,
               providerName: "AWS",
               regionName:   "US_EAST_1"
             }
           ]
         }
       ]
     };

     // Scale down the cluster and log the response
     const result = await context.functions.execute(
       "modifyCluster",
       projectID,
       clusterName,
       body
     );
     console.log(EJSON.stringify(result));

     return clusterName + " scaled down";
   };
   ```

   Replace the `<projectId>` and `<clusterName>` placeholders with your own project ID and cluster name, and adjust the `regionConfigs` array for your own topology.

   See the [Update One Cluster in One Project](https://www.mongodb.com/docs/atlas/reference/api-resources-spec/v2/#operation/updateGroupCluster) endpoint documentation for more details on the available fields you can include in the request body to modify your cluster's configuration.

4. Create the `scaleClusterDown` scheduled Trigger.

   From the Functions page, navigate to the Triggers page by clicking Triggers in the sidebar under the Build heading.

   Configure Trigger settings.

   In Trigger Details, set the following configuration:

   | Setting | Value |
   | --- | --- |
   | Trigger Type | Scheduled |
   | Schedule Type | Advanced. This allows you to specify a [CRON expression](https://www.mongodb.com/docs/atlas/app-services/triggers/scheduled-triggers.md#std-label-CRON-expressions) for the schedule. To run this every evening at 6 PM US Eastern (which is 22:00 UTC), use the following CRON expression: `0 22 * * *` |
   | Skip Events On Re-enable | On. This prevents the Trigger from executing on schedules that were queued while the Trigger was disabled. |
   | Event Type | Function. Select the `scaleClusterDown` Function from the dropdown. |
   | Trigger Name | `scaleClusterDown` |

   Click Save to create the Trigger.

   Together, these two Triggers ensure the cluster runs at higher capacity during busy hours and scales down afterwards.

## Optional Helper Functions

The following helper Functions can be test run from the Triggers Function Editor to list projects and clusters in your organization in order to specify which clusters you want to target in the Functions in this tutorial. You can also call these Functions from other Functions to retrieve this information programmatically.

### getProjects

#### List all projects in the organization.

`getProjects()` calls the [Return All Projects](https://www.mongodb.com/docs/atlas/reference/api-resources-spec/v2/#operation/listGroups) endpoint to return all projects in your organization.

```javascript
/*
 * Returns an array of the projects in the organization
 * See https://docs.atlas.mongodb.com/reference/api/project-get-all/
 *
 * Returns an array of objects, e.g.
 *
 * {
 * "clusterCount": {
 *      "$numberInt": "1"
 *    },
 *    "created": "2021-05-11T18:24:48Z",
 *    "id": "609acbef1b76b53fcd37c8e1",
 *    "links": [
 *      {
 *        "href": "https://cloud.mongodb.com/api/atlas/v1.0/groups/609acbef1b76b53fcd37c8e1",
 *        "rel": "self"
 *      }
 *    ],
 *    "name": "mg-training-sample",
 *    "orgId": "5b4e2d803b34b965050f1835"
 *  }
  *
 */
exports = async function() {
  
  // Retrieve headers to authenticate with a new access token, and define the request URL for the Atlas API endpoint
  const authHeaders = await context.functions.execute("getAuthHeaders");
  const requestUrl = `https://cloud.mongodb.com/api/atlas/v2/groups`;

  // Build the argument for the HTTP request to the Atlas API to get all projects in the organization
  const arg = {
    url: requestUrl,
    headers: authHeaders.headers
  };

  // The response body is a BSON.Binary object; parse it and return the `results` array, which contains the list of projects for the organization
  response = await context.http.get(arg);
  return EJSON.parse(response.body.text()).results; 
};
```

### getProjectClusters

#### List all clusters in a project.

`getProjectClusters(<projectId>)` calls the [Return All Clusters in One Project](https://www.mongodb.com/docs/atlas/reference/api-resources-spec/v2/#operation/listGroupClusters) endpoint to return all clusters in the project with the specified project ID.

```javascript
/*
 * Returns an array of the clusters for the supplied project ID.
 * See https://docs.atlas.mongodb.com/reference/api/clusters-get-all/
 *
 * Returns an array of objects. See the API documentation for details.
 * 
 */
exports = async function(projectId) {
  
  if (projectId == "Hello world!") { // Easy testing from the console
    projectId = "<projectId>"
  }
  
  // Retrieve headers to authenticate with a new access token, and define the request URL for the Atlas API endpoint
  const authHeaders = await context.functions.execute("getAuthHeaders");
  const requestUrl = `https://cloud.mongodb.com/api/atlas/v2/groups/${projectId}/clusters`;
  
  // Build the argument for the HTTP request to the Atlas API to get all clusters in the project
  const arg = {
    url: requestUrl,
    headers: authHeaders.headers
  };

  // The response body is a BSON.Binary object; parse it and return the `results` array, which contains the list of clusters for the project
  response = await context.http.get(arg);
  return EJSON.parse(response.body.text()).results; 
};
```

Replace the placeholder `<projectId>` with your own project ID.
