diff --git a/.doc_gen/metadata/ssm_metadata.yaml b/.doc_gen/metadata/ssm_metadata.yaml index 69c88fe7952..ee2f6556a85 100644 --- a/.doc_gen/metadata/ssm_metadata.yaml +++ b/.doc_gen/metadata/ssm_metadata.yaml @@ -1,4 +1,21 @@ # zexi 0.4.0 +ssm_Hello: + title: Hello &SYS; + title_abbrev: Hello &SYS; + synopsis: get started using &SYS;. + category: Hello + languages: + Java: + versions: + - sdk_version: 2 + github: javav2/example_code/ssm + sdkguide: + excerpts: + - description: + snippet_tags: + - ssm.java2.hello.main + services: + ssm: {listThings} ssm_DescribeParameters: title: Get information about &SYS; parameters using an &AWS; SDK title_abbrev: Get parameters information @@ -49,10 +66,10 @@ ssm_PutParameter: - ssm.rust.create-parameter services: ssm: {PutParameter} -ssm_CreateOpsItem: - title: Create a new OpsItem using an &AWS; SDK - title_abbrev: Create a new OpsItem - synopsis: create a new OpsItem. +ssm_createOpsItem: + title: Create an opsItem using the &SYS; SDK + title_abbrev: Create an opsItem + synopsis: create an opsItem. category: languages: Java: @@ -66,10 +83,78 @@ ssm_CreateOpsItem: - ssm.java2.create_ops.main services: ssm: {CreateOpsItem} -ssm_DescribeOpsItems: - title: Describe an OpsItem using an &AWS; SDK - title_abbrev: Describe an OpsItem - synopsis: describe an OpsItem. +ssm_updateMaintenanceWindow: + title: Update a maintenance window using the &SYS; SDK + title_abbrev: Update a maintenance window + synopsis: update a maintenance window. + category: + languages: + Java: + versions: + - sdk_version: 2 + github: javav2/example_code/ssm + sdkguide: + excerpts: + - description: + snippet_tags: + - ssm.java2.update_window.main + services: + ssm: {UpdateMaintenanceWindow} +ssm_createMaintenanceWindow: + title: Create a maintenance window using the &SYS; SDK + title_abbrev: Create a maintenance window + synopsis: create a maintenance window. + category: + languages: + Java: + versions: + - sdk_version: 2 + github: javav2/example_code/ssm + sdkguide: + excerpts: + - description: + snippet_tags: + - ssm.java2.create_window.main + services: + ssm: {CreateMaintenanceWindow} +ssm_sendCommand: + title: Send a command using the &SYS; SDK + title_abbrev: Send a command + synopsis: send a command. + category: + languages: + Java: + versions: + - sdk_version: 2 + github: javav2/example_code/ssm + sdkguide: + excerpts: + - description: + snippet_tags: + - ssm.Java2.send_command.main + services: + ssm: {SendCommand} +ssm_createDocument: + title: Create a document using the &SYS; SDK + title_abbrev: Create a document + synopsis: create a document. + category: + languages: + Java: + versions: + - sdk_version: 2 + github: javav2/example_code/ssm + sdkguide: + excerpts: + - description: + snippet_tags: + - ssm.java2.create_doc.main + services: + ssm: {CreateDocument} +ssm_describeOpsItems: + title: Describe an &SYS; Opsitem using the SDK + title_abbrev: Describe an Opsitem + synopsis: describe an Opsitem. category: languages: Java: @@ -82,10 +167,44 @@ ssm_DescribeOpsItems: snippet_tags: - ssm.java2.describe_ops.main services: - ssm: {DescribeOpsItems} + ssm: {DescribeOpsItems} +ssm_deleteMaintenanceWindow: + title: Delete a maintenance window using the &SYS; SDK + title_abbrev: Delete a maintenance window + synopsis: delete a maintenance window. + category: + languages: + Java: + versions: + - sdk_version: 2 + github: javav2/example_code/ssm + sdkguide: + excerpts: + - description: + snippet_tags: + - ssm.java2.delete_window.main + services: + ssm: {DeleteMaintenanceWindow} +ssm_deleteDocument: + title: Delete a document using the &SYS; SDK + title_abbrev: Delete a document + synopsis: delete a document. + category: + languages: + Java: + versions: + - sdk_version: 2 + github: javav2/example_code/ssm + sdkguide: + excerpts: + - description: + snippet_tags: + - ssm.Java2.delete_doc.main + services: + ssm: {DeleteDocument} ssm_UpdateOpsItem: - title: Updates an OpsItem using an &AWS; SDK - title_abbrev: Updates an OpsItem + title: Update an OpsItem using a &SYS; SDK + title_abbrev: Update an OpsItem synopsis: updates an OpsItem. category: languages: @@ -100,3 +219,20 @@ ssm_UpdateOpsItem: - ssm.Java2.resolve_ops.main services: ssm: {UpdateOpsItem} +ssm_Scenario: + title: Get started with &SYS; using an &AWS; SDK + title_abbrev: Get started with &SYS; + synopsis: work with &SYS; maintenance windows, documents, and OpsItems. + category: Scenarios + languages: + Java: + versions: + - sdk_version: 2 + github: javav2/example_code/ssm + sdkguide: + excerpts: + - description: + snippet_tags: + - ssm.java2.scenario.main + services: + ssm: {CreateOpsItem, CreateMaintenanceWindow, CreateDocument, SendCommand, CommandInvocations, DeleteMaintenanceWindow, UpdateOpsItem} diff --git a/getting_started_scenarios/ssm_scenario/Readme.md b/getting_started_scenarios/ssm_scenario/Readme.md new file mode 100644 index 00000000000..521dbd23580 --- /dev/null +++ b/getting_started_scenarios/ssm_scenario/Readme.md @@ -0,0 +1,45 @@ +# AWS Systems Management Getting Started Scenario + +## Introduction +This AWS Systems Manager getting started scenario demonstrates how to interact with the AWS Systems Manager service using an AWS SDK. The scenario covers various operations such as creating a maintenance window, creating an SSM document, sending a command to a managed node, creating an OpsItem, updating an OpsItem, and deleting SSM resources. + +## Setting up Resources +AWS Systems Manager Agent is Amazon software that runs on Amazon Elastic Compute Cloud (Amazon EC2) instances, edge devices, on-premises servers, and virtual machines (VMs). A Systems Manager Agent makes it possible for Systems Manager to update, manage, and configure these resources. To successfully run this getting started scenario, the EC2 instance must have a Systems Manager Agent. For more information, see [Working with SSM Agent](https://docs.aws.amazon.com/systems-manager/latest/userguide/ssm-agent.html). + +## Service Operations Invoked +The program performs the following tasks: + +1. Creates a Systems Manager maintenance window. +2. Modifies the maintenance window by changing the schedule. +3. Creates a Systems Manager document that defines the actions Systems Manager performs on managed nodes. +4. Sends a command to an EC2 instance using the created Systems Manager document. +5. Retrieves the time when the specific command was sent to the managed node. +6. Creates a Systems Manager OpsItem to track and manage an operational issue. +7. Updates the created OpsItem and gets the status. +8. Resolves the OpsItem. +9. Optionally deletes the Systems Manager resources (maintenance window, OpsItem, and document). + +## Usage +1. Clone the repository or download the source code. +2. Open the code in your preferred IDE. +3. This scenario requires the following variables: + - `instanceId`: The ID of the EC2 instance to send the command to. + - `title`: The title of the OpsItem to create. + - `source`: The source of the OpsItem. + - `category`: The category of the OpsItem. + - `severity`: The severity of the OpsItem. +4. Run the `SSMScenario` class. + +The program will guide you through the scenario, prompting you to enter the maintenance window name and the document name. The program will also display the progress and results of the various operations. + +## Code Explanation +The provided code demonstrates the following key features of the AWS SDK and the AWS Systems Manager service: + +1. **Maintenance Window Management**: The code uses the `SsmClient` to create, modify, and delete an SSM maintenance window. +2. **SSM Document Management**: The code creates an SSM document that defines the actions Systems Manager performs on managed nodes. +3. **Command Execution**: The code sends a command to an EC2 instance using the created SSM document and retrieves the timestamp of the command execution. +4. **OpsItem Management**: The code creates, updates, and resolves an SSM OpsItem to track and manage an operational issue. +5. **Error Handling**: The code includes exception handling for various SSM-related exceptions. +6. **User Interaction**: The code prompts the user for input, such as the maintenance window name and the document name. + +Overall, this AWS SDK Systems Manager code example is a resource for developers new to AWS Systems Manager and the AWS SDK. It provides a solid foundation for understanding and building applications that interact with the AWS Systems Manager service. \ No newline at end of file diff --git a/getting_started_scenarios/ssm_scenario/SPECIFICATION.md b/getting_started_scenarios/ssm_scenario/SPECIFICATION.md new file mode 100644 index 00000000000..5650e7dd090 --- /dev/null +++ b/getting_started_scenarios/ssm_scenario/SPECIFICATION.md @@ -0,0 +1,121 @@ +# AWS Systems Manager Engineering Specification + +## Overview + This SDK getting started scenario demonstrates how to interact with AWS Systems Manager using an AWS SDK. The provided code is an AWS application that demonstrates the usage of the AWS Systems Manager SDK to interact with various AWS Systems Manager service operations. + +## Scenario Program Flow + - Creates a Systems Manager maintenance window with a default name or a user-provided name. + - Modifies the maintenance window schedule. + - Creates a Systems Manager document with a default name or a user-provided name. + - Sends a command to a specified EC2 instance using the created document and display the time when the command was invoked. + - Creates a Systems Manager OpsItem with a predefined title, source, category, and severity. + - Updates and resolves the created OpsItem. + - Deletes the Systems Manager maintenance window, OpsItem, and document. + +## Hello SSM +This program is intended for users not familiar with Systems Manager SDK to easily get up and running. The logic is to show use of listDocumentsPaginator(). + +### Program execution +The following shows the output of the program in the console. + +``` + Document Name: AWSMigration-ConvertCentOsToRockyLinuxDistribution + Document Name: AWSMigration-CreateLoadBalanceAutoScaleGroup + Document Name: AWSMigration-EnableInspector +``` + + +## Scenario Program execution +The following shows the output of the program in the console. + + +``` +-------------------------------------------------------------------------------- +Welcome to the AWS Systems Manager SDK Getting Started scenario. +This Java program demonstrates how to interact with AWS Systems Manager using the AWS SDK. +AWS Systems Manager is the operations hub for your AWS applications and resources and a secure end-to-end management solution. +The program's primary functionalities 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 AWS SSM resources. +Upon completion of the program, all AWS resources are cleaned up. +Let's get started... +Please hit Enter + + +-------------------------------------------------------------------------------- +Create an SSM maintenance window. +Please enter the maintenance window name (default is ssm-maintenance-window): + +The maintenance window id is mw-0a782f69416fa2d68 +-------------------------------------------------------------------------------- +Modify the maintenance window by changing the schedule +Please hit Enter + +The SSM maintenance window was successfully updated +-------------------------------------------------------------------------------- +Create an SSM document that defines the actions that Systems Manager performs on your managed nodes. +Please enter the document name (default is ssmdocument): + +The status of the SSM document is Creating +-------------------------------------------------------------------------------- +Now we are going to run a command on an EC2 instance +Please hit Enter + +The SSM document is active and ready to use. +Command ID: ac4aef03-7d60-4fba-8d71-051defea89e2 +Wait 5 secs +Command execution successful +-------------------------------------------------------------------------------- +Lets get the time when the specific command was sent to the specific managed node +Please hit Enter + +The time of the command invocation is 2024-04-09 14:52:50 +-------------------------------------------------------------------------------- +-------------------------------------------------------------------------------- + Now we will create an SSM OpsItem. + SSM 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. + +Please hit Enter + +-------------------------------------------------------------------------------- +-------------------------------------------------------------------------------- +Now we will update SSM OpsItem oi-c1e5435471e9 +Please hit Enter + +Now we will resolve the SSM OpsItem oi-c1e5435471e9 +Please hit Enter + +-------------------------------------------------------------------------------- +-------------------------------------------------------------------------------- +Would you like to delete the AWS Systems Manager resources? (y/n) + +The AWS Systems Manager resources will not be deleted +-------------------------------------------------------------------------------- +This concludes the AWS Systems Manager SDK Getting Started scenario. +-------------------------------------------------------------------------------- + +``` +``` + +## Metadata + +The following table describes the metadata used in this SDK Getting Started Scenario. + + +| action | metadata file | metadata key | +|------------------------------|------------------------------|---------------------------------------- | +| `CreateOpsItem` | ssm_metadata.yaml | ssm_CreateOpsItem | +| `CreateMaintenanceWindow` | ssm_metadata.yaml | ssm_CreateMainWindow | +| `UpdateMaintenanceWindow` | ssm_metadata.yaml | ssm_UpdateMainWindow | +| `CreateDocument` | ssm_metadata.yaml | ssm_CreateDocument | +| `SendCommand ` | ssm_metadata.yaml | ssm_SendCommand | +| `CommandInvocations` | ssm_metadata.yaml | ssm_DescribeInvocation | +| `UpdateOpsItem` | ssm_metadata.yaml | ssm_UpdateOpsItem | +| `DeleteMaintenanceWindow ` | ssm_metadata.yaml | ssm_DeleteMainWindow | +| `DeleteDocument` | ssm_metadata.yaml | ssm_DeleteMainWindow | +| `DescribeOpsItems ` | ssm_metadata.yaml | ssm_DescribeOpsItems | diff --git a/javav2/example_code/sns/pom.xml b/javav2/example_code/sns/pom.xml index bf4682a1b26..76ea0aac09a 100644 --- a/javav2/example_code/sns/pom.xml +++ b/javav2/example_code/sns/pom.xml @@ -61,6 +61,11 @@ 5.9.2 test + + software.amazon.sns + sns-extended-client + 2.1.0 + org.junit.platform junit-platform-commons diff --git a/javav2/example_code/ssm/Readme.md b/javav2/example_code/ssm/Readme.md index bf7fe9f7648..bfd9ef9b50e 100644 --- a/javav2/example_code/ssm/Readme.md +++ b/javav2/example_code/ssm/Readme.md @@ -29,15 +29,35 @@ For prerequisites, see the [README](../../README.md#Prerequisites) in the `javav +### Get started + +- [Hello Systems Manager](src/main/java/com/example/ssm/HelloSSM.java#L6) (`listThings`) + + ### Single actions Code excerpts that show you how to call individual service functions. - [Add a parameter](src/main/java/com/example/ssm/PutParameter.java#L6) (`PutParameter`) -- [Create a new OpsItem](src/main/java/com/example/ssm/CreateOpsItem.java#L6) (`CreateOpsItem`) -- [Describe an OpsItem](src/main/java/com/example/ssm/DescribeOpsItems.java#L6) (`DescribeOpsItems`) +- [Create a document](src/main/java/com/example/scenario/SSMScenario.java#L474) (`CreateDocument`) +- [Create a maintenance window](src/main/java/com/example/scenario/SSMScenario.java#L428) (`CreateMaintenanceWindow`) +- [Create an OpsItem](src/main/java/com/example/scenario/SSMScenario.java#L226) (`CreateOpsItem`) +- [Create an opsItem](src/main/java/com/example/scenario/SSMScenario.java#L226) (`CreateOpsItem`) +- [Delete a document](src/main/java/com/example/scenario/SSMScenario.java#L370) (`DeleteDocument`) +- [Delete a maintenance window](src/main/java/com/example/scenario/SSMScenario.java#L388) (`DeleteMaintenanceWindow`) +- [Describe an OpsItem](src/main/java/com/example/scenario/SSMScenario.java#L516) (`DescribeOpsItems`) +- [Describe an Opsitem](src/main/java/com/example/scenario/SSMScenario.java#L516) (`DescribeOpsItems`) - [Get parameters information](src/main/java/com/example/ssm/GetParameter.java#L6) (`DescribeParameters`) -- [Updates an OpsItem](src/main/java/com/example/ssm/ResolveOpsItem.java#L6) (`UpdateOpsItem`) +- [Send a command](src/main/java/com/example/scenario/SSMScenario.java#L310) (`SendCommand`) +- [Update a maintenance window](src/main/java/com/example/scenario/SSMScenario.java#L405) (`UpdateMaintenanceWindow`) +- [Update an OpsItem](src/main/java/com/example/scenario/SSMScenario.java#L274) (`UpdateOpsItem`) + +### Scenarios + +Code examples that show you how to accomplish a specific task by calling multiple +functions within the same service. + +- [Get started with Systems Manager](src/main/java/com/example/scenario/SSMScenario.java) @@ -47,6 +67,13 @@ Code excerpts that show you how to call individual service functions. ### Instructions +AWS Systems Manager Agent (SSM Agent) is Amazon software that runs on Amazon Elastic Compute Cloud (Amazon EC2) instances, +edge devices, on-premises servers, and virtual machines (VMs). SSM Agent makes it possible for Systems Manager to +update, manage, and configure these resources. + +To successfully run this getting started scenario, the EC2 instance must have an SSM Agent. +For more information, see the following documentation topic [Working with SSM Agent](https://docs.aws.amazon.com/systems-manager/latest/userguide/ssm-agent.html). + @@ -64,7 +91,23 @@ Define these values to successfully run the JUnit tests: +#### Hello Systems Manager + +This example shows you how to get started using Systems Manager. + + + +#### Get started with Systems Manager + +This example shows you how to work with Systems Manager maintenance windows, documents, and Opsitems. + + + + + + + ### Tests diff --git a/javav2/example_code/ssm/src/main/java/com/example/scenario/SSMScenario.java b/javav2/example_code/ssm/src/main/java/com/example/scenario/SSMScenario.java new file mode 100644 index 00000000000..6a1ec33f079 --- /dev/null +++ b/javav2/example_code/ssm/src/main/java/com/example/scenario/SSMScenario.java @@ -0,0 +1,559 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.scenario; + +// snippet-start:[ssm.java2.scenario.main] +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: + <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); + } + + // snippet-start:[ssm.java2.describe_command.main] + // 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); + } + } + // snippet-end:[ssm.java2.describe_command.main] + + // snippet-start:[ssm.java2.create_ops.main] + // 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 ""; + } + // snippet-end:[ssm.java2.create_ops.main] + + // snippet-start:[ssm.java2.update_ops.main] + // 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); + } + } + // snippet-end:[ssm.java2.update_ops.main] + + // snippet-start:[ssm.Java2.resolve_ops.main] + 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); + } + } + // snippet-end:[ssm.Java2.resolve_ops.main] + + // snippet-start:[ssm.Java2.get_ops.main] + // 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; + } + // snippet-end:[ssm.Java2.get_ops.main] + + // snippet-start:[ssm.Java2.send_command.main] + // 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; + } + // snippet-end:[ssm.Java2.send_command.main] + + // snippet-start:[ssm.Java2.delete_doc.main] + // 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); + } + } + // snippet-end:[ssm.Java2.delete_doc.main] + + // snippet-start:[ssm.java2.delete_window.main] + 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); + } + } + // snippet-end:[ssm.java2.delete_window.main] + + // snippet-start:[ssm.java2.update_window.main] + // 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); + } + } + // snippet-end:[ssm.java2.update_window.main] + + // snippet-start:[ssm.java2.create_window.main] + 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; + } + // snippet-end:[ssm.java2.create_window.main] + + // snippet-start:[ssm.java2.create_doc.main] + // 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); + } + } + // snippet-end:[ssm.java2.create_doc.main] + + // snippet-start:[ssm.java2.describe_ops.main] + 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); + } + } + // snippet-end:[ssm.java2.describe_ops.main] + + 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); + } + } +} +// snippet-end:[ssm.java2.scenario.main] \ No newline at end of file diff --git a/javav2/example_code/ssm/src/main/java/com/example/ssm/CreateOpsItem.java b/javav2/example_code/ssm/src/main/java/com/example/ssm/CreateOpsItem.java deleted file mode 100644 index d946e96a5c0..00000000000 --- a/javav2/example_code/ssm/src/main/java/com/example/ssm/CreateOpsItem.java +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.ssm; - -// snippet-start:[ssm.java2.create_ops.main] -// snippet-start:[ssm.java2.create_ops.import] -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.ssm.SsmClient; -import software.amazon.awssdk.services.ssm.model.CreateOpsItemRequest; -import software.amazon.awssdk.services.ssm.model.CreateOpsItemResponse; -import software.amazon.awssdk.services.ssm.model.SsmException; -// snippet-end:[ssm.java2.create_ops.import] - -/** - * 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 CreateOpsItem { - public static void main(String[] args) { - - final String USAGE = """ - - Usage: - <title> <source> <category> <severity> - - Where: - title - The OpsItem title. - source - The origin of the OpsItem, such as Amazon EC2 or AWS Systems Manager. - category - A category to assign to an OpsItem. - severity - A severity to assign to an OpsItem. - """; - - if (args.length != 4) { - System.out.println(USAGE); - System.exit(1); - } - - String title = args[0]; - String source = args[1]; - String category = args[2]; - String severity = args[3]; - - Region region = Region.US_EAST_1; - SsmClient ssmClient = SsmClient.builder() - .region(region) - .build(); - - System.out - .println("The Id of the OpsItem is " + createNewOpsItem(ssmClient, title, source, category, severity)); - ssmClient.close(); - } - - public static String createNewOpsItem(SsmClient ssmClient, - String title, - String source, - String category, - String severity) { - - try { - CreateOpsItemRequest opsItemRequest = CreateOpsItemRequest.builder() - .description("Created by the SSM 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 ""; - } -} -// snippet-end:[ssm.java2.create_ops.main] diff --git a/javav2/example_code/ssm/src/main/java/com/example/ssm/DescribeOpsItems.java b/javav2/example_code/ssm/src/main/java/com/example/ssm/DescribeOpsItems.java deleted file mode 100644 index 73c5c98262b..00000000000 --- a/javav2/example_code/ssm/src/main/java/com/example/ssm/DescribeOpsItems.java +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.ssm; - -// snippet-start:[ssm.java2.describe_ops.main] -// snippet-start:[ssm.java2.describe_ops.import] -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.ssm.SsmClient; -import software.amazon.awssdk.services.ssm.model.DescribeOpsItemsRequest; -import software.amazon.awssdk.services.ssm.model.DescribeOpsItemsResponse; -import software.amazon.awssdk.services.ssm.model.OpsItemSummary; -import software.amazon.awssdk.services.ssm.model.SsmException; -import java.util.List; -// snippet-end:[ssm.java2.describe_ops.import] - -/** - * 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 DescribeOpsItems { - - public static void main(String[] args) { - Region region = Region.US_EAST_1; - SsmClient ssmClient = SsmClient.builder() - .region(region) - .build(); - - describeItems(ssmClient); - ssmClient.close(); - } - - public static void describeItems(SsmClient ssmClient) { - try { - DescribeOpsItemsRequest itemsRequest = DescribeOpsItemsRequest.builder() - .maxResults(10) - .build(); - - DescribeOpsItemsResponse itemsResponse = ssmClient.describeOpsItems(itemsRequest); - List<OpsItemSummary> items = itemsResponse.opsItemSummaries(); - for (OpsItemSummary item : items) { - System.out.println("The item title is " + item.title()); - } - - } catch (SsmException e) { - System.err.println(e.getMessage()); - System.exit(1); - } - } -} -// snippet-end:[ssm.java2.describe_ops.main] diff --git a/javav2/example_code/ssm/src/main/java/com/example/ssm/GetOpsItem.java b/javav2/example_code/ssm/src/main/java/com/example/ssm/GetOpsItem.java deleted file mode 100644 index 2de3e1c9919..00000000000 --- a/javav2/example_code/ssm/src/main/java/com/example/ssm/GetOpsItem.java +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -// snippet-start:[ssm.Java2.get_ops.complete] -package com.example.ssm; - -// snippet-start:[ssm.Java2.get_ops.main] -// snippet-start:[ssm.Java2.get_ops.import] -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.ssm.SsmClient; -import software.amazon.awssdk.services.ssm.model.GetOpsItemResponse; -import software.amazon.awssdk.services.ssm.model.GetOpsItemRequest; -import software.amazon.awssdk.services.ssm.model.OpsItem; -import software.amazon.awssdk.services.ssm.model.SsmException; -// snippet-end:[ssm.Java2.get_ops.import] - -/** - * 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 GetOpsItem { - public static void main(String[] args) { - final String usage = """ - - Usage: - <opsID> - - Where: - opsID - The Ops item ID value. - """; - - if (args.length != 1) { - System.out.println(usage); - System.exit(1); - } - - String opsID = args[0]; - Region region = Region.US_EAST_1; - SsmClient ssmClient = SsmClient.builder() - .region(region) - .build(); - - getOpsItem(ssmClient, opsID); - ssmClient.close(); - } - - public static void getOpsItem(SsmClient ssmClient, String opsID) { - try { - GetOpsItemRequest opsRequest = GetOpsItemRequest.builder() - .opsItemId(opsID) - .build(); - - // Get SSM Parameters (you can define them in the AWS Management Console). - GetOpsItemResponse opsItem = ssmClient.getOpsItem(opsRequest); - OpsItem item = opsItem.opsItem(); - - System.out.println(item.title()); - System.out.println(item.description()); - System.out.println(item.source()); - - } catch (SsmException e) { - System.err.println(e.getMessage()); - System.exit(1); - } - } -} -// snippet-end:[ssm.Java2.get_ops.main] -// snippet-end:[ssm.Java2.get_ops.complete] diff --git a/javav2/example_code/ssm/src/main/java/com/example/ssm/HelloSSM.java b/javav2/example_code/ssm/src/main/java/com/example/ssm/HelloSSM.java new file mode 100644 index 00000000000..17ead45d6a7 --- /dev/null +++ b/javav2/example_code/ssm/src/main/java/com/example/ssm/HelloSSM.java @@ -0,0 +1,66 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.ssm; + +// snippet-start:[ssm.java2.hello.main] +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); + } +} +// snippet-end:[ssm.java2.hello.main] \ No newline at end of file diff --git a/javav2/example_code/ssm/src/main/java/com/example/ssm/ResolveOpsItem.java b/javav2/example_code/ssm/src/main/java/com/example/ssm/ResolveOpsItem.java deleted file mode 100644 index 9d6ed96e851..00000000000 --- a/javav2/example_code/ssm/src/main/java/com/example/ssm/ResolveOpsItem.java +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.ssm; - -// snippet-start:[ssm.Java2.resolve_ops.main] -// snippet-start:[ssm.Java2.resolve_ops.import] -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.ssm.SsmClient; -import software.amazon.awssdk.services.ssm.model.SsmException; -import software.amazon.awssdk.services.ssm.model.UpdateOpsItemRequest; -import software.amazon.awssdk.services.ssm.model.OpsItemStatus; -// snippet-end:[ssm.Java2.resolve_ops.import] - -/** - * 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 ResolveOpsItem { - public static void main(String[] args) { - final String usage = """ - - Usage: - <opsID> - - Where: - opsID - The Ops item ID value. - """; - - if (args.length != 1) { - System.out.println(usage); - System.exit(1); - } - - String opsID = args[0]; - Region region = Region.US_EAST_1; - SsmClient ssmClient = SsmClient.builder() - .region(region) - .build(); - setOpsItemStatus(ssmClient, opsID); - } - - public static void setOpsItemStatus(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); - } - } -} -// snippet-end:[ssm.Java2.resolve_ops.main] \ No newline at end of file diff --git a/javav2/example_code/ssm/src/test/java/AWSSSMTest.java b/javav2/example_code/ssm/src/test/java/AWSSSMTest.java index 84611dfbd73..a17b739102e 100644 --- a/javav2/example_code/ssm/src/test/java/AWSSSMTest.java +++ b/javav2/example_code/ssm/src/test/java/AWSSSMTest.java @@ -12,6 +12,9 @@ import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueResponse; import software.amazon.awssdk.services.ssm.SsmClient; +import java.text.SimpleDateFormat; +import java.util.Date; + /** * To run these integration tests, you must set the required values * in the config.properties file or AWS Secrets Manager. @@ -22,11 +25,15 @@ public class AWSSSMTest { private static SsmClient ssmClient; private static String paraName = ""; private static String title = ""; + + private static String instance = ""; private static String source = ""; private static String category = ""; private static String severity = ""; private static String opsItemId = ""; + private static String account = ""; + @BeforeAll public static void setUp() { Region region = Region.US_EAST_1; @@ -40,11 +47,15 @@ public static void setUp() { String json = getSecretValues(); SecretValues values = gson.fromJson(json, SecretValues.class); paraName = values.getParaName(); + paraName = values.getParaName(); title = values.getTitle(); source = values.getSource(); category = values.getCategory(); + account = values.getAccount(); + instance = values.getInstanceId(); severity = values.getSeverity(); + // Uncomment this code block if you prefer using a config.properties file to // retrieve AWS values required for these tests. /* @@ -73,57 +84,48 @@ public static void setUp() { @Test @Tag("IntegrationTest") @Order(1) - public void CreateOpsItem() { - opsItemId = CreateOpsItem.createNewOpsItem(ssmClient, title, source, category, severity); - assertFalse(opsItemId.isEmpty()); - System.out.println("Test 1 passed"); + public void HelloSSM() { + assertDoesNotThrow(() -> HelloSSM.listDocuments(ssmClient, account)); + System.out.println("Integration Test 1 passed"); } @Test @Tag("IntegrationTest") @Order(2) - public void GetOpsItem() { - assertDoesNotThrow(() -> GetOpsItem.getOpsItem(ssmClient, opsItemId)); - System.out.println("Test 2 passed"); - } - - @Test - @Tag("IntegrationTest") - @Order(3) - public void DescribeOpsItems() { - assertDoesNotThrow(() -> DescribeOpsItems.describeItems(ssmClient)); - System.out.println("Test 3 passed"); - } - - @Test - @Tag("IntegrationTest") - @Order(4) - public void DescribeParameters() { - assertDoesNotThrow(() -> DescribeParameters.describeParams(ssmClient)); - System.out.println("Test 4 passed"); - } - - @Test - @Tag("IntegrationTest") - @Order(5) public void GetParameter() { assertDoesNotThrow(() -> GetParameter.getParaValue(ssmClient, paraName)); - System.out.println("Test 5 passed"); + System.out.println("Integration Test 2 passed"); } @Test @Tag("IntegrationTest") - @Order(6) - public void ResolveOpsItem() { - assertDoesNotThrow(() -> ResolveOpsItem.setOpsItemStatus(ssmClient, opsItemId)); - System.out.println("Test 6 passed"); + @Order(3) + public void InvokeScenario() throws InterruptedException { + String currentDateTime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()); + String maintenanceWindowName = "windowmain_" + currentDateTime; + String title = "Disk Space Alert" ; + String documentName = "doc_" + currentDateTime; + String maintenanceWindowId = assertDoesNotThrow(() -> com.example.scenario.SSMScenario.createMaintenanceWindow(ssmClient, maintenanceWindowName)); + assertDoesNotThrow(() -> com.example.scenario.SSMScenario.updateSSMMaintenanceWindow(ssmClient, maintenanceWindowId, maintenanceWindowName)); + assertDoesNotThrow(() -> com.example.scenario.SSMScenario.createSSMDoc(ssmClient, documentName)); + String commandId = assertDoesNotThrow(() -> com.example.scenario.SSMScenario.sendSSMCommand(ssmClient, documentName, instance)); + + assertDoesNotThrow(() -> com.example.scenario.SSMScenario.displayCommands(ssmClient, commandId)); + String opsItemId = assertDoesNotThrow(() ->com.example.scenario.SSMScenario.createSSMOpsItem(ssmClient, title, source, category, severity)); + String description = "An update to "+opsItemId ; + assertDoesNotThrow(() ->com.example.scenario.SSMScenario.updateOpsItem(ssmClient, opsItemId, title, description)); + assertDoesNotThrow(() -> com.example.scenario.SSMScenario.describeOpsItems(ssmClient, opsItemId)); + assertDoesNotThrow(() -> com.example.scenario.SSMScenario.resolveOpsItem(ssmClient, opsItemId)); + assertDoesNotThrow(() -> com.example.scenario.SSMScenario.deleteDoc(ssmClient, documentName)); + assertDoesNotThrow(() -> com.example.scenario.SSMScenario.deleteMaintenanceWindow(ssmClient, maintenanceWindowId)); + System.out.println("Test 3 passed"); } - private static String getSecretValues() { - SecretsManagerClient secretClient = SecretsManagerClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + private static String getSecretValues() { + SecretsManagerClient secretClient = SecretsManagerClient.builder() + .region(Region.US_EAST_1) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); String secretName = "test/ssm"; GetSecretValueRequest valueRequest = GetSecretValueRequest.builder() @@ -145,6 +147,10 @@ class SecretValues { private String title; + private String account ; + + private String instance ; + public String getParaName() { return paraName; } @@ -164,5 +170,14 @@ public String getSeverity() { public String getTitle() { return title; } + + public String getAccount() { + return account; + } + public String getInstanceId() { + return instance; + } + + } }