如何用java编程启动和停止AmazonEC2实例



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

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

我最近在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); }

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

  • 开始实例()
  • 停止实例()
  • 重新启动实例()

如果您已经使用了AWS API,那么它只是对AmazonEC2Client对象的简单调用。使用以下方法

  • 启动实例
  • 停止实例

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

最新更新