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 EC2CreateInstance
{
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)
.build();
// Launch an Amazon EC2 Instance
RunInstancesRequest runInstancesRequest = new RunInstancesRequest().withImageId("ami-0080e4c5bc078760e")
.withInstanceType("t2.micro") // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html
.withMinCount(1)
.withMaxCount(1)
.withKeyName("priyajdm")
.withNetworkInterfaces(new InstanceNetworkInterfaceSpecification()
.withAssociatePublicIpAddress(true)
.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", "Edurekademo"));
ec2Client.createTags(createTagsRequest);
// Starting the Instance
StartInstancesRequest startInstancesRequest = new StartInstancesRequest().withInstanceIds(instanceId);
ec2Client.startInstances(startInstancesRequest);
}
}
This is the code you can use to Create an EC2 Instance using AWS SDK.