文件 AWS SDK AWS 範例 SDK 儲存庫中有更多可用的
本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
CreateMaintenanceWindow
搭配 a 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 使用者指南中的維護 Windows。
-
如需 API 詳細資訊,請參閱 AWS CLI 命令參考中的 CreateMaintenanceWindow
。
-
- Java
-
- Java 2.x 的 SDK
-
注意
還有更多 on 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 詳細資訊,請參閱 CreateMaintenanceWindow AWS SDK for Java 2.x 參考中的 API。
-
- JavaScript
-
- SDK for JavaScript (v3)
-
注意
還有更多 on 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 詳細資訊,請參閱 CreateMaintenanceWindow AWS SDK for JavaScript 參考中的 API。
-
- PowerShell
-
- 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
-
- Python 的 SDK (Boto3)
-
注意
還有更多 on 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 詳細資訊,請參閱 CreateMaintenanceWindow AWS SDK for Python (Boto3) Word 參考中的 API。
-