Search in sources :

Example 1 with RunInstancesResponse

use of software.amazon.awssdk.services.ec2.model.RunInstancesResponse in project aws-doc-sdk-examples by awsdocs.

the class CreateInstance method createEC2Instance.

// snippet-start:[ec2.java2.create_instance.main]
public static String createEC2Instance(Ec2Client ec2, String name, String amiId) {
    RunInstancesRequest runRequest = RunInstancesRequest.builder().imageId(amiId).instanceType(InstanceType.T1_MICRO).maxCount(1).minCount(1).build();
    RunInstancesResponse response = ec2.runInstances(runRequest);
    String instanceId = response.instances().get(0).instanceId();
    Tag tag = Tag.builder().key("Name").value(name).build();
    CreateTagsRequest tagRequest = CreateTagsRequest.builder().resources(instanceId).tags(tag).build();
    try {
        ec2.createTags(tagRequest);
        System.out.printf("Successfully started EC2 Instance %s based on AMI %s", instanceId, amiId);
        return instanceId;
    } catch (Ec2Exception e) {
        System.err.println(e.awsErrorDetails().errorMessage());
        System.exit(1);
    }
    return "";
}
Also used : RunInstancesResponse(software.amazon.awssdk.services.ec2.model.RunInstancesResponse) CreateTagsRequest(software.amazon.awssdk.services.ec2.model.CreateTagsRequest) Ec2Exception(software.amazon.awssdk.services.ec2.model.Ec2Exception) RunInstancesRequest(software.amazon.awssdk.services.ec2.model.RunInstancesRequest) Tag(software.amazon.awssdk.services.ec2.model.Tag)

Aggregations

CreateTagsRequest (software.amazon.awssdk.services.ec2.model.CreateTagsRequest)1 Ec2Exception (software.amazon.awssdk.services.ec2.model.Ec2Exception)1 RunInstancesRequest (software.amazon.awssdk.services.ec2.model.RunInstancesRequest)1 RunInstancesResponse (software.amazon.awssdk.services.ec2.model.RunInstancesResponse)1 Tag (software.amazon.awssdk.services.ec2.model.Tag)1