February 1, 2012

Terminate AWS instances with Java SDK

    BasicAWSCredentials awsCredentials = new BasicAWSCredentials(
        AWSAccessKeyId, SecretAccessKey);

    AmazonEC2Client ec2Client = new AmazonEC2Client(awsCredentials);
    ec2Client.setEndpoint("ec2.us-east-1.amazonaws.com"); // Zone

    List<String> instancesToTerminate = new ArrayList<String>();
    
    DescribeInstancesResult result = ec2Client.describeInstances();
    List<Reservation> reservations = result.getReservations();
    for (Reservation reservation : reservations) {
      List<Instance> instances = reservation.getInstances();
      for (Instance instance : instances) {
        System.out.println("Terminating: " + instance.getInstanceId());
        instancesToTerminate.add(instance.getInstanceId());
      }
    }

    TerminateInstancesRequest term = new TerminateInstancesRequest();
    term.setInstanceIds(instancesToTerminate);
    ec2Client.terminateInstances(term);

No comments:

Post a Comment