CONTACT
お問い合わせ

AWS SDKを利用したJavaプログラムでのEC2インスタンス起動停止処理

Javaプログラム(コマンドライン)から、EC2の起動および停止を行うサンプルプログラムは以下の通り。

package jp.a_frontier.aws;

import java.util.ArrayList;
import java.util.List;

import com.amazonaws.AmazonClientException;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.AmazonEC2Client;
import com.amazonaws.services.ec2.model.DescribeInstancesRequest;
import com.amazonaws.services.ec2.model.DescribeInstancesResult;
import com.amazonaws.services.ec2.model.Filter;
import com.amazonaws.services.ec2.model.Instance;
import com.amazonaws.services.ec2.model.Reservation;
import com.amazonaws.services.ec2.model.StartInstancesRequest;
import com.amazonaws.services.ec2.model.StartInstancesResult;
import com.amazonaws.services.ec2.model.StopInstancesRequest;
import com.amazonaws.services.ec2.model.StopInstancesResult;
import com.amazonaws.services.ec2.model.Tag;

public class AwsSdkSample_EC2_GetInformation {

	
	public static AmazonEC2 ec2;
			
	public static void main(String[] args) {
		
        System.out.println("[Start]");

        AWSCredentials credentials = null;
        try {
            credentials = new ProfileCredentialsProvider().getCredentials();
        } catch (Exception e) {
            throw new AmazonClientException(
                    "Cannot load the credentials from the credential profiles file. " +
                    "Please make sure that your credentials file is at the correct " +
                    "location (~/.aws/credentials), and is in valid format.",
                    e);
        }

        System.out.println("[Done]AWSCredentials");

        ec2 = new AmazonEC2Client(credentials);
        Region apNortheast1 = Region.getRegion(Regions.AP_NORTHEAST_1);
        ec2.setRegion(apNortheast1);
        
        //showParam();
        stopInstanceALL();
        //startInstanceALL();
        //showParam();

        System.out.println("[Fin]");

	}
	
	public static void showParam(){
		System.out.println("[Start]showParam");
		
		DescribeInstancesResult instanceResult = ec2.describeInstances( new DescribeInstancesRequest() );
		
		for(Reservation reservation:instanceResult.getReservations()){
			for(Instance instance:reservation.getInstances()){
				
				System.out.println("InstanceId=["+instance.getInstanceId()+"] : "+instance.getState().getName()+":"+instance.getPrivateIpAddress()+"\t : "+instance.getPrivateDnsName()+":"+instance.getInstanceType()+":"+instance.getInstanceLifecycle()+"\t"+instance.getTags().get(0).getValue());
			}
		}
		
		System.out.println("[Done]showParam");
		
	}
	
	public static void startInstanceALL(){
		
		System.out.println("[Start]startInstanceALL");
		
        List<String> value1 = new ArrayList<String>();
        //value1.add("running");
        value1.add("stopped");
        Filter filter1 = new Filter("instance-state-name",value1);
        
        DescribeInstancesResult instanceResult = ec2.describeInstances( new DescribeInstancesRequest().withFilters(filter1) );
        
        for(Reservation reservation:instanceResult.getReservations()){
        	for(Instance instance:reservation.getInstances()){
        		for(Tag tag:instance.getTags()){
        			String tagName2 = tag.getKey().toString();
        			System.out.println("tagName="+tagName2+":"+tag.getValue()+":"+instance.getInstanceId());
        			
        			List<String> instanceIds = new ArrayList<String>();
        		    instanceIds.add(instance.getInstanceId());
        		    
        		    //インスタンスの起動
        		    StartInstancesRequest startInstancesRequest = new StartInstancesRequest(instanceIds);
        		    StartInstancesResult startInstancesResult = ec2.startInstances(startInstancesRequest);

        		}
        	}
        }
		System.out.println("[Done]startInstanceALL");

	}
	
	public static void stopInstanceALL(){
		
		System.out.println("[Start]stopInstanceALL");

        List<String> value1 = new ArrayList<String>();
        value1.add("running");
        //value1.add("stopped");
        Filter filter1 = new Filter("instance-state-name",value1);
        
        DescribeInstancesResult instanceResult = ec2.describeInstances( new DescribeInstancesRequest().withFilters(filter1) );
        
        for(Reservation reservation:instanceResult.getReservations()){
        	for(Instance instance:reservation.getInstances()){
        		for(Tag tag:instance.getTags()){
        			String tagName2 = tag.getKey().toString();
        			System.out.println("tagName="+tagName2+":"+tag.getValue()+":"+instance.getInstanceId());
        			
        			List<String> instanceIds = new ArrayList<String>();
        		    instanceIds.add(instance.getInstanceId());
        		    
        			//インスタンスの停止
        		    StopInstancesRequest stopInstancesRequest = new StopInstancesRequest(instanceIds);
        		    StopInstancesResult stopInstancesResult = ec2.stopInstances(stopInstancesRequest);
        		}
        	}
        }
        
		System.out.println("[Done]stopInstanceALL");

	}

}