Connecting Mongo Cloud Atlas to GCP via Pulumi

· 1 min read

Didn't find a simple starter example of how to easily connect MongoDB Cloud Atlas to GCP via Pulumi for Infrastructure as Code. Read comments in code for further explanation of expected values.

1) create the provider for mongo

 const mongoDbAtlasProvider = new mongodbatlas.Provider(
    `${Env}-provider`,
    {
      /**
       * publicKey and privateKey created manually at https://cloud.mongodb.com/v2#/org/{YOUR_ORG_ID}/access/apiKeys
       * Mongo Web UI > Organizations > Billie > Identity and Access Management > Applications> API Keys
       */
      publicKey: getPulumiConfigSecret("mongoPublicKey"),
      privateKey: getPulumiConfigSecret("mongoPrivateKey"),
    }
  );

2) Create the cluster

const mongoDbCluster = new mongodbatlas.Cluster(
    `${Env}-mongo-db-cluster`,
    {
      // the projectId (an alphanumeric string) similar to the ObjectId in the mongo web UI
      projectId: Config.mongoDbAtlas.projectId,
      name: `${Env}-mongo-db-cluster`,
      providerName: "GCP",
      // Matching "atlas region" to GCP region as in https://www.mongodb.com/docs/atlas/reference/google-gcp/
      providerRegionName: "CENTRAL_US",
      mongoDbMajorVersion: "8.0",
      diskSizeGb: 10,
      providerInstanceSizeName: "M10",
      cloudBackup: true,
    },
    {
      provider: mongoDbAtlasProvider, // Don't forget this 
      dependsOn: [mongoDbAtlasProvider],
    }
  );

3) Create a user, it must be created in admin DB, this will allow that user to create DB, read and write to collections but not to drop DBs


  const mongoDbClusterUser = new mongodbatlas.DatabaseUser(
    `${Env}-mongo-db-cluster-user`,
    {
      projectId: Config.mongoDbAtlas.projectId,
      authDatabaseName: "admin", // user must be created in admin database
      username: `${Env}-mongo-db-cluster-user`,
      password: `${Env}-mongo-db-cluster-password`,
      roles: [
        {
          databaseName: "admin", // user must be created in admin database
          // Roles as defined: https://www.mongodb.com/docs/api/doc/atlas-admin-api-v2/operation/operation-creategroupdatabaseuser
          roleName: "readWriteAnyDatabase", //allows to create, read and write to any database but not drop the databases
        },
      ],
      scopes: [{ name: mongoDbCluster.name, type: "CLUSTER" }],
    },
    {
      provider: mongoDbAtlasProvider,
      dependsOn: [mongoDbCluster],
    }
  );

This should work for terraform as well.