【问题标题】:How to start and stop an Amazon EC2 instance programmatically in java如何在 Java 中以编程方式启动和停止 Amazon EC2 实例
【发布时间】:2023-03-29 04:25:01
【问题描述】:

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

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

【问题讨论】:

标签: java amazon-ec2


【解决方案1】:

如果您已经使用过AWS API,则只需调用AmazonEC2Client 对象即可。使用以下方法

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

【讨论】:

    【解决方案2】:

    我最近在Bamboo AWS Plugin 中实现了这个功能;它是开源的,code is available on 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 对象,该接口定义了所有相关方法(以及许多其他方法),具体而言:

    【讨论】:

      猜你喜欢
      • 2011-11-17
      • 1970-01-01
      • 1970-01-01
      • 2022-11-18
      • 2019-08-03
      • 2022-12-13
      • 2015-11-15
      • 2018-08-15
      • 1970-01-01
      相关资源
      最近更新 更多