Utilizzare CreateMaintenanceWindow con un o AWS SDK CLI - Esempi di codice dell'AWS SDK

Ci sono altri AWS SDK esempi disponibili nel repository AWS Doc SDK Examples GitHub .

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

Utilizzare CreateMaintenanceWindow con un o AWS SDK CLI

I seguenti esempi di codice mostrano come utilizzareCreateMaintenanceWindow.

Gli esempi di operazioni sono estratti di codice da programmi più grandi e devono essere eseguiti nel contesto. È possibile visualizzare questa operazione nel contesto nel seguente esempio di codice:

CLI
AWS CLI

Esempio 1: creare una finestra di manutenzione

L'create-maintenance-windowesempio seguente crea una nuova finestra di manutenzione che ogni cinque minuti per un massimo di due ore (se necessario), impedisce l'avvio di nuove attività entro un'ora dalla fine dell'esecuzione della finestra di manutenzione, consente destinazioni non associate (istanze che non sono state registrate nella finestra di manutenzione) e indica, tramite l'uso di tag personalizzati, che il suo creatore intende utilizzarla in un 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" }

Esempio 2: creare una finestra di manutenzione che venga eseguita una sola volta

L'create-maintenance-windowesempio seguente crea una nuova finestra di manutenzione che viene eseguita una sola volta nella data e all'ora specificate.

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" }

Per ulteriori informazioni, vedere Maintenance Windows nella AWS Systems Manager User Guide.

Java
SDKper Java 2.x
Nota

C'è di più su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice 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]; }
PowerShell
Strumenti per PowerShell

Esempio 1: Questo esempio crea una nuova finestra di manutenzione con il nome specificato che viene eseguita alle 16:00 di ogni martedì per 4 ore, con un limite di 1 ora e che consente destinazioni non associate.

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

Output:

mw-03eb53e1ea7383998
Python
SDKper Python (Boto3)
Nota

C'è di più su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice 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