如何在 Java 中以编程方式启动和停止 Amazon EC2 实例 [英] How to start and stop an Amazon EC2 instance programmatically in java

查看:24
本文介绍了如何在 Java 中以编程方式启动和停止 Amazon EC2 实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 java 中的 aws-sdk 以编程方式启动和停止亚马逊 EC2 实例?

How do i start and stop an amazon EC2 instance programmatically using aws-sdk in java?

非常感谢任何帮助,因为我花了一天时间试图解决这个问题.

Any helps are greatly appreciated as I have spent a day while trying to sort this out.

推荐答案

我最近在 Bamboo AWS 中实现了这个功能插件;它是开源的,代码在 Bitbucket 上可用,你可以找到一个完整的示例如何启动/停止/重启EC2Task.java 中的一个实例(实际上应该是一个单独的类,唉......).

I've recently implemented this functionality within the Bamboo AWS Plugin; it's Open Source and the code is available on Bitbucket, you can find a complete example how to start/stop/reboot an instance within EC2Task.java (should be a separate class actually, alas ...).

幸运的是这一点都不复杂,例如,一个实例可以这样启动:

Fortunately this is not complicated at all, for example, an instance can be started like so:

private String startInstance(final String instanceId, AmazonEC2 ec2, final BuildLogger buildLogger)
        throws AmazonServiceException, AmazonClientException, InterruptedException
{
    StartInstancesRequest startRequest = new StartInstancesRequest().withInstanceIds(instanceId);
    StartInstancesResult startResult = ec2.startInstances(startRequest);
    List<InstanceStateChange> stateChangeList = startResult.getStartingInstances();
    buildLogger.addBuildLogEntry("Starting instance '" + instanceId + "':");

    // Wait for the instance to be started
    return waitForTransitionCompletion(stateChangeList, "running", ec2, instanceId, buildLogger); }

BuildLogger 是 Bamboo 特有的,并且 waitForTransitionCompletion() 是一个实现特定的帮助程序,用于报告流程/结果.AmazonEC2 ec2 参数将引用传递给 AmazonEC2Client 对象通过 AmazonEC2 接口,它定义了所有相关方法(以及许多其他方法),特别是:

BuildLogger is Bamboo specific and waitForTransitionCompletion() is an implementation specific helper to report back on the process/result. The AmazonEC2 ec2 parameter passes the reference to an AmazonEC2Client object by means of the AmazonEC2 interface, which defines all relevant methods (amongst many others), specifically:

这篇关于如何在 Java 中以编程方式启动和停止 Amazon EC2 实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆