如何在java中以编程方式启动和停止Amazon EC2实例

diy*_*iya 14 java amazon-ec2

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

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

Ste*_*pel 9

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

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

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); }
Run Code Online (Sandbox Code Playgroud)

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


Nis*_*ant 6

如果您已经使用过AWS API,那么可以在AmazonEC2Client对象上进行简单调用.使用以下方法

此外,您可能知道启动/停止机制适用于具有EBS支持的根设备的映像.