このチュートリアルでは、Atlas のスケジュールされたトリガーを使用して、プログラムで Atlas Administration APIを呼び出し、クラスター管理タスクを自動化します。
このチュートリアルには、次の手順が含まれています。
初期設定: 既存の Atlasプロジェクトに対して 権限を持つ サービス アカウントを作成し、サービスアカウントの認証情報を 値とシークレット
Project Ownerとして保存し、これらの認証情報を使用して 1 つのクラスターで 1 つのアップデートを呼び出す再利用可能な関数を作成します。プロジェクト エンドポイント。注意
サービス アカウントの代わりにAPIキーを使用して、 権限を持つ Atlas Administration APIで認証する場合は、
Project OwnerAPI公開キーと秘密キーを 値と秘密キー として保存し、このチュートリアルの関数で使用できます。予定されたクラスターの一時停止と再開: スケジュールされたトリガーを作成して、クラスターを自動的に一時停止し、毎週午前に再開します。
スケジュールでクラスターをスケーリング: スケジュールされたトリガーを作成して、ピーク時間帯にクラスターを自動的に増やすアップし、その後はダウンします。
必要な権限
このチュートリアルを完了するには、 MongoDB AtlasプロジェクトへのProject Owner アクセス権を持つユーザーが必要です。
初期設定
この初期設定は一度だけ完了する必要があり、このページで予定されたトリガーを作成してクラスター管理タスクを自動化できます。このチュートリアルを実行する前に、少なくとも 1 つのクラスターを含むMongoDB Atlasプロジェクトがあることを確認してください。この手順では、次のセットアップ タスクを実行します。
Atlas サービス アカウントの認証情報を作成して保存します。このアカウントは、既存の Atlasプロジェクトに対する
Project Owner権限を持つ Atlas Administration API を呼び出すために使用します。サービス アカウントの認証情報を使用してアクセス トークンを生成し、Atlas Administration APIを呼び出すための適切な認証ヘッダーを返す
getAuthHeadersという再利用可能な関数を作成します。modifyCluster1 つのプロジェクトAPIの 1 つのクラスターの更新をラップする という再利用可能な関数を作成します。
サービス アカウントの作成
trigger が既存の Atlasプロジェクトに対するProject Owner 権限を持つ Atlas Administration API を呼び出すために使用できるサービス アカウントを作成するには、次の手順に従います。
Atlasで、Go Users{0 ページに します。
まだ表示されていない場合は、以下から目的の組織を選択しますナビゲーション バーのOrganizationsメニュー
サイドバーの [Identity & Access] セクションの下の [All Projects] をクリックし、目的のプロジェクトを選択します。
サイドバーの [Security] セクションの下の [Project Identity & Access] をクリックします。
[ ユーザー ] ページが表示されます。
Create ApplicationService Account[ をクリックします。
サービスアカウント情報を入力します。
名前: サービス アカウントの名前。 (例:
TriggersServiceAccount)説明: (任意)サービス アカウントの説明。 (例: Atlas Administration APIを呼び出すための Atlas Function のサービス アカウント。)
サービス アカウントの権限:
Project Owner
[Create] をクリックします。
これにより、サービス アカウントが作成され、権限
Organization Memberを持つプロジェクトの親組織に自動的に追加されます。API Access List を設定します。
このサービス アカウントで Atlas Administration API を呼び出せるIPアドレスを制限する場合は、API Access List にIPアドレスを追加します。
注意
組織で Require IP Access List for the Atlas Administration API が有効になっている場合、またはサービス アカウントの API Access List にIPアドレスを追加した場合、すべての Atlas Administration APIリクエストはIPアクセス リスト チェックに合格する必要があります。
Atlas triggers と Functions は、特定のアウトバウンドIPアドレスのセットから送信HTTPリクエストを送信します。スケジュールされたトリガーで Atlas Administration APIやその他の外部サービスを呼び出すようにするには、これらのIPアドレスをサービス アカウントの API Access List に追加する必要があります。
Atlas Functionで使用されるアウトバウンドIPアドレスの完全なリストについては、「 関数のセキュリティ アウトバウンドIPアクセス 」を参照してください。各IPアドレスを個別に追加する必要があります。
サービス アカウントの認証情報を 値とシークレット として保存します。
サービス アカウントの認証情報を保存するには、次の値とシークレットを作成します。
AtlasClientIdサービス アカウントクライアントIDを含む値。AtlasClientSecretサービス アカウントクライアントシークレットを含む シークレットAtlasClientSecretシークレットにリンクする値。これにより、シークレットとして安全に保存されたままに、関数内のクライアントシークレット値にアクセスできるようになります。
Atlas で、 Triggers ページに移動します。
まだ表示されていない場合は、プロジェクトを含む組織をナビゲーション バーの Organizations メニューで選択します。
まだ表示されていない場合は、ナビゲーション バーの Projects メニューからプロジェクトを選択します。
サイドバーで、 Streaming Data見出しの下のTriggersをクリックします。
Triggersページが表示されます。
Values ページに移動します。
Linked App Service: Triggersリンクをクリックします。
サイドバーで、 Build見出しの下のValuesをクリックします。
クライアントID を値 に保存します。
クリック Create a Value
Value Name として
AtlasClientIdを入力します。Valueタイプを選択します。
Custom Content オプションを選択し、クライアントIDを入力します。
注意
クライアントID は、引用符(
"<clientId>")を含む文字列として入力する必要があります。[Save] をクリックします。
クライアントシークレットを シークレット に保存し、それを 値にリンクします。
注意
シークレット値には直接アクセスできないため、シークレットにリンクする 2 番目の 値 を作成する必要があります。
[Create a Value] をクリックします。
Value Name として
AtlasClientSecretを入力します。Valueタイプを選択します。
Link to Secret オプションを選択します。
シークレット値に名前を付けるには、「
AtlasClientSecret」と入力し、Create "AtlasClientSecret" をクリックします。シークレット名の下に表示される Client Secretフィールドにクライアントシークレットを貼り付けます。
シークレットと値の両方を作成するには、Save をクリックします。
getAuthHeaders関数を作成します。
サービス アカウントの認証情報を使用してアクセス トークンを取得し、 Atlas Administration APIを呼び出すための適切な認証ヘッダーを返す再利用可能な関数を作成するには、次の手順に従います。
Functions ページに移動します。
サイドバーで、 Build見出しの下のFunctionsをクリックします。
[Create a Function] をクリックします。
Settingsタブにはデフォルトで が表示されます。
関数の Name として
getAuthHeadersを入力します。Private を
trueに設定します。この関数は、このチュートリアルでは他の関数によってのみ呼び出されます。Settingsタブのその他の構成オプションはデフォルト値のままにします。
関数 コードを定義します。
[Function Editor ] タブをクリックし、次のコードを貼り付けて関数を定義します。
1 /* 2 * Generate API request headers with a new Service Account Access Token. 3 */ 4 exports = async function getAuthHeaders() { 5 6 // Get stored credentials 7 clientId = context.values.get("AtlasClientId"); 8 clientSecret = context.values.get("AtlasClientSecret"); 9 10 // Throw an error if credentials are missing 11 if (!clientId || !clientSecret) { 12 throw new Error("Authentication credentials not found. Set AtlasClientId/AtlasClientSecret (service account auth credentials)."); 13 } 14 15 // Define the argument for the HTTP request to get the access token 16 const tokenUrl = "https://cloud.mongodb.com/api/oauth/token"; 17 const credentials = Buffer.from(`${clientId}:${clientSecret}`).toString("base64"); 18 19 const arg = { 20 url: tokenUrl, 21 headers: { 22 "Authorization": [ `Basic ${credentials}` ], 23 "Content-Type": [ "application/x-www-form-urlencoded" ] 24 }, 25 body: "grant_type=client_credentials" 26 } 27 28 // The response body is a BSON.Binary object; parse it to extract the access token 29 const response = await context.http.post(arg); 30 const tokenData = JSON.parse(response.body.text()); 31 const accessToken = tokenData.access_token; 32 33 // Define the Accept header with the resource version from env var or default to latest stable 34 const resourceVersion = context.environment.ATLAS_API_VERSION || "2025-03-12"; 35 const acceptHeader = `application/vnd.atlas.${resourceVersion}+json`; 36 37 // Return the access token as headers for future API calls 38 return { 39 headers: { 40 "Authorization": [ `Bearer ${accessToken}` ], 41 "Accept": [ acceptHeader ], 42 "Accept-Encoding": [ "bzip, deflate" ], 43 "Content-Type": [ "application/json" ] 44 } 45 }; 46 }
modifyCluster関数を作成します。
1 つのプロジェクトの 1 つのクラスターの更新 をラップする再利用可能な関数 エンドポイントを作成するには、次の手順に従います。
Functions ページから、Create a Function をクリックします。
Settingsタブにはデフォルトで が表示されます。
関数の Name として
modifyClusterを入力します。Private を
trueに設定します。この関数は、このチュートリアルでは他の関数によってのみ呼び出されます。Settingsタブのその他の構成オプションはデフォルト値のままにします。
関数 コードを定義します。
[Function Editor ] タブをクリックし、次のコードを貼り付けて関数を定義します。
1 /* 2 * Modifies the cluster as defined by the `body` parameter. 3 * See https://www.mongodb.com/ja-jp/docs/atlas/reference/api-resources-spec/v2/#tag/Clusters/operation/updateCluster 4 */ 5 exports = async function(projectID, clusterName, body) { 6 7 // Easy testing from the console 8 if (projectID === "Hello world!") { 9 projectID = "<projectId>"; 10 clusterName = "<clusterName>"; 11 body = { paused: false }; 12 } 13 14 // Retrieve headers to authenticate with a new access token, and define the request URL for the Atlas API endpoint 15 const authHeaders = await context.functions.execute("getAuthHeaders"); 16 const requestUrl = `https://cloud.mongodb.com/api/atlas/v2/groups/${projectID}/clusters/${clusterName}`; 17 18 // Build the argument for the HTTP request to the Atlas API to modify the cluster 19 const arg = { 20 url: requestUrl, 21 headers: authHeaders.headers, 22 body: JSON.stringify(body) 23 }; 24 25 // The response body is a BSON.Binary object; parse it and return the modified cluster description 26 const response = await context.http.patch(arg); 27 if (response.body) { 28 return EJSON.parse(response.body.text()); 29 } else { 30 throw new Error(`No response body returned from Atlas API. Status code: ${response.status}`); 31 } 32 }; 注意
関数エディターでコードをテストします。
Testing Console で関数を実行すると、Function Editor は最初の引数として
"Hello world!"を自動的に提供します。このコードはその入力をテストし、"Hello world!"が受信された場合は パラメーターに値を提供します。独自の入力で関数をテストするには、次のプレースホルダー値を独自の情報に置き換えます。
<projectId><clusterName>bodyパラメーターでは、クラスターに加える変更を含むペイロードを指定します。例コードには、クラスターを一時停止するペイロードが含まれています。
スケジュールされたクラスターの一時停止と再開
この手順では、クラスターを自動的に一時停止し、各日の午前中に再開する予定されたトリガーが作成されます。これは、営業時間外で実行する必要がない非本番クラスターや、スケジュール時に自動的に一時停止して再開したいクラスターに便利です。
pauseClusters関数を作成します。
Atlas で、 Triggers ページに移動します。
まだ表示されていない場合は、プロジェクトを含む組織をナビゲーション バーの Organizations メニューで選択します。
まだ表示されていない場合は、ナビゲーション バーの Projects メニューからプロジェクトを選択します。
サイドバーで、 Streaming Data見出しの下のTriggersをクリックします。
Triggersページが表示されます。
Functionsページに移動します
Linked App Service: Triggersリンクをクリックします。
サイドバーで、 Build見出しの下のFunctionsをクリックします。
[Create a Function] をクリックします。
Settingsタブにはデフォルトで が表示されます。
関数の Name として
pauseClustersを入力します。Private を
trueに設定します。この関数は、このチュートリアルではpauseClusterstrigger によってのみ呼び出されます。Settingsタブのその他の構成オプションはデフォルト値のままにします。
関数 コードを定義します。
[Function Editor ] タブをクリックし、次のコードを貼り付けて関数を定義します。
1 /* 2 * Iterates over the provided projects and clusters, pausing those clusters. 3 */ 4 exports = async function () { 5 6 // Supply project IDs and cluster names to pause 7 const projectIDs = [ 8 { 9 id: "<projectIdA>", 10 names: [ "<clusterNameA>", "<clusterNameB>" ] 11 }, 12 { 13 id: "<projectIdB>", 14 names: [ "<clusterNameC>" ] 15 } 16 ]; 17 18 // Set desired state 19 const body = { paused: true }; 20 21 // Pause each cluster and log the response 22 for (const project of projectIDs) { 23 for (const cluster of project.names) { 24 const result = await context.functions.execute( 25 "modifyCluster", 26 project.id, 27 cluster, 28 body, 29 ); 30 console.log("Cluster " + cluster + ": " + EJSON.stringify(result)); 31 } 32 } 33 34 return "Clusters Paused"; 35 }; projectIDs配列を独自のプロジェクトとクラスター名に置き換えます。
pauseClustersの予定されたトリガーを作成します。
Functions ページから、Build 見出しの下のサイドバーにある Triggers をクリックして、Triggers ページに移動します。
Create a Triggerをクリックしてトリガー設定ページを開きます。
既存の trigger がある場合は、次をクリックします Add a Trigger
trigger 設定を構成します。
Trigger Details で、次の構成を設定します。
設定値trigger タイプ
スケジュール
スケジュールの種類
再有効化時にイベントをスキップ
。これにより、trigger が無効になっている間にキューに入れられたスケジュールで trigger が実行されなくなります。
eventType
関数。ドロップダウンから
pauseClusters関数を選択します。trigger 名
pauseClusterstrigger を作成するには、Save をクリックします。
テスト クラスターは、毎日午前 606 時(米国東部)に自動的に一時停止されるようになりました。
resumeClusters関数を作成します。
pauseClusters関数をresumeClustersという名前の新しい関数に複製します。Function Editorタブで、関数コードで
paused状態をfalseに更新します。1 /* 2 * Iterates over the provided projects and clusters, resuming those clusters. 3 */ 4 exports = async function () { 5 6 // Supply project IDs and cluster names to resume 7 const projectIDs = [ 8 { 9 id: "<projectIdA>", 10 names: [ "<clusterNameA>", "<clusterNameB>" ] 11 }, 12 { 13 id: "<projectIdB>", 14 names: [ "<clusterNameC>" ] 15 } 16 ]; 17 18 // Set desired state 19 const body = { paused: false }; 20 21 // Resume each cluster and log the response 22 for (const project of projectIDs) { 23 for (const cluster of project.names) { 24 const result = await context.functions.execute( 25 "modifyCluster", 26 project.id, 27 cluster, 28 body, 29 ); 30 console.log("Cluster " + cluster + ": " + EJSON.stringify(result)); 31 } 32 } 33 34 return "Clusters Resumed"; 35 };
resumeClustersの予定されたトリガーを作成します。
Functions ページから、Build 見出しの下のサイドバーにある Triggers をクリックして、Triggers ページに移動します。
trigger 設定を構成します。
Trigger Details で、次の構成を設定します。
設定値trigger タイプ
スケジュール
スケジュールの種類
再有効化時にイベントをスキップ
。これにより、trigger が無効になっている間にキューに入れられたスケジュールで trigger が実行されなくなります。
eventType
関数。ドロップダウンから
resumeClusters関数を選択します。trigger 名
resumeClusterstrigger を作成するには、Save をクリックします。
これで、テスト クラスターは毎週ごとに一時停止され、毎週午前に自動的に再開されます。
一定のスケジュールでクラスターを拡張する
この手順では、ピーク時間帯にクラスターを自動的に増やすアップし、その後はダウンするようにスケジュールされたトリガーを作成します。これは、ワークロードが増加する前に積極的に増やす、その後は増やすしてコストを節約したい、予測可能な使用パターンを持つクラスターに役立ちます。
注意
Atlas は、使用状況または予測された使用量に基づいて、クラスター層またはストレージキャパシティーを自動的に増やすためのクラスター オートスケーリング をサポートしています。ただし、予測可能なピーク使用期間がある場合は、スケジュールされた trigger を使用して、ワークロードが増加する前にクラスターを積極的に増やすできます。
scaleClusterUp関数を作成します。
Atlas で、 Triggers ページに移動します。
まだ表示されていない場合は、プロジェクトを含む組織をナビゲーション バーの Organizations メニューで選択します。
まだ表示されていない場合は、ナビゲーション バーの Projects メニューからプロジェクトを選択します。
サイドバーで、 Streaming Data見出しの下のTriggersをクリックします。
Triggersページが表示されます。
Functionsページに移動します
Linked App Service: Triggersリンクをクリックします。
サイドバーで、 Build見出しの下のFunctionsをクリックします。
[Create a Function] をクリックします。
Settingsタブにはデフォルトで が表示されます。
関数の Name として
scaleClusterUpを入力します。Private を
trueに設定します。この関数は、このチュートリアルではscaleClusterUptrigger によってのみ呼び出されます。Settingsタブのその他の構成オプションはデフォルト値のままにします。
関数 コードを定義します。
Create Function ページから、Function Editorタブをクリックし、次のコードを貼り付けて関数を定義します。
1 /* 2 * Scales a single cluster up to a larger instance size. 3 * This example scales an AWS cluster up to M30 in region US_EAST_1. 4 */ 5 exports = async function() { 6 // Supply project ID and cluster name... 7 const projectID = "<projectId>"; 8 const clusterName = "<clusterName>"; 9 10 // Set the desired instance size and topology... 11 const body = { 12 replicationSpecs: [ 13 { 14 regionConfigs: [ 15 { 16 electableSpecs: { 17 instanceSize: "M30", // for example, larger tier 18 nodeCount: 3 19 }, 20 priority: 7, 21 providerName: "AWS", 22 regionName: "US_EAST_1" 23 } 24 ] 25 } 26 ] 27 }; 28 29 // Scale up the cluster and log the response 30 const result = await context.functions.execute( 31 "modifyCluster", 32 projectID, 33 clusterName, 34 body 35 ); 36 console.log(EJSON.stringify(result)); 37 38 return clusterName + " scaled up"; 39 }; <projectId>と<clusterName>のプレースホルダーを独自のプロジェクトIDとクラスター名に置き換え、regionConfigs配列を独自のトポロジーに合わせて調整します。クラスターの構成を変更するためにリクエスト本文に含めることができるフィールドの詳細については、「 1 つのプロジェクトの 1 つのクラスターの更新 」エンドポイントのドキュメントを参照してください。
scaleClusterUpの予定されたトリガーを作成します。
Functions ページから、Build 見出しの下のサイドバーにある Triggers をクリックして、Triggers ページに移動します。
Create a Triggerをクリックしてトリガー設定ページを開きます。
既存の trigger がある場合は、次をクリックします Add a Trigger
trigger 設定を構成します。
Trigger Details で、次の構成を設定します。
設定値trigger タイプ
スケジュール
スケジュールの種類
再有効化時にイベントをスキップ
。これにより、trigger が無効になっている間にキューに入れられたスケジュールで trigger が実行されなくなります。
eventType
関数。ドロップダウンから
pauseClusters関数を選択します。trigger 名
scaleClusterUptrigger を作成するには、Save をクリックします。
テスト クラスターは、毎日午前8 60 時(米国東部)にテスト クラスターが自動的に増やすアップされるようになりました。
scaleClusterDown関数を作成します。
scaleClusterUp関数をscaleClusterDownという名前の新しい関数に複製します。Function Editorタブで、次のコードを貼り付けて調整し、指定された構成にクラスターを増やすダウンします。
1 /* 2 * Scales a single cluster down to a smaller instance size. 3 * This example scales an AWS cluster down to M10 in region US_EAST_1. 4 */ 5 exports = async function() { 6 const projectID = "<projectId>"; 7 const clusterName = "<clusterName>"; 8 9 const body = { 10 replicationSpecs: [ 11 { 12 regionConfigs: [ 13 { 14 electableSpecs: { 15 instanceSize: "M10", // for example, smaller tier 16 nodeCount: 3 17 }, 18 priority: 7, 19 providerName: "AWS", 20 regionName: "US_EAST_1" 21 } 22 ] 23 } 24 ] 25 }; 26 27 // Scale down the cluster and log the response 28 const result = await context.functions.execute( 29 "modifyCluster", 30 projectID, 31 clusterName, 32 body 33 ); 34 console.log(EJSON.stringify(result)); 35 36 return clusterName + " scaled down"; 37 }; <projectId>と<clusterName>のプレースホルダーを独自のプロジェクトIDとクラスター名に置き換え、regionConfigs配列を独自のトポロジーに合わせて調整します。クラスターの構成を変更するためにリクエスト本文に含めることができるフィールドの詳細については、「 1 つのプロジェクトの 1 つのクラスターの更新 」エンドポイントのドキュメントを参照してください。
scaleClusterDownの予定されたトリガーを作成します。
Functions ページから、Build 見出しの下のサイドバーにある Triggers をクリックして、Triggers ページに移動します。
trigger 設定を構成します。
Trigger Details で、次の構成を設定します。
設定値trigger タイプ
スケジュール
スケジュールの種類
再有効化時にイベントをスキップ
。これにより、trigger が無効になっている間にキューに入れられたスケジュールで trigger が実行されなくなります。
eventType
関数。ドロップダウンから
scaleClusterDown関数を選択します。trigger 名
scaleClusterDowntrigger を作成するには、Save をクリックします。
これら 2 つの trigger を組み合わせると、クラスターがピーク時間帯により高いキャパシティーで実行され、その後はスケールダウンされます。
オプションのヘルパー関数
次のヘルパー関数は、Triggers 関数エディターからテスト実行して、組織内のプロジェクトとクラスターを一覧表示して、このチュートリアルの関数でターゲットにするクラスターを指定できます。また、他の関数からこれらの関数を呼び出して、プログラムでこの情報を検索することもできます。
getProjects() 組織内のすべてのプロジェクトを返すには、すべてのプロジェクトを返すエンドポイントを呼び出します。
1 /* 2 * Returns an array of the projects in the organization 3 * See https://mongodb.com/ja-jp/docs/atlas/reference/api/project-get-all/ 4 * 5 * Returns an array of objects, e.g. 6 * 7 * { 8 * "clusterCount": { 9 * "$numberInt": "1" 10 * }, 11 * "created": "2021-05-11T18:24:48Z", 12 * "id": "609acbef1b76b53fcd37c8e1", 13 * "links": [ 14 * { 15 * "href": "https://cloud.mongodb.com/api/atlas/v1.0/groups/609acbef1b76b53fcd37c8e1", 16 * "rel": "self" 17 * } 18 * ], 19 * "name": "mg-training-sample", 20 * "orgId": "5b4e2d803b34b965050f1835" 21 * } 22 * 23 */ 24 exports = async function() { 25 26 // Retrieve headers to authenticate with a new access token, and define the request URL for the Atlas API endpoint 27 const authHeaders = await context.functions.execute("getAuthHeaders"); 28 const requestUrl = `https://cloud.mongodb.com/api/atlas/v2/groups`; 29 30 // Build the argument for the HTTP request to the Atlas API to get all projects in the organization 31 const arg = { 32 url: requestUrl, 33 headers: authHeaders.headers 34 }; 35 36 // The response body is a BSON.Binary object; parse it and return the `results` array, which contains the list of projects for the organization 37 response = await context.http.get(arg); 38 return EJSON.parse(response.body.text()).results; 39 };
getProjectClusters(<projectId>) は、指定されたプロジェクトIDを持つプロジェクト内のすべてのクラスターを返すために、「1 つのプロジェクトのすべてのクラスターを返す」エンドポイントを呼び出します。
1 /* 2 * Returns an array of the clusters for the supplied project ID. 3 * See https://mongodb.com/ja-jp/docs/atlas/reference/api/clusters-get-all/ 4 * 5 * Returns an array of objects. See the API documentation for details. 6 * 7 */ 8 exports = async function(projectId) { 9 10 if (projectId == "Hello world!") { // Easy testing from the console 11 projectId = "<projectId>" 12 } 13 14 // Retrieve headers to authenticate with a new access token, and define the request URL for the Atlas API endpoint 15 const authHeaders = await context.functions.execute("getAuthHeaders"); 16 const requestUrl = `https://cloud.mongodb.com/api/atlas/v2/groups/${projectId}/clusters`; 17 18 // Build the argument for the HTTP request to the Atlas API to get all clusters in the project 19 const arg = { 20 url: requestUrl, 21 headers: authHeaders.headers 22 }; 23 24 // The response body is a BSON.Binary object; parse it and return the `results` array, which contains the list of clusters for the project 25 response = await context.http.get(arg); 26 return EJSON.parse(response.body.text()).results; 27 };
プレースホルダー <projectId> を独自のプロジェクトIDに置き換えます。