Gunakan CreateMaintenanceWindow dengan AWS SDK atau CLI - AWS Systems Manager

Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.

Gunakan CreateMaintenanceWindow dengan AWS SDK atau CLI

Contoh kode berikut menunjukkan cara menggunakanCreateMaintenanceWindow.

Contoh tindakan adalah kutipan kode dari program yang lebih besar dan harus dijalankan dalam konteks. Anda dapat melihat tindakan ini dalam konteks dalam contoh kode berikut:

CLI
AWS CLI

Contoh 1: Untuk membuat jendela pemeliharaan

create-maintenance-windowContoh berikut membuat jendela pemeliharaan baru yang setiap lima menit hingga dua jam (sesuai kebutuhan), mencegah tugas baru dimulai dalam waktu satu jam setelah akhir eksekusi jendela pemeliharaan, memungkinkan target yang tidak terkait (contoh yang belum Anda daftarkan dengan jendela pemeliharaan), dan menunjukkan melalui penggunaan tag khusus bahwa pembuatnya bermaksud menggunakannya dalam tutorial.

aws ssm create-maintenance-window \ --name "My-Tutorial-Maintenance-Window" \ --schedule "rate(5 minutes)" \ --duration 2 --cutoff 1 \ --allow-unassociated-targets \ --tags "Key=Purpose,Value=Tutorial"

Output:

{ "WindowId": "mw-0c50858d01EXAMPLE" }

Contoh 2: Untuk membuat jendela pemeliharaan yang berjalan hanya sekali

create-maintenance-windowContoh berikut membuat jendela pemeliharaan baru yang hanya berjalan satu kali pada tanggal dan waktu yang ditentukan.

aws ssm create-maintenance-window \ --name My-One-Time-Maintenance-Window \ --schedule "at(2020-05-14T15:55:00)" \ --duration 5 \ --cutoff 2 \ --allow-unassociated-targets \ --tags "Key=Environment,Value=Production"

Output:

{ "WindowId": "mw-01234567890abcdef" }

Untuk informasi selengkapnya, lihat Pemeliharaan Windows di Panduan Pengguna AWS Systems Manager.

Java
SDKuntuk Java 2.x
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode 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]; }
JavaScript
SDKuntuk JavaScript (v3)
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS.

import { CreateMaintenanceWindowCommand, SSMClient } from "@aws-sdk/client-ssm"; import { parseArgs } from "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; } } };
PowerShell
Alat untuk PowerShell

Contoh 1: Contoh ini membuat jendela pemeliharaan baru dengan nama tertentu yang berjalan pada pukul 4 sore setiap hari Selasa selama 4 jam, dengan cutoff 1 jam, dan yang memungkinkan target yang tidak terkait.

New-SSMMaintenanceWindow -Name "MyMaintenanceWindow" -Duration 4 -Cutoff 1 -AllowUnassociatedTarget $true -Schedule "cron(0 16 ? * TUE *)"

Output:

mw-03eb53e1ea7383998
Python
SDKuntuk Python (Boto3)
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode 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

Untuk daftar lengkap panduan AWS SDK pengembang dan contoh kode, lihatMenggunakan Systems Manager dengan AWS SDK. Topik ini juga mencakup informasi tentang memulai dan detail tentang SDK versi sebelumnya.