×
☰ See All Chapters

AWS Java SDK program to Start and Stop an EC2 instance

StartAndStopInstance.java

package com.java4coding;

import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.PropertiesFileCredentialsProvider;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.AmazonEC2Client;
import com.amazonaws.services.ec2.model.StartInstancesRequest;
import com.amazonaws.services.ec2.model.StopInstancesRequest;

public class StartAndStopInstance {
   
public static void main(String[] args) {
       
AWSCredentialsProvider provider = new PropertiesFileCredentialsProvider(
               
"F:\\My_Programs\\AWS\\AWSEC2Example\\src\\main\\resources\\awscredentials.properties");

       
AmazonEC2 amazonEC2Client = AmazonEC2Client.builder()
               .withRegion(
Regions.US_WEST_2)
               .withCredentials(
provider)
               .build();

       
StartInstancesRequest startInstancesRequest = new StartInstancesRequest();
       
startInstancesRequest.withInstanceIds("instanceId");
       
amazonEC2Client.startInstances(startInstancesRequest);

       
StopInstancesRequest stopInstancesRequest = new StopInstancesRequest();
       
stopInstancesRequest.withInstanceIds("instanceId");
       
amazonEC2Client.stopInstances(stopInstancesRequest);
   }

}

 

 


All Chapters
Author