AWS Java SDK - запуск команды с помощью SSM на экземплярах EC2

Я не смог найти никаких примеров этого в Интернете, равно как и не смог найти документацию, объясняющую, как это сделать. В основном у меня есть список экземпляров Windows EC2, и мне нужно запустить команду quser в каждом из них, чтобы проверить, сколько пользователей вошли в систему.

Это можно сделать с помощью службы AWS Systems Manager и выполнения команды AWS-RunPowerShellScript. Я нашел только примеры с использованием AWS CLI, примерно так:

aws ssm send-command --instance-ids "instance ID" --document-name "AWS-RunPowerShellScript" --comment "Get Users" --parameters commands=quser --output text

Но как это сделать с помощью AWS Java SDK 1.11.x?


person Alexandre Krabbe    schedule 30.10.2019    source источник


Ответы (1)


@Alexandre Krabbe, прошло больше года, прежде чем вы задали этот вопрос. Так что не уверен, что ответ вам поможет. Но недавно я пытался сделать то же самое, и это привело меня к этому вопросу без ответа. В итоге я решил проблему и подумал, что мой ответ может помочь другим людям, столкнувшимся с той же проблемой. Вот фрагмент кода для того же:

public void runCommand() throws InterruptedException {
    //Command to be run
    String ssmCommand = "ls -l";
    Map<String, List<String>> params = new HashMap<String, List<String>>(){{
        put("commands", new ArrayList<String>(){{ add(ssmCommand); }});
    }};
    int timeoutInSecs = 5;
    //You can add multiple command ids separated by commas
    Target target = new Target().withKey("InstanceIds").withValues("instance-id");
    //Create ssm client.
    //The builder could be chosen as per your preferred way of authentication
    //use withRegion for specifying your region
    AWSSimpleSystemsManagement ssm = AWSSimpleSystemsManagementClientBuilder.standard().build();
    //Build a send command request
    SendCommandRequest commandRequest = new SendCommandRequest()
            .withTargets(target)
            .withDocumentName("AWS-RunShellScript")
            .withParameters(params);
    //The result has commandId which is used to track the execution further
    SendCommandResult commandResult = ssm.sendCommand(commandRequest);
    String commandId = commandResult.getCommand().getCommandId();
    //Loop until the invocation ends
    String status;
    do {
        ListCommandInvocationsRequest request = new ListCommandInvocationsRequest()
                .withCommandId(commandId)
                .withDetails(true);
        //You get one invocation per ec2 instance that you added to target
        //For just a single instance use get(0) else loop over the instanced
        CommandInvocation invocation = ssm.listCommandInvocations(request).getCommandInvocations().get(0);
        status = invocation.getStatus();
        if(status.equals("Success")) {
            //command output holds the output of running the command
            //eg. list of directories in case of ls
            String commandOutput = invocation.getCommandPlugins().get(0).getOutput();
            //Process the output
        }
        //Wait for a few seconds before you check the invocation status again
        try {
            TimeUnit.SECONDS.sleep(timeoutInSecs);
        } catch (InterruptedException e) {
            //Handle not being able to sleep
        }
    } while(status.equals("Pending") || status.equals("InProgress"));
    if(!status.equals("Success")) {
        //Command ended up in a failure
    }
}
person Mugdha    schedule 01.02.2021