Run an Amazon EC2 Instance - AWS SDK for Java 1.x

We announced the upcoming end-of-support for AWS SDK for Java (v1). We recommend that you migrate to AWS SDK for Java v2. For dates, additional details, and information on how to migrate, please refer to the linked announcement.

Run an Amazon EC2 Instance

Use the following procedure to launch one or more identically configured EC2 instances from the same Amazon Machine Image (AMI). After you create your EC2 instances, you can check their status. After your EC2 instances are running, you can connect to them.

  1. Create and initialize a RunInstancesRequest instance. Make sure that the AMI, key pair, and security group that you specify exist in the region that you specified when you created the client object.

    RunInstancesRequest runInstancesRequest = new RunInstancesRequest(); runInstancesRequest.withImageId("ami-a9d09ed1") .withInstanceType(InstanceType.T1Micro) .withMinCount(1) .withMaxCount(1) .withKeyName("my-key-pair") .withSecurityGroups("my-security-group");
    withImageId
    withInstanceType
    • An instance type that is compatible with the specified AMI. For more information, see Instance Types in the Amazon EC2 User Guide for Linux Instances.

    withMinCount
    • The minimum number of EC2 instances to launch. If this is more instances than Amazon EC2 can launch in the target Availability Zone, Amazon EC2 launches no instances.

    withMaxCount
    • The maximum number of EC2 instances to launch. If this is more instances than Amazon EC2 can launch in the target Availability Zone, Amazon EC2 launches the largest possible number of instances above MinCount. You can launch between 1 and the maximum number of instances you’re allowed for the instance type. For more information, see How many instances can I run in Amazon EC2 in the Amazon EC2 General FAQ.

    withKeyName
    • The name of the EC2 key pair. If you launch an instance without specifying a key pair, you can’t connect to it. For more information, see Create a Key Pair.

    withSecurityGroups
  2. Launch the instances by passing the request object to the runInstances method. The method returns a RunInstancesResult object, as follows:

    RunInstancesResult result = amazonEC2Client.runInstances( runInstancesRequest);

After your instance is running, you can connect to it using your key pair. For more information, see Connect to Your Linux Instance. in the Amazon EC2 User Guide for Linux Instances.