Create Amazon EC2 instance with API

0 votes

How do i create a EC2 instance from JAVA SDK not from web management  console ?

Jul 20, 2018 in AWS by datageek
• 2,440 points
99 views

1 answer to this question.

0 votes

If you are looking for a method then , RunInstances is the method, it should be in the SDK.

Sample code to create EC2 Instances with Amazon AWS SDK for Java :

InputStream credentialsAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("AwsCredentials.properties");
Preconditions.checkNotNull(credentialsAsStream, "File 'AwsCredentials.properties' NOT found in the classpath");
AWSCredentials credentials = new PropertiesCredentials(credentialsAsStream);

AmazonEC2 ec2 = new AmazonEC2Client(credentials);
ec2.setEndpoint("ec2.eu-west-1.amazonaws.com");

// CREATE EC2 INSTANCES
RunInstancesRequest runInstancesRequest = new RunInstancesRequest()
    .withInstanceType("t1.micro")
    .withImageId("ami-62201116")
    .withMinCount(2)
    .withMaxCount(2)
    .withSecurityGroupIds("tomcat")
    .withKeyName("xebia-france")
    .withUserData(Base64.encodeBase64String(myUserData.getBytes()))
;

RunInstancesResult runInstances = ec2.runInstances(runInstancesRequest);

// TAG EC2 INSTANCES
List<Instance> instances = runInstances.getReservation().getInstances();
int idx = 1;
for (Instance instance : instances) {
  CreateTagsRequest createTagsRequest = new CreateTagsRequest();
  createTagsRequest.withResources(instance.getInstanceId()) //
      .withTags(new Tag("Name", "travel-ecommerce-" + idx));
  ec2.createTags(createTagsRequest);

  idx++;
}
I hope this helps.
answered Jul 20, 2018 by Archana
• 4,090 points

Related Questions In AWS

0 votes
0 answers
0 votes
1 answer
0 votes
1 answer
+1 vote
2 answers

Starting with an AWS Instance with API and AUTHPARAMS

The API is usually much easier to ...READ MORE

answered Apr 17, 2018 in AWS by Cloud gunner
• 4,280 points
446 views
0 votes
1 answer

How do I create folder under an Amazon S3 bucket through PHP API?

Of Course, it is possible to create ...READ MORE

answered Apr 24, 2018 in AWS by anonymous
2,554 views
+1 vote
1 answer
0 votes
1 answer

Trying to Determine Amazon EC2 instance creation date/time

You can't find as such attribute called ...READ MORE

answered May 29, 2018 in AWS by Flying geek
• 3,160 points
2,335 views
0 votes
1 answer

nstalling phpMyAdmin in Amazon EC2 instance

I needed to update the /etc/httpd/conf.d/phpMyAdmin.conf to allow remote ...READ MORE

answered Jul 13, 2018 in AWS by Cloud gunner
• 4,280 points
157 views
0 votes
1 answer

Amazon EC2 instance unable to resolve host.

Here is my checklist of things you ...READ MORE

answered Aug 23, 2018 in AWS by Archana
• 4,090 points
512 views
0 votes
1 answer

How to launch an EC2 instance with IAM-Role?

The credentials you are using from your ...READ MORE

answered Sep 3, 2018 in AWS by Archana
• 4,090 points
232 views