Menu
AWS SDK for Java
Developer Guide

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.

To launch an Amazon EC2 instance

  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.

    Copy
    RunInstancesRequest runInstancesRequest = new RunInstancesRequest(); runInstancesRequest.withImageId("ami-4b814f22") .withInstanceType("m1.small") .withMinCount(1) .withMaxCount(1) .withKeyName("my-key-pair") .withSecurityGroups("my-security-group");
    withImageId

    The ID of the AMI. For a list of public AMIs provided by Amazon, see Amazon Machine Images.

    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

    One or more security groups. For more information, see Create an Amazon EC2 Security Group.

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

    Copy
    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.