Untitled

mail@pastecode.io avatar
unknown
plain_text
24 days ago
4.2 kB
3
Indexable
Never
import software.amazon.awssdk.auth.credentials.AwsSessionCredentials;
import software.amazon.awssdk.auth.credentials.StsAssumeRoleCredentialsProvider;
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 software.amazon.awssdk.services.sts.StsClient;
import software.amazon.awssdk.services.sts.model.AssumeRoleRequest;
import software.amazon.awssdk.services.sts.model.AssumeRoleResponse;

import java.util.Arrays;
import java.util.Collections;

public class SSMExample {
    public static void main(String[] args) {
        // Specify the AWS region
        Region region = Region.US_EAST_1;

        // Define the role ARN
        String roleArn = "arn:aws:iam::123456789012:role/MySSMRole";

        // Create an STS client
        StsClient stsClient = StsClient.builder()
                .region(region)
                .build();

        // Assume the role
        AssumeRoleRequest assumeRoleRequest = AssumeRoleRequest.builder()
                .roleArn(roleArn)
                .roleSessionName("SSMCommandSession")
                .build();

        AssumeRoleResponse assumeRoleResponse = stsClient.assumeRole(assumeRoleRequest);
        AwsSessionCredentials sessionCredentials = AwsSessionCredentials.create(
                assumeRoleResponse.credentials().accessKeyId(),
                assumeRoleResponse.credentials().secretAccessKey(),
                assumeRoleResponse.credentials().sessionToken()
        );

        // Create an SSM client using the assumed role credentials
        SsmClient ssmClient = SsmClient.builder()
                .region(region)
                .credentialsProvider(() -> sessionCredentials)
                .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("sudo echo Hello World")))
                .build();

        // Send the command
        try {
            SendCommandResponse sendCommandResponse = ssmClient.sendCommand(sendCommandRequest);
            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.");
        } catch (Exception e) {
            System.err.println("Failed to send command: " + e.getMessage());
        }
    }
}
Leave a Comment