如何重启自动伸缩组中的所有实例?

问题描述 投票:0回答:1

如何重启具有自动伸缩组的所有实例?我不太清楚如何以一种好的方式做到这一点。

目标是在出现问题时重新启动应用程序。

amazon-web-services autoscaling
1个回答
0
投票

您可以使用 AWS 开发工具包来执行此任务。例如,假设您正在使用 Java V2 API。在这种情况下,您将使用此服务客户端:

https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/autoscaling/AutoScalingClient.html

还有这个:

https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/ec2/Ec2Client.html

要重启所有实例,可以获取组内所有实例:

public static String getAutoScaling( AutoScalingClient autoScalingClient, String groupName) {
        try{
            String instanceId = "";
            DescribeAutoScalingGroupsRequest scalingGroupsRequest = DescribeAutoScalingGroupsRequest.builder()
                .autoScalingGroupNames(groupName)
                .build();

            DescribeAutoScalingGroupsResponse response = autoScalingClient.describeAutoScalingGroups(scalingGroupsRequest);
            List<AutoScalingGroup> groups = response.autoScalingGroups();
            for (AutoScalingGroup group: groups) {
                System.out.println("The group name is " + group.autoScalingGroupName());
                System.out.println("The group ARN is " + group.autoScalingGroupARN());

                List<Instance> instances = group.instances();
                for (Instance instance : instances) {
                    instanceId = instance.instanceId();
                    // NOW CALL A METHOD that uses EC2 API to reboot instance using instance ID value

                }
            }
            return instanceId;
        } catch (AutoScalingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return "";
    }

要使用实例 ID 值重新启动实例,您可以使用以下 Java 代码:

public static void rebootEC2Instance(Ec2Client ec2, String instanceId) {
        try {
            RebootInstancesRequest request = RebootInstancesRequest.builder()
                .instanceIds(instanceId)
                .build();

            ec2.rebootInstances(request);
            System.out.printf("Successfully rebooted instance %s", instanceId);

        } catch (Ec2Exception e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.