package com.ec2application.ec2application;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.AmazonEC2ClientBuilder;
import com.amazonaws.services.ec2.model.CreateTagsRequest;
import com.amazonaws.services.ec2.model.Instance;
import com.amazonaws.services.ec2.model.InstanceNetworkInterfaceSpecification;
import com.amazonaws.services.ec2.model.RunInstancesRequest;
import com.amazonaws.services.ec2.model.RunInstancesResult;
import com.amazonaws.services.ec2.model.StartInstancesRequest;
import com.amazonaws.services.ec2.model.Tag;
public class CreateEc2instance
{
private static final AWSCredentials AWS_CREDENTIALS;
static {
// Your accesskey and secretkey
AWS_CREDENTIALS = new BasicAWSCredentials(
"Your-ID",
"Your secret-key"
);
}
public static void main(String[] args) {
// Set up the amazon ec2 client
AmazonEC2 ec2Client = AmazonEC2ClientBuilder.standard()
.withCredentials(new AWSStaticCredentialsProvider(AWS_CREDENTIALS))
.withRegion(Regions.US_EAST_1) //Specify the region the instance should be launched in
.build();
// Launch an Amazon EC2 Instance
RunInstancesRequest runInstancesRequest = new RunInstancesRequest().withImageId("ami-0080e4c5bc078760e")
.withInstanceType("t2.micro") //Enter the instance type, t2.micro is under free tier
.withMinCount(1)
.withMaxCount(1)
.withKeyName("privatekey1")
.withNetworkInterfaces(new InstanceNetworkInterfaceSpecification()
.withAssociatePublicIpAddress(true)//true if you want to enable public ip
.withDeviceIndex(0)
.withSubnetId("subnet-id")
.withGroups("sg-id"));
RunInstancesResult runInstancesResult = ec2Client.runInstances(runInstancesRequest);
Instance instance = runInstancesResult.getReservation().getInstances().get(0);
String instanceId = instance.getInstanceId();
System.out.println("EC2 Instance Id: " + instanceId);
// Setting up the tags for the instance
CreateTagsRequest createTagsRequest = new CreateTagsRequest()
.withResources(instance.getInstanceId())
.withTags(new Tag("Name", "Server"));
ec2Client.createTags(createTagsRequest);
// Starting the Instance
StartInstancesRequest startInstancesRequest = new StartInstancesRequest().withInstanceIds(instanceId);
ec2Client.startInstances(startInstancesRequest);
}
}