本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
CreateMaintenanceWindow
搭配 AWS SDK 或 CLI 使用
下列程式碼範例示範如何使用 CreateMaintenanceWindow
。
動作範例是大型程式的程式碼摘錄,必須在內容中執行。您可以在下列程式碼範例的內容中看到此動作:
- CLI
-
- AWS CLI
-
範例 1:建立維護時段
下列
create-maintenance-window
範例會建立一個新的維護時段,該維護時段每五分鐘 (最長持續兩個小時,視需要) 防止新任務在維護時段執行結束後一小時內啟動、允許未關聯的目標 (尚未向維護時段註冊的執行個體),以及透過使用其建立者打算在教學課程中使用的自訂標籤來進行表示。aws ssm create-maintenance-window \ --name
"My-Tutorial-Maintenance-Window"
\ --schedule"rate(5 minutes)"
\ --duration2
--cutoff1
\ --allow-unassociated-targets \ --tags"Key=Purpose,Value=Tutorial"
輸出:
{ "WindowId": "mw-0c50858d01EXAMPLE" }
範例 2:建立只執行一次的維護時段
下列
create-maintenance-window
範例會建立只在指定的日期和時間執行一次的新維護時段。aws ssm create-maintenance-window \ --name
My-One-Time-Maintenance-Window
\ --schedule"at(2020-05-14T15:55:00)"
\ --duration5
\ --cutoff2
\ --allow-unassociated-targets \ --tags"Key=Environment,Value=Production"
輸出:
{ "WindowId": "mw-01234567890abcdef" }
如需詳細資訊,請參閱《AWS Systems Manager 使用者指南》中的 Maintenance Windows。
-
如需 API 詳細資訊,請參閱《AWS CLI 命令參考》中的 CreateMaintenanceWindow
。
-
- Java
-
- SDK for Java 2.x
-
注意
GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 /** * Creates an SSM maintenance window asynchronously. * * @param winName The name of the maintenance window. * @return The ID of the created or existing maintenance window. * <p> * This method initiates an asynchronous request to create an SSM maintenance window. * If the request is successful, it prints the maintenance window ID. * If an exception occurs, it handles the error appropriately. */ public String createMaintenanceWindow(String winName) throws SsmException, DocumentAlreadyExistsException { CreateMaintenanceWindowRequest request = CreateMaintenanceWindowRequest.builder() .name(winName) .description("This is my maintenance window") .allowUnassociatedTargets(true) .duration(2) .cutoff(1) .schedule("cron(0 10 ? * MON-FRI *)") .build(); CompletableFuture<CreateMaintenanceWindowResponse> future = getAsyncClient().createMaintenanceWindow(request); final String[] windowId = {null}; future.whenComplete((response, ex) -> { if (response != null) { String maintenanceWindowId = response.windowId(); System.out.println("The maintenance window id is " + maintenanceWindowId); windowId[0] = maintenanceWindowId; } else { Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex; if (cause instanceof DocumentAlreadyExistsException) { throw new CompletionException(cause); } else if (cause instanceof SsmException) { throw new CompletionException(cause); } else { throw new RuntimeException(cause); } } }).join(); if (windowId[0] == null) { MaintenanceWindowFilter filter = MaintenanceWindowFilter.builder() .key("name") .values(winName) .build(); DescribeMaintenanceWindowsRequest winRequest = DescribeMaintenanceWindowsRequest.builder() .filters(filter) .build(); CompletableFuture<DescribeMaintenanceWindowsResponse> describeFuture = getAsyncClient().describeMaintenanceWindows(winRequest); describeFuture.whenComplete((describeResponse, describeEx) -> { if (describeResponse != null) { List<MaintenanceWindowIdentity> windows = describeResponse.windowIdentities(); if (!windows.isEmpty()) { windowId[0] = windows.get(0).windowId(); System.out.println("Window ID: " + windowId[0]); } else { System.out.println("Window not found."); windowId[0] = ""; } } else { Throwable describeCause = (describeEx instanceof CompletionException) ? describeEx.getCause() : describeEx; throw new RuntimeException("Error describing maintenance windows: " + describeCause.getMessage(), describeCause); } }).join(); } return windowId[0]; }
-
如需 API 詳細資訊,請參閱《AWS SDK for Java 2.x API 參考》中的 CreateMaintenanceWindow。
-
- JavaScript
-
- SDK for JavaScript (v3)
-
注意
GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 import { CreateMaintenanceWindowCommand, SSMClient } from "@aws-sdk/client-ssm"; import { parseArgs } from "node:util"; /** * Create an SSM maintenance window. * @param {{ name: string, allowUnassociatedTargets: boolean, duration: number, cutoff: number, schedule: string, description?: string }} */ export const main = async ({ name, allowUnassociatedTargets, // Allow the maintenance window to run on managed nodes, even if you haven't registered those nodes as targets. duration, // The duration of the maintenance window in hours. cutoff, // The number of hours before the end of the maintenance window that Amazon Web Services Systems Manager stops scheduling new tasks for execution. schedule, // The schedule of the maintenance window in the form of a cron or rate expression. description = undefined, }) => { const client = new SSMClient({}); try { const { windowId } = await client.send( new CreateMaintenanceWindowCommand({ Name: name, Description: description, AllowUnassociatedTargets: allowUnassociatedTargets, // Allow the maintenance window to run on managed nodes, even if you haven't registered those nodes as targets. Duration: duration, // The duration of the maintenance window in hours. Cutoff: cutoff, // The number of hours before the end of the maintenance window that Amazon Web Services Systems Manager stops scheduling new tasks for execution. Schedule: schedule, // The schedule of the maintenance window in the form of a cron or rate expression. }), ); console.log(`Maintenance window created with Id: ${windowId}`); return { WindowId: windowId }; } catch (caught) { if (caught instanceof Error && caught.name === "MissingParameter") { console.warn(`${caught.message}. Did you provide these values?`); } else { throw caught; } } };
-
如需 API 詳細資訊,請參閱《AWS SDK for JavaScript API 參考》中的 CreateMaintenanceWindow。
-
- PowerShell
-
- Tools for PowerShell
-
範例 1:此範例會建立一個具有指定名稱的新維護時段,該維護時段在每個星期二下午 4 點執行 4 小時並有一個 1 小時的截止,而且允許未關聯的目標。
New-SSMMaintenanceWindow -Name "MyMaintenanceWindow" -Duration 4 -Cutoff 1 -AllowUnassociatedTarget $true -Schedule "cron(0 16 ? * TUE *)"
輸出:
mw-03eb53e1ea7383998
-
如需 API 詳細資訊,請參閱《AWS Tools for PowerShell Cmdlet 參考》中的 CreateMaintenanceWindow。
-
- Python
-
- SDK for Python (Boto3)
-
注意
GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 class MaintenanceWindowWrapper: """Encapsulates AWS Systems Manager maintenance window actions.""" def __init__(self, ssm_client): """ :param ssm_client: A Boto3 Systems Manager client. """ self.ssm_client = ssm_client self.window_id = None self.name = None @classmethod def from_client(cls): ssm_client = boto3.client("ssm") return cls(ssm_client) def create(self, name, schedule, duration, cutoff, allow_unassociated_targets): """ Create an AWS Systems Manager maintenance window. :param name: The name of the maintenance window. :param schedule: The schedule of the maintenance window. :param duration: The duration of the maintenance window. :param cutoff: The cutoff time of the maintenance window. :param allow_unassociated_targets: Allow the maintenance window to run on managed nodes, even if you haven't registered those nodes as targets. """ try: response = self.ssm_client.create_maintenance_window( Name=name, Schedule=schedule, Duration=duration, Cutoff=cutoff, AllowUnassociatedTargets=allow_unassociated_targets, ) self.window_id = response["WindowId"] self.name = name logger.info("Created maintenance window %s.", self.window_id) except ParamValidationError as error: logger.error( "Parameter validation error when trying to create maintenance window %s. Here's why: %s", self.window_id, error, ) raise except ClientError as err: logger.error( "Couldn't create maintenance window %s. Here's why: %s: %s", name, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise
-
如需 API 詳細資訊,請參閱《AWS SDK for Python (Boto3) API 參考》中的 CreateMaintenanceWindow。
-
如需 AWS SDK 開發人員指南和程式碼範例的完整清單,請參閱 將此服務與 AWS SDK 搭配使用。此主題也包含有關入門的資訊和舊版 SDK 的詳細資訊。