Untitled
unknown
plain_text
a year ago
2.9 kB
8
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.ListCommandsRequest;
import software.amazon.awssdk.services.ssm.model.ListCommandsResponse;
import software.amazon.awssdk.services.ssm.model.Command;
import software.amazon.awssdk.services.ssm.model.CommandStatus;
import java.util.Collections;
import java.util.Arrays;
import java.util.Map;
import java.util.List;
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(Collections.singletonMap("commands", Arrays.asList("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