Untitled

 avatar
unknown
plain_text
10 months ago
2.8 kB
4
Indexable
import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ssm.SsmClient;
import software.amazon.awssdk.services.ssm.model.SendCommandRequest;
import software.amazon.awssdk.services.ssm.model.SendCommandResponse;
import software.amazon.awssdk.services.ssm.model.Command;
import software.amazon.awssdk.services.ssm.model.ListCommandsRequest;
import software.amazon.awssdk.services.ssm.model.ListCommandsResponse;
import software.amazon.awssdk.services.ssm.model.CommandStatus;

public class SSMExample {
    public static void main(String[] args) {
        // Specify the AWS region
        Region region = Region.US_EAST_1;
        
        // Create an SSM client
        SsmClient ssmClient = SsmClient.builder()
                .region(region)
                .credentialsProvider(ProfileCredentialsProvider.create())
                .build();

        // Create a SendCommandRequest
        SendCommandRequest sendCommandRequest = SendCommandRequest.builder()
                .instanceIds("instance-id")  // Replace with your instance ID
                .documentName("AWS-RunShellScript")
                .parameters(Map.of("commands", List.of("echo Hello World")))
                .build();

        // Send the command
        SendCommandResponse sendCommandResponse = ssmClient.sendCommand(sendCommandRequest);

        // Get the command ID
        String commandId = sendCommandResponse.command().commandId();
        System.out.println("Command ID: " + commandId);

        // Poll the command status
        boolean isCommandCompleted = false;
        while (!isCommandCompleted) {
            try {
                // Wait for 5 seconds before polling again
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            // Create a ListCommandsRequest to get the command status
            ListCommandsRequest listCommandsRequest = ListCommandsRequest.builder()
                    .commandId(commandId)
                    .build();

            // Get the command status
            ListCommandsResponse listCommandsResponse = ssmClient.listCommands(listCommandsRequest);
            Command command = listCommandsResponse.commands().get(0);
            CommandStatus status = command.status();

            System.out.println("Current status: " + status);

            // Check if the command has completed
            if (status == CommandStatus.SUCCESS || status == CommandStatus.FAILED || status == CommandStatus.CANCELLED) {
                isCommandCompleted = true;
            }
        }

        System.out.println("Command execution completed.");
    }
}
Editor is loading...
Leave a Comment