I was needing to do many operations with Amazon EC2. Then I implemented an utility class for this operations. Maybe it can be util to someone that arrive here. I implemented using AWS SDK for java version 2. The operations are:
- Create machine;
- Start machine;
- Stop machine;
- Reboot machine;
- Delete machine (Terminate);
- Describe machine;
- Get Public IP from machine;
AmazonEC2 class:
import govbr.cloud.management.api.CloudManagementException;
import govbr.cloud.management.api.CloudServerMachine;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.exception.SdkServiceException;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ec2.Ec2Client;
import software.amazon.awssdk.services.ec2.model.DescribeInstancesRequest;
import software.amazon.awssdk.services.ec2.model.DescribeInstancesResponse;
import software.amazon.awssdk.services.ec2.model.Ec2Exception;
import software.amazon.awssdk.services.ec2.model.Instance;
import software.amazon.awssdk.services.ec2.model.InstanceNetworkInterface;
import software.amazon.awssdk.services.ec2.model.InstanceType;
import software.amazon.awssdk.services.ec2.model.RebootInstancesRequest;
import software.amazon.awssdk.services.ec2.model.Reservation;
import software.amazon.awssdk.services.ec2.model.RunInstancesRequest;
import software.amazon.awssdk.services.ec2.model.RunInstancesResponse;
import software.amazon.awssdk.services.ec2.model.StartInstancesRequest;
import software.amazon.awssdk.services.ec2.model.StopInstancesRequest;
import software.amazon.awssdk.services.ec2.model.TerminateInstancesRequest;
public class AmazonEC2 {
private final static String EC2_MESSAGE_ERROR = "A error occurred on the Ec2.";
private final static String CLIENT_MESSAGE_ERROR = "A error occurred in client side.";
private final static String SERVER_MESSAGE_ERROR = "A error occurred in Amazon server.";
private final static String UNEXPECTED_MESSAGE_ERROR = "Unexpected error occurred.";
private Ec2Client buildDefaultEc2() {
AwsCredentialsProvider credentials = AmazonCredentials.loadCredentialsFromFile();
Ec2Client ec2 = Ec2Client.builder()
.region(Region.SA_EAST_1)
.credentialsProvider(credentials)
.build();
return ec2;
}
public String createMachine(String name, String amazonMachineId)
throws CloudManagementException {
try {
if(amazonMachineId == null) {
amazonMachineId = "ami-07b14488da8ea02a0";
}
Ec2Client ec2 = buildDefaultEc2();
RunInstancesRequest request = RunInstancesRequest.builder()
.imageId(amazonMachineId)
.instanceType(InstanceType.T1_MICRO)
.maxCount(1)
.minCount(1)
.build();
RunInstancesResponse response = ec2.runInstances(request);
Instance instance = null;
if (response.reservation().instances().size() > 0) {
instance = response.reservation().instances().get(0);
}
if(instance != null) {
System.out.println("Machine created! Machine identifier: "
+ instance.instanceId());
return instance.instanceId();
}
return null;
} catch (Ec2Exception e) {
throw new CloudManagementException(EC2_MESSAGE_ERROR, e);
} catch (SdkClientException e) {
throw new CloudManagementException(CLIENT_MESSAGE_ERROR, e);
} catch (SdkServiceException e) {
throw new CloudManagementException(SERVER_MESSAGE_ERROR, e);
} catch (Exception e) {
throw new CloudManagementException(UNEXPECTED_MESSAGE_ERROR, e);
}
}
public void startMachine(String instanceId) {
try {
Ec2Client ec2 = buildDefaultEc2();
StartInstancesRequest request = StartInstancesRequest.builder()
.instanceIds(instanceId).build();
ec2.startInstances(request);
} catch (Ec2Exception e) {
throw new CloudManagementException(EC2_MESSAGE_ERROR, e);
} catch (SdkClientException e) {
throw new CloudManagementException(CLIENT_MESSAGE_ERROR, e);
} catch (SdkServiceException e) {
throw new CloudManagementException(SERVER_MESSAGE_ERROR, e);
} catch (Exception e) {
throw new CloudManagementException(UNEXPECTED_MESSAGE_ERROR, e);
}
}
public void stopMachine(String instanceId) {
try {
Ec2Client ec2 = buildDefaultEc2();
StopInstancesRequest request = StopInstancesRequest.builder()
.instanceIds(instanceId).build();
ec2.stopInstances(request);
} catch (Ec2Exception e) {
throw new CloudManagementException(EC2_MESSAGE_ERROR, e);
} catch (SdkClientException e) {
throw new CloudManagementException(CLIENT_MESSAGE_ERROR, e);
} catch (SdkServiceException e) {
throw new CloudManagementException(SERVER_MESSAGE_ERROR, e);
} catch (Exception e) {
throw new CloudManagementException(UNEXPECTED_MESSAGE_ERROR, e);
}
}
public void rebootMachine(String instanceId) {
try {
Ec2Client ec2 = buildDefaultEc2();
RebootInstancesRequest request = RebootInstancesRequest.builder()
.instanceIds(instanceId).build();
ec2.rebootInstances(request);
} catch (Ec2Exception e) {
throw new CloudManagementException(EC2_MESSAGE_ERROR, e);
} catch (SdkClientException e) {
throw new CloudManagementException(CLIENT_MESSAGE_ERROR, e);
} catch (SdkServiceException e) {
throw new CloudManagementException(SERVER_MESSAGE_ERROR, e);
} catch (Exception e) {
throw new CloudManagementException(UNEXPECTED_MESSAGE_ERROR, e);
}
}
public void destroyMachine(String instanceId) {
try {
Ec2Client ec2 = buildDefaultEc2();
TerminateInstancesRequest request = TerminateInstancesRequest.builder()
.instanceIds(instanceId).build();
ec2.terminateInstances(request);
} catch (Ec2Exception e) {
throw new CloudManagementException(EC2_MESSAGE_ERROR, e);
} catch (SdkClientException e) {
throw new CloudManagementException(CLIENT_MESSAGE_ERROR, e);
} catch (SdkServiceException e) {
throw new CloudManagementException(SERVER_MESSAGE_ERROR, e);
} catch (Exception e) {
throw new CloudManagementException(UNEXPECTED_MESSAGE_ERROR, e);
}
}
public String getPublicIpAddress(String instanceId) throws CloudManagementException {
try {
Ec2Client ec2 = buildDefaultEc2();
boolean done = false;
DescribeInstancesRequest request = DescribeInstancesRequest.builder().build();
while(!done) {
DescribeInstancesResponse response = ec2.describeInstances(request);
for(Reservation reservation : response.reservations()) {
for(Instance instance : reservation.instances()) {
if(instance.instanceId().equals(instanceId)) {
if(instance.networkInterfaces().size() > 0) {
InstanceNetworkInterface networkInterface =
instance.networkInterfaces().get(0);
String publicIp = networkInterface
.association().publicIp();
System.out.println("Machine found. Machine with Id "
+ instanceId
+ " has the follow public IP: "
+ publicIp);
return publicIp;
}
}
}
}
if(response.nextToken() == null) {
done = true;
}
}
return null;
} catch (Ec2Exception e) {
throw new CloudManagementException(EC2_MESSAGE_ERROR, e);
} catch (SdkClientException e) {
throw new CloudManagementException(CLIENT_MESSAGE_ERROR, e);
} catch (SdkServiceException e) {
throw new CloudManagementException(SERVER_MESSAGE_ERROR, e);
} catch (Exception e) {
throw new CloudManagementException(UNEXPECTED_MESSAGE_ERROR, e);
}
}
public String describeMachine(String instanceId) {
try {
Ec2Client ec2 = buildDefaultEc2();
boolean done = false;
DescribeInstancesRequest request = DescribeInstancesRequest.builder().build();
while(!done) {
DescribeInstancesResponse response = ec2.describeInstances(request);
for(Reservation reservation : response.reservations()) {
for(Instance instance : reservation.instances()) {
if(instance.instanceId().equals(instanceId)) {
return "Found reservation with id " +
instance.instanceId() +
", AMI " + instance.imageId() +
", type " + instance.instanceType() +
", state " + instance.state().name() +
"and monitoring state" +
instance.monitoring().state();
}
}
}
if(response.nextToken() == null) {
done = true;
}
}
return null;
} catch (Ec2Exception e) {
throw new CloudManagementException(EC2_MESSAGE_ERROR, e);
} catch (SdkClientException e) {
throw new CloudManagementException(CLIENT_MESSAGE_ERROR, e);
} catch (SdkServiceException e) {
throw new CloudManagementException(SERVER_MESSAGE_ERROR, e);
} catch (Exception e) {
throw new CloudManagementException(UNEXPECTED_MESSAGE_ERROR, e);
}
}
}
AmazonCredentials class:
import java.io.InputStream;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.profiles.ProfileFile;
import software.amazon.awssdk.profiles.ProfileFile.Type;
public class AmazonCredentials {
public static AwsCredentialsProvider loadCredentialsFromFile() {
InputStream profileInput = ClassLoader.getSystemResourceAsStream("credentials.profiles");
ProfileFile profileFile = ProfileFile.builder()
.content(profileInput)
.type(Type.CREDENTIALS)
.build();
AwsCredentialsProvider profileProvider = ProfileCredentialsProvider.builder()
.profileFile(profileFile)
.build();
return profileProvider;
}
}
CloudManagementException class:
public class CloudManagementException extends RuntimeException {
private static final long serialVersionUID = 1L;
public CloudManagementException(String message) {
super(message);
}
public CloudManagementException(String message, Throwable cause) {
super(message, cause);
}
}
credentials.profiles:
[default]
aws_access_key_id={your access key id here}
aws_secret_access_key={your secret access key here}
I hope help o/