Systems Manager examples using SDK for Java 2.x - Amazon SDK for Java 2.x
Services or capabilities described in Amazon Web Services documentation might vary by Region. To see the differences applicable to the China Regions, see Getting Started with Amazon Web Services in China (PDF).

Systems Manager examples using SDK for Java 2.x

The following code examples show you how to perform actions and implement common scenarios by using the Amazon SDK for Java 2.x with Systems Manager.

Actions are code excerpts from larger programs and must be run in context. While actions show you how to call individual service functions, you can see actions in context in their related scenarios and cross-service examples.

Scenarios are code examples that show you how to accomplish a specific task by calling multiple functions within the same service.

Each example includes a link to GitHub, where you can find instructions on how to set up and run the code in context.

Get started

The following code example shows how to get started using Systems Manager.

SDK for Java 2.x
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.ssm.SsmClient; import software.amazon.awssdk.services.ssm.model.DocumentFilter; import software.amazon.awssdk.services.ssm.model.ListDocumentsRequest; import software.amazon.awssdk.services.ssm.model.ListDocumentsResponse; public class HelloSSM { public static void main(String[] args) { final String usage = """ Usage: <awsAccount> Where: awsAccount - Your AWS Account number. """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String awsAccount = args[0] ; Region region = Region.US_EAST_1; SsmClient ssmClient = SsmClient.builder() .region(region) .build(); listDocuments(ssmClient, awsAccount); } /* This code automatically fetches the next set of results using the `nextToken` and stops once the desired maxResults (20 in this case) have been reached. */ public static void listDocuments(SsmClient ssmClient, String awsAccount) { String nextToken = null; int totalDocumentsReturned = 0; int maxResults = 20; do { ListDocumentsRequest request = ListDocumentsRequest.builder() .documentFilterList( DocumentFilter.builder() .key("Owner") .value(awsAccount) .build() ) .maxResults(maxResults) .nextToken(nextToken) .build(); ListDocumentsResponse response = ssmClient.listDocuments(request); response.documentIdentifiers().forEach(identifier -> System.out.println("Document Name: " + identifier.name())); nextToken = response.nextToken(); totalDocumentsReturned += response.documentIdentifiers().size(); } while (nextToken != null && totalDocumentsReturned < maxResults); } }
  • For API details, see listThings in Amazon SDK for Java 2.x API Reference.

Actions

The following code example shows how to use CreateDocument.

SDK for Java 2.x
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

// Create an AWS SSM document to use in this scenario. public static void createSSMDoc(SsmClient ssmClient, String docName) { // Create JSON for the content String jsonData = """ { "schemaVersion": "2.2", "description": "Run a simple shell command", "mainSteps": [ { "action": "aws:runShellScript", "name": "runEchoCommand", "inputs": { "runCommand": [ "echo 'Hello, world!'" ] } } ] } """; try { CreateDocumentRequest request = CreateDocumentRequest.builder() .content(jsonData) .name(docName) .documentType(DocumentType.COMMAND) .build(); // Create the document. CreateDocumentResponse response = ssmClient.createDocument(request); System.out.println("The status of the document is " + response.documentDescription().status()); } catch (DocumentAlreadyExistsException e) { System.err.println("The document already exists. Moving on." ); } catch (SsmException e) { System.err.println(e.getMessage()); System.exit(1); } }
  • For API details, see CreateDocument in Amazon SDK for Java 2.x API Reference.

The following code example shows how to use CreateMaintenanceWindow.

SDK for Java 2.x
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

public static String createMaintenanceWindow(SsmClient ssmClient, String winName) { 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(); try { CreateMaintenanceWindowResponse response = ssmClient.createMaintenanceWindow(request); String maintenanceWindowId = response.windowId(); System.out.println("The maintenance window id is " + maintenanceWindowId); return maintenanceWindowId; } catch (DocumentAlreadyExistsException e) { System.err.println("The maintenance window already exists. Moving on."); } catch (SsmException e) { System.err.println(e.getMessage()); System.exit(1); } MaintenanceWindowFilter filter = MaintenanceWindowFilter.builder() .key("name") .values(winName) .build(); DescribeMaintenanceWindowsRequest winRequest = DescribeMaintenanceWindowsRequest.builder() .filters(filter) .build(); String windowId = ""; DescribeMaintenanceWindowsResponse response = ssmClient.describeMaintenanceWindows(winRequest); List<MaintenanceWindowIdentity> windows = response.windowIdentities(); if (!windows.isEmpty()) { windowId = windows.get(0).windowId(); System.out.println("Window ID: " + windowId); } else { System.out.println("Window not found."); } return windowId; }

The following code example shows how to use CreateOpsItem.

SDK for Java 2.x
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

// Create an SSM OpsItem public static String createSSMOpsItem(SsmClient ssmClient, String title, String source, String category, String severity) { try { CreateOpsItemRequest opsItemRequest = CreateOpsItemRequest.builder() .description("Created by the Systems Manager Java API") .title(title) .source(source) .category(category) .severity(severity) .build(); CreateOpsItemResponse itemResponse = ssmClient.createOpsItem(opsItemRequest); return itemResponse.opsItemId(); } catch (SsmException e) { System.err.println(e.getMessage()); System.exit(1); } return ""; }
  • For API details, see CreateOpsItem in Amazon SDK for Java 2.x API Reference.

The following code example shows how to use DeleteDocument.

SDK for Java 2.x
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

// Deletes an AWS Systems Manager document. public static void deleteDoc(SsmClient ssmClient, String documentName) { try { DeleteDocumentRequest documentRequest = DeleteDocumentRequest.builder() .name(documentName) .build(); ssmClient.deleteDocument(documentRequest); System.out.println("The Systems Manager document was successfully deleted."); } catch (SsmException e) { System.err.println(e.getMessage()); System.exit(1); } }
  • For API details, see DeleteDocument in Amazon SDK for Java 2.x API Reference.

The following code example shows how to use DeleteMaintenanceWindow.

SDK for Java 2.x
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

public static void deleteMaintenanceWindow(SsmClient ssmClient, String winId) { try { DeleteMaintenanceWindowRequest windowRequest = DeleteMaintenanceWindowRequest.builder() .windowId(winId) .build(); ssmClient.deleteMaintenanceWindow(windowRequest); System.out.println("The maintenance window was successfully deleted."); } catch (SsmException e) { System.err.println(e.getMessage()); System.exit(1); } }

The following code example shows how to use DescribeOpsItems.

SDK for Java 2.x
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

public static void describeOpsItems(SsmClient ssmClient, String key) { try { OpsItemFilter filter = OpsItemFilter.builder() .key(OpsItemFilterKey.OPS_ITEM_ID) .values(key) .operator(OpsItemFilterOperator.EQUAL) .build(); DescribeOpsItemsRequest itemsRequest = DescribeOpsItemsRequest.builder() .maxResults(10) .opsItemFilters(filter) .build(); DescribeOpsItemsResponse itemsResponse = ssmClient.describeOpsItems(itemsRequest); List<OpsItemSummary> items = itemsResponse.opsItemSummaries(); for (OpsItemSummary item : items) { System.out.println("The item title is " + item.title() +" and the status is "+item.status().toString()); } } catch (SsmException e) { System.err.println(e.getMessage()); System.exit(1); } }
  • For API details, see DescribeOpsItems in Amazon SDK for Java 2.x API Reference.

The following code example shows how to use DescribeParameters.

SDK for Java 2.x
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.ssm.SsmClient; import software.amazon.awssdk.services.ssm.model.GetParameterRequest; import software.amazon.awssdk.services.ssm.model.GetParameterResponse; import software.amazon.awssdk.services.ssm.model.SsmException; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class GetParameter { public static void main(String[] args) { final String usage = """ Usage: <paraName> Where: paraName - The name of the parameter. """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String paraName = args[0]; Region region = Region.US_EAST_1; SsmClient ssmClient = SsmClient.builder() .region(region) .build(); getParaValue(ssmClient, paraName); ssmClient.close(); } public static void getParaValue(SsmClient ssmClient, String paraName) { try { GetParameterRequest parameterRequest = GetParameterRequest.builder() .name(paraName) .build(); GetParameterResponse parameterResponse = ssmClient.getParameter(parameterRequest); System.out.println("The parameter value is " + parameterResponse.parameter().value()); } catch (SsmException e) { System.err.println(e.getMessage()); System.exit(1); } } }

The following code example shows how to use PutParameter.

SDK for Java 2.x
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.ssm.SsmClient; import software.amazon.awssdk.services.ssm.model.ParameterType; import software.amazon.awssdk.services.ssm.model.PutParameterRequest; import software.amazon.awssdk.services.ssm.model.SsmException; public class PutParameter { public static void main(String[] args) { final String usage = """ Usage: <paraName> Where: paraName - The name of the parameter. paraValue - The value of the parameter. """; if (args.length != 2) { System.out.println(usage); System.exit(1); } String paraName = args[0]; String paraValue = args[1]; Region region = Region.US_EAST_1; SsmClient ssmClient = SsmClient.builder() .region(region) .build(); putParaValue(ssmClient, paraName, paraValue); ssmClient.close(); } public static void putParaValue(SsmClient ssmClient, String paraName, String value) { try { PutParameterRequest parameterRequest = PutParameterRequest.builder() .name(paraName) .type(ParameterType.STRING) .value(value) .build(); ssmClient.putParameter(parameterRequest); System.out.println("The parameter was successfully added."); } catch (SsmException e) { System.err.println(e.getMessage()); System.exit(1); } } }
  • For API details, see PutParameter in Amazon SDK for Java 2.x API Reference.

The following code example shows how to use SendCommand.

SDK for Java 2.x
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

// Sends a SSM command to a managed node. public static String sendSSMCommand(SsmClient ssmClient, String documentName, String instanceId) throws InterruptedException { // Before we use Document to send a command - make sure it is active. boolean isDocumentActive = false; DescribeDocumentRequest request = DescribeDocumentRequest.builder() .name(documentName) .build(); while (!isDocumentActive) { DescribeDocumentResponse response = ssmClient.describeDocument(request); String documentStatus = response.document().statusAsString(); if (documentStatus.equals("Active")) { System.out.println("The Systems Manager document is active and ready to use."); isDocumentActive = true; } else { System.out.println("The Systems Manager document is not active. Status: " + documentStatus); try { // Add a delay to avoid making too many requests. Thread.sleep(5000); // Wait for 5 seconds before checking again } catch (InterruptedException e) { e.printStackTrace(); } } } // Create the SendCommandRequest. SendCommandRequest commandRequest = SendCommandRequest.builder() .documentName(documentName) .instanceIds(instanceId) .build(); // Send the command. SendCommandResponse commandResponse = ssmClient.sendCommand(commandRequest); String commandId = commandResponse.command().commandId(); System.out.println("The command Id is " + commandId); // Wait for the command execution to complete. GetCommandInvocationRequest invocationRequest = GetCommandInvocationRequest.builder() .commandId(commandId) .instanceId(instanceId) .build(); System.out.println("Wait 5 secs"); TimeUnit.SECONDS.sleep(5); // Retrieve the command execution details. GetCommandInvocationResponse commandInvocationResponse = ssmClient.getCommandInvocation(invocationRequest); // Check the status of the command execution. CommandInvocationStatus status = commandInvocationResponse.status(); if (status == CommandInvocationStatus.SUCCESS) { System.out.println("Command execution successful."); } else { System.out.println("Command execution failed. Status: " + status); } return commandId; }
  • For API details, see SendCommand in Amazon SDK for Java 2.x API Reference.

The following code example shows how to use UpdateMaintenanceWindow.

SDK for Java 2.x
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

// Update the maintenance window schedule public static void updateSSMMaintenanceWindow(SsmClient ssmClient, String id, String name) { try { UpdateMaintenanceWindowRequest updateRequest = UpdateMaintenanceWindowRequest.builder() .windowId(id) .allowUnassociatedTargets(true) .duration(24) .enabled(true) .name(name) .schedule("cron(0 0 ? * MON *)") .build(); ssmClient.updateMaintenanceWindow(updateRequest); System.out.println("The Systems Manager maintenance window was successfully updated."); } catch (SsmException e) { System.err.println(e.getMessage()); System.exit(1); } }

The following code example shows how to use UpdateOpsItem.

SDK for Java 2.x
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

public static void resolveOpsItem(SsmClient ssmClient, String opsID) { try { UpdateOpsItemRequest opsItemRequest = UpdateOpsItemRequest.builder() .opsItemId(opsID) .status(OpsItemStatus.RESOLVED) .build(); ssmClient.updateOpsItem(opsItemRequest); } catch (SsmException e) { System.err.println(e.getMessage()); System.exit(1); } }
  • For API details, see UpdateOpsItem in Amazon SDK for Java 2.x API Reference.

Scenarios

The following code example shows how to work with Systems Manager maintenance windows, documents, and OpsItems.

SDK for Java 2.x
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.ssm.SsmClient; import software.amazon.awssdk.services.ssm.model.CommandInvocation; import software.amazon.awssdk.services.ssm.model.CommandInvocationStatus; import software.amazon.awssdk.services.ssm.model.CreateDocumentRequest; import software.amazon.awssdk.services.ssm.model.CreateDocumentResponse; import software.amazon.awssdk.services.ssm.model.CreateMaintenanceWindowRequest; import software.amazon.awssdk.services.ssm.model.CreateMaintenanceWindowResponse; import software.amazon.awssdk.services.ssm.model.CreateOpsItemRequest; import software.amazon.awssdk.services.ssm.model.CreateOpsItemResponse; import software.amazon.awssdk.services.ssm.model.DeleteDocumentRequest; import software.amazon.awssdk.services.ssm.model.DeleteMaintenanceWindowRequest; import software.amazon.awssdk.services.ssm.model.DeleteOpsItemRequest; import software.amazon.awssdk.services.ssm.model.DescribeDocumentRequest; import software.amazon.awssdk.services.ssm.model.DescribeDocumentResponse; import software.amazon.awssdk.services.ssm.model.DescribeMaintenanceWindowsRequest; import software.amazon.awssdk.services.ssm.model.DescribeMaintenanceWindowsResponse; import software.amazon.awssdk.services.ssm.model.DescribeOpsItemsRequest; import software.amazon.awssdk.services.ssm.model.DescribeOpsItemsResponse; import software.amazon.awssdk.services.ssm.model.DocumentAlreadyExistsException; import software.amazon.awssdk.services.ssm.model.DocumentType; import software.amazon.awssdk.services.ssm.model.GetCommandInvocationRequest; import software.amazon.awssdk.services.ssm.model.GetCommandInvocationResponse; import software.amazon.awssdk.services.ssm.model.GetOpsItemRequest; import software.amazon.awssdk.services.ssm.model.GetOpsItemResponse; import software.amazon.awssdk.services.ssm.model.ListCommandInvocationsRequest; import software.amazon.awssdk.services.ssm.model.ListCommandInvocationsResponse; import software.amazon.awssdk.services.ssm.model.MaintenanceWindowFilter; import software.amazon.awssdk.services.ssm.model.MaintenanceWindowIdentity; import software.amazon.awssdk.services.ssm.model.OpsItemDataValue; import software.amazon.awssdk.services.ssm.model.OpsItemFilter; import software.amazon.awssdk.services.ssm.model.OpsItemFilterKey; import software.amazon.awssdk.services.ssm.model.OpsItemFilterOperator; import software.amazon.awssdk.services.ssm.model.OpsItemStatus; import software.amazon.awssdk.services.ssm.model.OpsItemSummary; import software.amazon.awssdk.services.ssm.model.SendCommandRequest; import software.amazon.awssdk.services.ssm.model.SendCommandResponse; import software.amazon.awssdk.services.ssm.model.SsmException; import software.amazon.awssdk.services.ssm.model.UpdateMaintenanceWindowRequest; import software.amazon.awssdk.services.ssm.model.UpdateOpsItemRequest; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.concurrent.TimeUnit; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/setup.html * * * This Java program performs these tasks: * 1. Creates an AWS Systems Manager maintenance window with a default name or a user-provided name. * 2. Modifies the maintenance window schedule. * 3. Creates a Systems Manager document with a default name or a user-provided name. * 4. Sends a command to a specified EC2 instance using the created Systems Manager document and displays the time when the command was invoked. * 5. Creates a Systems Manager OpsItem with a predefined title, source, category, and severity. * 6. Updates and resolves the created OpsItem. * 7. Deletes the Systems Manager maintenance window, OpsItem, and document. */ public class SSMScenario { public static final String DASHES = new String(new char[80]).replace("\0", "-"); public static void main(String[] args) throws InterruptedException { String usage = """ Usage: <instanceId> <title> <source> <category> <severity> Where: instanceId - The Amazon EC2 Linux/UNIX instance Id that AWS Systems Manager uses (ie, i-0149338494ed95f06). title - The title of the parameter (default is Disk Space Alert). source - The source of the parameter (default is EC2). category - The category of the parameter. Valid values are 'Availability', 'Cost', 'Performance', 'Recovery', 'Security' (default is Performance). severity - The severity of the parameter. Severity should be a number from 1 to 4 (default is 2). """; if (args.length != 1) { System.out.println(usage); System.exit(1); } Scanner scanner = new Scanner(System.in); String documentName; String windowName; String instanceId = args[0]; String title = "Disk Space Alert" ; String source = "EC2" ; String category = "Performance" ; String severity = "2" ; Region region = Region.US_EAST_1; SsmClient ssmClient = SsmClient.builder() .region(region) .build(); System.out.println(DASHES); System.out.println(""" Welcome to the AWS Systems Manager SDK Getting Started scenario. This program demonstrates how to interact with Systems Manager using the AWS SDK for Java (v2). Systems Manager is the operations hub for your AWS applications and resources and a secure end-to-end management solution. The program's primary functions include creating a maintenance window, creating a document, sending a command to a document, listing documents, listing commands, creating an OpsItem, modifying an OpsItem, and deleting Systems Manager resources. Upon completion of the program, all AWS resources are cleaned up. Let's get started... Please hit Enter """); scanner.nextLine(); System.out.println(DASHES); System.out.println("Create a Systems Manager maintenance window."); System.out.println("Please enter the maintenance window name (default is ssm-maintenance-window):"); String win = scanner.nextLine(); windowName = win.isEmpty() ? "ssm-maintenance-window" : win; String winId = createMaintenanceWindow(ssmClient, windowName); System.out.println(DASHES); System.out.println("Modify the maintenance window by changing the schedule"); System.out.println("Please hit Enter"); scanner.nextLine(); updateSSMMaintenanceWindow(ssmClient, winId, windowName); System.out.println(DASHES); System.out.println("Create a document that defines the actions that Systems Manager performs on your EC2 instance."); System.out.println("Please enter the document name (default is ssmdocument):"); String doc = scanner.nextLine(); documentName = doc.isEmpty() ? "ssmdocument" : doc; createSSMDoc(ssmClient, documentName); System.out.println("Now we are going to run a command on an EC2 instance that echoes 'Hello, world!'"); System.out.println("Please hit Enter"); scanner.nextLine(); String commandId = sendSSMCommand(ssmClient, documentName, instanceId); System.out.println(DASHES); System.out.println("Lets get the time when the specific command was sent to the specific managed node"); System.out.println("Please hit Enter"); scanner.nextLine(); displayCommands(ssmClient, commandId); System.out.println(DASHES); System.out.println(DASHES); System.out.println(""" Now we will create a Systems Manager OpsItem. An OpsItem is a feature provided by the Systems Manager service. It is a type of operational data item that allows you to manage and track various operational issues, events, or tasks within your AWS environment. You can create OpsItems to track and manage operational issues as they arise. For example, you could create an OpsItem whenever your application detects a critical error or an anomaly in your infrastructure. """); System.out.println("Please hit Enter"); scanner.nextLine(); String opsItemId = createSSMOpsItem(ssmClient, title, source, category, severity); System.out.println(DASHES); System.out.println(DASHES); System.out.println("Now we will update the OpsItem "+opsItemId); System.out.println("Please hit Enter"); scanner.nextLine(); String description = "An update to "+opsItemId ; updateOpsItem(ssmClient, opsItemId, title, description); System.out.println("Now we will get the status of the OpsItem "+opsItemId); System.out.println("Please hit Enter"); scanner.nextLine(); describeOpsItems(ssmClient, opsItemId); System.out.println("Now we will resolve the OpsItem "+opsItemId); System.out.println("Please hit Enter"); scanner.nextLine(); resolveOpsItem(ssmClient, opsItemId); System.out.println(DASHES); System.out.println(DASHES); System.out.println("Would you like to delete the Systems Manager resources? (y/n)"); String delAns = scanner.nextLine().trim(); if (delAns.equalsIgnoreCase("y")) { System.out.println("You selected to delete the resources."); System.out.print("Press Enter to continue..."); scanner.nextLine(); deleteOpsItem(ssmClient, opsItemId); deleteMaintenanceWindow(ssmClient, winId); deleteDoc(ssmClient, documentName); } else { System.out.println("The Systems Manager resources will not be deleted"); } System.out.println(DASHES); System.out.println("This concludes the Systems Manager SDK Getting Started scenario."); System.out.println(DASHES); } // Displays the date and time when the specific command was invoked. public static void displayCommands(SsmClient ssmClient, String commandId) { try { ListCommandInvocationsRequest commandInvocationsRequest = ListCommandInvocationsRequest.builder() .commandId(commandId) .build(); ListCommandInvocationsResponse response = ssmClient.listCommandInvocations(commandInvocationsRequest); List<CommandInvocation> commandList = response.commandInvocations(); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.systemDefault()); for (CommandInvocation invocation : commandList) { System.out.println("The time of the command invocation is " + formatter.format(invocation.requestedDateTime())); } } catch (SsmException e) { System.err.println(e.getMessage()); System.exit(1); } } // Create an SSM OpsItem public static String createSSMOpsItem(SsmClient ssmClient, String title, String source, String category, String severity) { try { CreateOpsItemRequest opsItemRequest = CreateOpsItemRequest.builder() .description("Created by the Systems Manager Java API") .title(title) .source(source) .category(category) .severity(severity) .build(); CreateOpsItemResponse itemResponse = ssmClient.createOpsItem(opsItemRequest); return itemResponse.opsItemId(); } catch (SsmException e) { System.err.println(e.getMessage()); System.exit(1); } return ""; } // Update the AWS SSM OpsItem. public static void updateOpsItem(SsmClient ssmClient, String opsItemId, String title, String description) { Map<String, OpsItemDataValue> operationalData = new HashMap<>(); operationalData.put("key1", OpsItemDataValue.builder().value("value1").build()); operationalData.put("key2", OpsItemDataValue.builder().value("value2").build()); try { UpdateOpsItemRequest request = UpdateOpsItemRequest.builder() .opsItemId(opsItemId) .title(title) .operationalData(operationalData) .status(getOpsItem(ssmClient, opsItemId)) .description(description) .build(); ssmClient.updateOpsItem(request); } catch (SsmException e) { System.err.println(e.getMessage()); System.exit(1); } } public static void resolveOpsItem(SsmClient ssmClient, String opsID) { try { UpdateOpsItemRequest opsItemRequest = UpdateOpsItemRequest.builder() .opsItemId(opsID) .status(OpsItemStatus.RESOLVED) .build(); ssmClient.updateOpsItem(opsItemRequest); } catch (SsmException e) { System.err.println(e.getMessage()); System.exit(1); } } // Gets a specific OpsItem. private static OpsItemStatus getOpsItem(SsmClient ssmClient, String opsItemId) { GetOpsItemRequest itemRequest = GetOpsItemRequest.builder() .opsItemId(opsItemId) .build(); try { GetOpsItemResponse response = ssmClient.getOpsItem(itemRequest); return response.opsItem().status(); } catch (SsmException e) { System.err.println(e.getMessage()); System.exit(1); } return null; } // Sends a SSM command to a managed node. public static String sendSSMCommand(SsmClient ssmClient, String documentName, String instanceId) throws InterruptedException { // Before we use Document to send a command - make sure it is active. boolean isDocumentActive = false; DescribeDocumentRequest request = DescribeDocumentRequest.builder() .name(documentName) .build(); while (!isDocumentActive) { DescribeDocumentResponse response = ssmClient.describeDocument(request); String documentStatus = response.document().statusAsString(); if (documentStatus.equals("Active")) { System.out.println("The Systems Manager document is active and ready to use."); isDocumentActive = true; } else { System.out.println("The Systems Manager document is not active. Status: " + documentStatus); try { // Add a delay to avoid making too many requests. Thread.sleep(5000); // Wait for 5 seconds before checking again } catch (InterruptedException e) { e.printStackTrace(); } } } // Create the SendCommandRequest. SendCommandRequest commandRequest = SendCommandRequest.builder() .documentName(documentName) .instanceIds(instanceId) .build(); // Send the command. SendCommandResponse commandResponse = ssmClient.sendCommand(commandRequest); String commandId = commandResponse.command().commandId(); System.out.println("The command Id is " + commandId); // Wait for the command execution to complete. GetCommandInvocationRequest invocationRequest = GetCommandInvocationRequest.builder() .commandId(commandId) .instanceId(instanceId) .build(); System.out.println("Wait 5 secs"); TimeUnit.SECONDS.sleep(5); // Retrieve the command execution details. GetCommandInvocationResponse commandInvocationResponse = ssmClient.getCommandInvocation(invocationRequest); // Check the status of the command execution. CommandInvocationStatus status = commandInvocationResponse.status(); if (status == CommandInvocationStatus.SUCCESS) { System.out.println("Command execution successful."); } else { System.out.println("Command execution failed. Status: " + status); } return commandId; } // Deletes an AWS Systems Manager document. public static void deleteDoc(SsmClient ssmClient, String documentName) { try { DeleteDocumentRequest documentRequest = DeleteDocumentRequest.builder() .name(documentName) .build(); ssmClient.deleteDocument(documentRequest); System.out.println("The Systems Manager document was successfully deleted."); } catch (SsmException e) { System.err.println(e.getMessage()); System.exit(1); } } public static void deleteMaintenanceWindow(SsmClient ssmClient, String winId) { try { DeleteMaintenanceWindowRequest windowRequest = DeleteMaintenanceWindowRequest.builder() .windowId(winId) .build(); ssmClient.deleteMaintenanceWindow(windowRequest); System.out.println("The maintenance window was successfully deleted."); } catch (SsmException e) { System.err.println(e.getMessage()); System.exit(1); } } // Update the maintenance window schedule public static void updateSSMMaintenanceWindow(SsmClient ssmClient, String id, String name) { try { UpdateMaintenanceWindowRequest updateRequest = UpdateMaintenanceWindowRequest.builder() .windowId(id) .allowUnassociatedTargets(true) .duration(24) .enabled(true) .name(name) .schedule("cron(0 0 ? * MON *)") .build(); ssmClient.updateMaintenanceWindow(updateRequest); System.out.println("The Systems Manager maintenance window was successfully updated."); } catch (SsmException e) { System.err.println(e.getMessage()); System.exit(1); } } public static String createMaintenanceWindow(SsmClient ssmClient, String winName) { 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(); try { CreateMaintenanceWindowResponse response = ssmClient.createMaintenanceWindow(request); String maintenanceWindowId = response.windowId(); System.out.println("The maintenance window id is " + maintenanceWindowId); return maintenanceWindowId; } catch (DocumentAlreadyExistsException e) { System.err.println("The maintenance window already exists. Moving on."); } catch (SsmException e) { System.err.println(e.getMessage()); System.exit(1); } MaintenanceWindowFilter filter = MaintenanceWindowFilter.builder() .key("name") .values(winName) .build(); DescribeMaintenanceWindowsRequest winRequest = DescribeMaintenanceWindowsRequest.builder() .filters(filter) .build(); String windowId = ""; DescribeMaintenanceWindowsResponse response = ssmClient.describeMaintenanceWindows(winRequest); List<MaintenanceWindowIdentity> windows = response.windowIdentities(); if (!windows.isEmpty()) { windowId = windows.get(0).windowId(); System.out.println("Window ID: " + windowId); } else { System.out.println("Window not found."); } return windowId; } // Create an AWS SSM document to use in this scenario. public static void createSSMDoc(SsmClient ssmClient, String docName) { // Create JSON for the content String jsonData = """ { "schemaVersion": "2.2", "description": "Run a simple shell command", "mainSteps": [ { "action": "aws:runShellScript", "name": "runEchoCommand", "inputs": { "runCommand": [ "echo 'Hello, world!'" ] } } ] } """; try { CreateDocumentRequest request = CreateDocumentRequest.builder() .content(jsonData) .name(docName) .documentType(DocumentType.COMMAND) .build(); // Create the document. CreateDocumentResponse response = ssmClient.createDocument(request); System.out.println("The status of the document is " + response.documentDescription().status()); } catch (DocumentAlreadyExistsException e) { System.err.println("The document already exists. Moving on." ); } catch (SsmException e) { System.err.println(e.getMessage()); System.exit(1); } } public static void describeOpsItems(SsmClient ssmClient, String key) { try { OpsItemFilter filter = OpsItemFilter.builder() .key(OpsItemFilterKey.OPS_ITEM_ID) .values(key) .operator(OpsItemFilterOperator.EQUAL) .build(); DescribeOpsItemsRequest itemsRequest = DescribeOpsItemsRequest.builder() .maxResults(10) .opsItemFilters(filter) .build(); DescribeOpsItemsResponse itemsResponse = ssmClient.describeOpsItems(itemsRequest); List<OpsItemSummary> items = itemsResponse.opsItemSummaries(); for (OpsItemSummary item : items) { System.out.println("The item title is " + item.title() +" and the status is "+item.status().toString()); } } catch (SsmException e) { System.err.println(e.getMessage()); System.exit(1); } } public static void deleteOpsItem(SsmClient ssmClient, String opsId) { try { DeleteOpsItemRequest deleteOpsItemRequest = DeleteOpsItemRequest.builder() .opsItemId(opsId) .build(); ssmClient.deleteOpsItem(deleteOpsItemRequest); System.out.println(opsId +" Opsitem was deleted"); } catch (SsmException e) { System.err.println(e.getMessage()); System.exit(1); } } }