Example usage for com.amazonaws.services.ec2 AmazonEC2 createTags

List of usage examples for com.amazonaws.services.ec2 AmazonEC2 createTags

Introduction

In this page you can find the example usage for com.amazonaws.services.ec2 AmazonEC2 createTags.

Prototype

CreateTagsResult createTags(CreateTagsRequest createTagsRequest);

Source Link

Document

Adds or overwrites the specified tags for the specified Amazon EC2 resource or resources.

Usage

From source file:InlineTaggingCodeApp.java

License:Open Source License

/**
 * @param args/*from   w w  w .java 2s. com*/
 */
public static void main(String[] args) {
    //============================================================================================//
    //=============================== Submitting a Request =======================================//
    //============================================================================================//

    // Create the AmazonEC2Client object so we can call various APIs.
    AmazonEC2 ec2 = new AmazonEC2Client(new ClasspathPropertiesFileCredentialsProvider());
    Region usWest2 = Region.getRegion(Regions.US_EAST_1);
    ec2.setRegion(usWest2);

    // Initializes a Spot Instance Request
    RequestSpotInstancesRequest requestRequest = new RequestSpotInstancesRequest();

    // Request 1 x t1.micro instance with a bid price of $0.03.
    requestRequest.setSpotPrice("0.03");
    requestRequest.setInstanceCount(Integer.valueOf(1));

    // Setup the specifications of the launch. This includes the instance type (e.g. t1.micro)
    // and the latest Amazon Linux AMI id available. Note, you should always use the latest
    // Amazon Linux AMI id or another of your choosing.
    LaunchSpecification launchSpecification = new LaunchSpecification();
    launchSpecification.setImageId("ami-700e4a19");
    launchSpecification.setInstanceType("t1.micro");

    // Add the security group to the request.
    ArrayList<String> securityGroups = new ArrayList<String>();
    securityGroups.add("ForAssignment2");
    launchSpecification.setSecurityGroups(securityGroups);

    // Add the launch specifications to the request.
    requestRequest.setLaunchSpecification(launchSpecification);

    //============================================================================================//
    //=========================== Getting the Request ID from the Request ========================//
    //============================================================================================//

    // Call the RequestSpotInstance API.
    RequestSpotInstancesResult requestResult = ec2.requestSpotInstances(requestRequest);
    List<SpotInstanceRequest> requestResponses = requestResult.getSpotInstanceRequests();

    // Setup an arraylist to collect all of the request ids we want to watch hit the running
    // state.
    ArrayList<String> spotInstanceRequestIds = new ArrayList<String>();

    // Add all of the request ids to the hashset, so we can determine when they hit the
    // active state.
    for (SpotInstanceRequest requestResponse : requestResponses) {
        System.out.println("Created Spot Request: " + requestResponse.getSpotInstanceRequestId());
        spotInstanceRequestIds.add(requestResponse.getSpotInstanceRequestId());
    }

    //============================================================================================//
    //====================================== Tag the Spot Requests ===============================//
    //============================================================================================//

    // Create the list of tags we want to create
    ArrayList<Tag> requestTags = new ArrayList<Tag>();
    requestTags.add(new Tag("keyname1", "value1"));

    // Create a tag request for requests.
    CreateTagsRequest createTagsRequest_requests = new CreateTagsRequest();
    createTagsRequest_requests.setResources(spotInstanceRequestIds);
    createTagsRequest_requests.setTags(requestTags);

    // Try to tag the Spot request submitted.
    try {
        ec2.createTags(createTagsRequest_requests);
    } catch (AmazonServiceException e) {
        // Write out any exceptions that may have occurred.
        System.out.println("Error terminating instances");
        System.out.println("Caught Exception: " + e.getMessage());
        System.out.println("Reponse Status Code: " + e.getStatusCode());
        System.out.println("Error Code: " + e.getErrorCode());
        System.out.println("Request ID: " + e.getRequestId());
    }

    //============================================================================================//
    //=========================== Determining the State of the Spot Request ======================//
    //============================================================================================//

    // Create a variable that will track whether there are any requests still in the open state.
    boolean anyOpen;

    // Initialize variables.
    ArrayList<String> instanceIds = new ArrayList<String>();

    do {
        // Create the describeRequest with tall of the request id to monitor (e.g. that we started).
        DescribeSpotInstanceRequestsRequest describeRequest = new DescribeSpotInstanceRequestsRequest();
        describeRequest.setSpotInstanceRequestIds(spotInstanceRequestIds);

        // Initialize the anyOpen variable to false ??? which assumes there are no requests open unless
        // we find one that is still open.
        anyOpen = false;

        try {
            // Retrieve all of the requests we want to monitor.
            DescribeSpotInstanceRequestsResult describeResult = ec2
                    .describeSpotInstanceRequests(describeRequest);
            List<SpotInstanceRequest> describeResponses = describeResult.getSpotInstanceRequests();

            // Look through each request and determine if they are all in the active state.
            for (SpotInstanceRequest describeResponse : describeResponses) {
                // If the state is open, it hasn't changed since we attempted to request it.
                // There is the potential for it to transition almost immediately to closed or
                // cancelled so we compare against open instead of active.
                if (describeResponse.getState().equals("open")) {
                    anyOpen = true;
                    break;
                }

                // Add the instance id to the list we will eventually terminate.
                instanceIds.add(describeResponse.getInstanceId());
            }
        } catch (AmazonServiceException e) {
            // If we have an exception, ensure we don't break out of the loop.
            // This prevents the scenario where there was blip on the wire.
            anyOpen = true;
        }

        try {
            // Sleep for 60 seconds.
            Thread.sleep(60 * 1000);
        } catch (Exception e) {
            // Do nothing because it woke up early.
        }
    } while (anyOpen);

    //============================================================================================//
    //====================================== Tag the Spot Instances ===============================//
    //============================================================================================//

    // Create the list of tags we want to create
    ArrayList<Tag> instanceTags = new ArrayList<Tag>();
    instanceTags.add(new Tag("keyname1", "value1"));

    // Create a tag request for instances.
    CreateTagsRequest createTagsRequest_instances = new CreateTagsRequest();
    createTagsRequest_instances.setResources(instanceIds);
    createTagsRequest_instances.setTags(instanceTags);

    // Try to tag the Spot instance started.
    try {
        ec2.createTags(createTagsRequest_instances);
    } catch (AmazonServiceException e) {
        // Write out any exceptions that may have occurred.
        System.out.println("Error terminating instances");
        System.out.println("Caught Exception: " + e.getMessage());
        System.out.println("Reponse Status Code: " + e.getStatusCode());
        System.out.println("Error Code: " + e.getErrorCode());
        System.out.println("Request ID: " + e.getRequestId());
    }

    //============================================================================================//
    //====================================== Canceling the Request ==============================//
    //============================================================================================//

    try {
        // Cancel requests.
        CancelSpotInstanceRequestsRequest cancelRequest = new CancelSpotInstanceRequestsRequest(
                spotInstanceRequestIds);
        ec2.cancelSpotInstanceRequests(cancelRequest);
    } catch (AmazonServiceException e) {
        // Write out any exceptions that may have occurred.
        System.out.println("Error cancelling instances");
        System.out.println("Caught Exception: " + e.getMessage());
        System.out.println("Reponse Status Code: " + e.getStatusCode());
        System.out.println("Error Code: " + e.getErrorCode());
        System.out.println("Request ID: " + e.getRequestId());
    }

    //============================================================================================//
    //=================================== Terminating any Instances ==============================//
    //============================================================================================//
    try {
        // Terminate instances.
        TerminateInstancesRequest terminateRequest = new TerminateInstancesRequest(instanceIds);
        ec2.terminateInstances(terminateRequest);
    } catch (AmazonServiceException e) {
        // Write out any exceptions that may have occurred.
        System.out.println("Error terminating instances");
        System.out.println("Caught Exception: " + e.getMessage());
        System.out.println("Reponse Status Code: " + e.getStatusCode());
        System.out.println("Error Code: " + e.getErrorCode());
        System.out.println("Request ID: " + e.getRequestId());
    }

}

From source file:InlineTaggingCodeSampleApp.java

License:Open Source License

public static void main(String[] args) {
    //============================================================================================//
    //=============================== Submitting a Request =======================================//
    //============================================================================================//

    /*/*ww w. j  a v  a 2  s  . c  o m*/
     * The ProfileCredentialsProvider will return your [haow2]
     * credential profile by reading from the credentials file located at
     * (/Users/Dawn/.aws/credentials).
     */
    AWSCredentials credentials = null;
    try {
        credentials = new ProfileCredentialsProvider("haow2").getCredentials();
    } catch (Exception e) {
        throw new AmazonClientException("Cannot load the credentials from the credential profiles file. "
                + "Please make sure that your credentials file is at the correct "
                + "location (/Users/Dawn/.aws/credentials), and is in valid format.", e);
    }

    // Create the AmazonEC2Client object so we can call various APIs.
    AmazonEC2 ec2 = new AmazonEC2Client(credentials);
    Region usWest2 = Region.getRegion(Regions.US_WEST_2);
    ec2.setRegion(usWest2);

    // Initializes a Spot Instance Request
    RequestSpotInstancesRequest requestRequest = new RequestSpotInstancesRequest();

    // Request 1 x t1.micro instance with a bid price of $0.03.
    requestRequest.setSpotPrice("0.03");
    requestRequest.setInstanceCount(Integer.valueOf(1));

    // Setup the specifications of the launch. This includes the instance type (e.g. t1.micro)
    // and the latest Amazon Linux AMI id available. Note, you should always use the latest
    // Amazon Linux AMI id or another of your choosing.
    LaunchSpecification launchSpecification = new LaunchSpecification();
    launchSpecification.setImageId("ami-8c1fece5");
    launchSpecification.setInstanceType("t1.micro");

    // Add the security group to the request.
    ArrayList<String> securityGroups = new ArrayList<String>();
    securityGroups.add("GettingStartedGroup");
    launchSpecification.setSecurityGroups(securityGroups);

    // Add the launch specifications to the request.
    requestRequest.setLaunchSpecification(launchSpecification);

    //============================================================================================//
    //=========================== Getting the Request ID from the Request ========================//
    //============================================================================================//

    // Call the RequestSpotInstance API.
    RequestSpotInstancesResult requestResult = ec2.requestSpotInstances(requestRequest);
    List<SpotInstanceRequest> requestResponses = requestResult.getSpotInstanceRequests();

    // Setup an arraylist to collect all of the request ids we want to watch hit the running
    // state.
    ArrayList<String> spotInstanceRequestIds = new ArrayList<String>();

    // Add all of the request ids to the hashset, so we can determine when they hit the
    // active state.
    for (SpotInstanceRequest requestResponse : requestResponses) {
        System.out.println("Created Spot Request: " + requestResponse.getSpotInstanceRequestId());
        spotInstanceRequestIds.add(requestResponse.getSpotInstanceRequestId());
    }

    //============================================================================================//
    //====================================== Tag the Spot Requests ===============================//
    //============================================================================================//

    // Create the list of tags we want to create
    ArrayList<Tag> requestTags = new ArrayList<Tag>();
    requestTags.add(new Tag("keyname1", "value1"));

    // Create a tag request for requests.
    CreateTagsRequest createTagsRequest_requests = new CreateTagsRequest();
    createTagsRequest_requests.setResources(spotInstanceRequestIds);
    createTagsRequest_requests.setTags(requestTags);

    // Try to tag the Spot request submitted.
    try {
        ec2.createTags(createTagsRequest_requests);
    } catch (AmazonServiceException e) {
        // Write out any exceptions that may have occurred.
        System.out.println("Error terminating instances");
        System.out.println("Caught Exception: " + e.getMessage());
        System.out.println("Reponse Status Code: " + e.getStatusCode());
        System.out.println("Error Code: " + e.getErrorCode());
        System.out.println("Request ID: " + e.getRequestId());
    }

    //============================================================================================//
    //=========================== Determining the State of the Spot Request ======================//
    //============================================================================================//

    // Create a variable that will track whether there are any requests still in the open state.
    boolean anyOpen;

    // Initialize variables.
    ArrayList<String> instanceIds = new ArrayList<String>();

    do {
        // Create the describeRequest with tall of the request id to monitor (e.g. that we started).
        DescribeSpotInstanceRequestsRequest describeRequest = new DescribeSpotInstanceRequestsRequest();
        describeRequest.setSpotInstanceRequestIds(spotInstanceRequestIds);

        // Initialize the anyOpen variable to false, which assumes there are no requests open unless
        // we find one that is still open.
        anyOpen = false;

        try {
            // Retrieve all of the requests we want to monitor.
            DescribeSpotInstanceRequestsResult describeResult = ec2
                    .describeSpotInstanceRequests(describeRequest);
            List<SpotInstanceRequest> describeResponses = describeResult.getSpotInstanceRequests();

            // Look through each request and determine if they are all in the active state.
            for (SpotInstanceRequest describeResponse : describeResponses) {
                // If the state is open, it hasn't changed since we attempted to request it.
                // There is the potential for it to transition almost immediately to closed or
                // cancelled so we compare against open instead of active.
                if (describeResponse.getState().equals("open")) {
                    anyOpen = true;
                    break;
                }

                // Add the instance id to the list we will eventually terminate.
                instanceIds.add(describeResponse.getInstanceId());
            }
        } catch (AmazonServiceException e) {
            // If we have an exception, ensure we don't break out of the loop.
            // This prevents the scenario where there was blip on the wire.
            anyOpen = true;
        }

        try {
            // Sleep for 60 seconds.
            Thread.sleep(60 * 1000);
        } catch (Exception e) {
            // Do nothing because it woke up early.
        }
    } while (anyOpen);

    //============================================================================================//
    //====================================== Tag the Spot Instances ===============================//
    //============================================================================================//

    // Create the list of tags we want to create
    ArrayList<Tag> instanceTags = new ArrayList<Tag>();
    instanceTags.add(new Tag("keyname1", "value1"));

    // Create a tag request for instances.
    CreateTagsRequest createTagsRequest_instances = new CreateTagsRequest();
    createTagsRequest_instances.setResources(instanceIds);
    createTagsRequest_instances.setTags(instanceTags);

    // Try to tag the Spot instance started.
    try {
        ec2.createTags(createTagsRequest_instances);
    } catch (AmazonServiceException e) {
        // Write out any exceptions that may have occurred.
        System.out.println("Error terminating instances");
        System.out.println("Caught Exception: " + e.getMessage());
        System.out.println("Reponse Status Code: " + e.getStatusCode());
        System.out.println("Error Code: " + e.getErrorCode());
        System.out.println("Request ID: " + e.getRequestId());
    }

    //============================================================================================//
    //====================================== Canceling the Request ==============================//
    //============================================================================================//

    try {
        // Cancel requests.
        CancelSpotInstanceRequestsRequest cancelRequest = new CancelSpotInstanceRequestsRequest(
                spotInstanceRequestIds);
        ec2.cancelSpotInstanceRequests(cancelRequest);
    } catch (AmazonServiceException e) {
        // Write out any exceptions that may have occurred.
        System.out.println("Error cancelling instances");
        System.out.println("Caught Exception: " + e.getMessage());
        System.out.println("Reponse Status Code: " + e.getStatusCode());
        System.out.println("Error Code: " + e.getErrorCode());
        System.out.println("Request ID: " + e.getRequestId());
    }

    //============================================================================================//
    //=================================== Terminating any Instances ==============================//
    //============================================================================================//
    try {
        // Terminate instances.
        TerminateInstancesRequest terminateRequest = new TerminateInstancesRequest(instanceIds);
        ec2.terminateInstances(terminateRequest);
    } catch (AmazonServiceException e) {
        // Write out any exceptions that may have occurred.
        System.out.println("Error terminating instances");
        System.out.println("Caught Exception: " + e.getMessage());
        System.out.println("Reponse Status Code: " + e.getStatusCode());
        System.out.println("Error Code: " + e.getErrorCode());
        System.out.println("Request ID: " + e.getRequestId());
    }

}

From source file:advanced.InlineTaggingCodeSampleApp.java

License:Open Source License

/**
 * @param args/*  www  .j  a  v  a2 s . c  om*/
 */
public static void main(String[] args) {
    //============================================================================================//
    //=============================== Submitting a Request =======================================// 
    //============================================================================================//

    // Retrieves the credentials from an AWSCredentials.properties file.
    AWSCredentials credentials = null;
    try {
        credentials = new PropertiesCredentials(
                InlineTaggingCodeSampleApp.class.getResourceAsStream("AwsCredentials.properties"));
    } catch (IOException e1) {
        System.out.println("Credentials were not properly entered into AwsCredentials.properties.");
        System.out.println(e1.getMessage());
        System.exit(-1);
    }

    // Create the AmazonEC2Client object so we can call various APIs.
    AmazonEC2 ec2 = new AmazonEC2Client(credentials);

    // Initializes a Spot Instance Request
    RequestSpotInstancesRequest requestRequest = new RequestSpotInstancesRequest();

    // Request 1 x t1.micro instance with a bid price of $0.03. 
    requestRequest.setSpotPrice("0.03");
    requestRequest.setInstanceCount(Integer.valueOf(1));

    // Setup the specifications of the launch. This includes the instance type (e.g. t1.micro)
    // and the latest Amazon Linux AMI id available. Note, you should always use the latest 
    // Amazon Linux AMI id or another of your choosing.
    LaunchSpecification launchSpecification = new LaunchSpecification();
    launchSpecification.setImageId("ami-8c1fece5");
    launchSpecification.setInstanceType("t1.micro");

    // Add the security group to the request.
    ArrayList<String> securityGroups = new ArrayList<String>();
    securityGroups.add("GettingStartedGroup");
    launchSpecification.setSecurityGroups(securityGroups);

    // Add the launch specifications to the request.
    requestRequest.setLaunchSpecification(launchSpecification);

    //============================================================================================//
    //=========================== Getting the Request ID from the Request ========================// 
    //============================================================================================//

    // Call the RequestSpotInstance API. 
    RequestSpotInstancesResult requestResult = ec2.requestSpotInstances(requestRequest);
    List<SpotInstanceRequest> requestResponses = requestResult.getSpotInstanceRequests();

    // Setup an arraylist to collect all of the request ids we want to watch hit the running
    // state.
    ArrayList<String> spotInstanceRequestIds = new ArrayList<String>();

    // Add all of the request ids to the hashset, so we can determine when they hit the 
    // active state.
    for (SpotInstanceRequest requestResponse : requestResponses) {
        System.out.println("Created Spot Request: " + requestResponse.getSpotInstanceRequestId());
        spotInstanceRequestIds.add(requestResponse.getSpotInstanceRequestId());
    }

    //============================================================================================//
    //====================================== Tag the Spot Requests ===============================// 
    //============================================================================================//

    // Create the list of tags we want to create
    ArrayList<Tag> requestTags = new ArrayList<Tag>();
    requestTags.add(new Tag("keyname1", "value1"));

    // Create a tag request for requests.
    CreateTagsRequest createTagsRequest_requests = new CreateTagsRequest();
    createTagsRequest_requests.setResources(spotInstanceRequestIds);
    createTagsRequest_requests.setTags(requestTags);

    // Try to tag the Spot request submitted.
    try {
        ec2.createTags(createTagsRequest_requests);
    } catch (AmazonServiceException e) {
        // Write out any exceptions that may have occurred.
        System.out.println("Error terminating instances");
        System.out.println("Caught Exception: " + e.getMessage());
        System.out.println("Reponse Status Code: " + e.getStatusCode());
        System.out.println("Error Code: " + e.getErrorCode());
        System.out.println("Request ID: " + e.getRequestId());
    }

    //============================================================================================//
    //=========================== Determining the State of the Spot Request ======================// 
    //============================================================================================//

    // Create a variable that will track whether there are any requests still in the open state.
    boolean anyOpen;

    // Initialize variables.
    ArrayList<String> instanceIds = new ArrayList<String>();

    do {
        // Create the describeRequest with tall of the request id to monitor (e.g. that we started).
        DescribeSpotInstanceRequestsRequest describeRequest = new DescribeSpotInstanceRequestsRequest();
        describeRequest.setSpotInstanceRequestIds(spotInstanceRequestIds);

        // Initialize the anyOpen variable to false  which assumes there are no requests open unless
        // we find one that is still open.
        anyOpen = false;

        try {
            // Retrieve all of the requests we want to monitor. 
            DescribeSpotInstanceRequestsResult describeResult = ec2
                    .describeSpotInstanceRequests(describeRequest);
            List<SpotInstanceRequest> describeResponses = describeResult.getSpotInstanceRequests();

            // Look through each request and determine if they are all in the active state.
            for (SpotInstanceRequest describeResponse : describeResponses) {
                // If the state is open, it hasn't changed since we attempted to request it.
                // There is the potential for it to transition almost immediately to closed or
                // cancelled so we compare against open instead of active.
                if (describeResponse.getState().equals("open")) {
                    anyOpen = true;
                    break;
                }

                // Add the instance id to the list we will eventually terminate.
                instanceIds.add(describeResponse.getInstanceId());
            }
        } catch (AmazonServiceException e) {
            // If we have an exception, ensure we don't break out of the loop.
            // This prevents the scenario where there was blip on the wire.
            anyOpen = true;
        }

        try {
            // Sleep for 60 seconds.
            Thread.sleep(60 * 1000);
        } catch (Exception e) {
            // Do nothing because it woke up early.
        }
    } while (anyOpen);

    //============================================================================================//
    //====================================== Tag the Spot Instances ===============================// 
    //============================================================================================//

    // Create the list of tags we want to create
    ArrayList<Tag> instanceTags = new ArrayList<Tag>();
    instanceTags.add(new Tag("keyname1", "value1"));

    // Create a tag request for instances.
    CreateTagsRequest createTagsRequest_instances = new CreateTagsRequest();
    createTagsRequest_instances.setResources(instanceIds);
    createTagsRequest_instances.setTags(instanceTags);

    // Try to tag the Spot instance started.
    try {
        ec2.createTags(createTagsRequest_instances);
    } catch (AmazonServiceException e) {
        // Write out any exceptions that may have occurred.
        System.out.println("Error terminating instances");
        System.out.println("Caught Exception: " + e.getMessage());
        System.out.println("Reponse Status Code: " + e.getStatusCode());
        System.out.println("Error Code: " + e.getErrorCode());
        System.out.println("Request ID: " + e.getRequestId());
    }

    //============================================================================================//
    //====================================== Canceling the Request ==============================// 
    //============================================================================================//

    try {
        // Cancel requests.
        CancelSpotInstanceRequestsRequest cancelRequest = new CancelSpotInstanceRequestsRequest(
                spotInstanceRequestIds);
        ec2.cancelSpotInstanceRequests(cancelRequest);
    } catch (AmazonServiceException e) {
        // Write out any exceptions that may have occurred.
        System.out.println("Error cancelling instances");
        System.out.println("Caught Exception: " + e.getMessage());
        System.out.println("Reponse Status Code: " + e.getStatusCode());
        System.out.println("Error Code: " + e.getErrorCode());
        System.out.println("Request ID: " + e.getRequestId());
    }

    //============================================================================================//
    //=================================== Terminating any Instances ==============================// 
    //============================================================================================//
    try {
        // Terminate instances.
        TerminateInstancesRequest terminateRequest = new TerminateInstancesRequest(instanceIds);
        ec2.terminateInstances(terminateRequest);
    } catch (AmazonServiceException e) {
        // Write out any exceptions that may have occurred.
        System.out.println("Error terminating instances");
        System.out.println("Caught Exception: " + e.getMessage());
        System.out.println("Reponse Status Code: " + e.getStatusCode());
        System.out.println("Error Code: " + e.getErrorCode());
        System.out.println("Request ID: " + e.getRequestId());
    }

}

From source file:aws.example.ec2.CreateInstance.java

License:Open Source License

public static void main(String[] args) {
    final String USAGE = "To run this example, supply an instance name and AMI image id\n"
            + "Ex: CreateInstance <instance-name> <ami-image-id>\n";

    if (args.length != 2) {
        System.out.println(USAGE);
        System.exit(1);//  w w  w . j  ava2  s .c o m
    }

    String name = args[0];
    String ami_id = args[1];

    final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient();

    RunInstancesRequest run_request = new RunInstancesRequest().withImageId(ami_id)
            .withInstanceType(InstanceType.T1Micro).withMaxCount(1).withMinCount(1);

    RunInstancesResult run_response = ec2.runInstances(run_request);

    String instance_id = run_response.getReservation().getReservationId();

    Tag tag = new Tag().withKey("Name").withValue(name);

    CreateTagsRequest tag_request = new CreateTagsRequest().withTags(tag);

    CreateTagsResult tag_response = ec2.createTags(tag_request);

    System.out.printf("Successfully started EC2 instance %s based on AMI %s", instance_id, ami_id);
}

From source file:aws.sample.InlineTaggingCodeSampleApp.java

License:Open Source License

/**
 * @param args//from   w w  w  .  java 2s. c  om
 */
public static void main(String[] args) {
    // ============================================================================================//
    // =============================== Submitting a Request =======================================//
    // ============================================================================================//

    // Retrieves the credentials from an AWSCredentials.properties file.
    AWSCredentials credentials = null;
    try {
        credentials = new PropertiesCredentials(
                InlineTaggingCodeSampleApp.class.getResourceAsStream("/AwsCredentials.properties"));
    } catch (IOException e1) {
        System.out.println("Credentials were not properly entered into AwsCredentials.properties.");
        System.out.println(e1.getMessage());
        System.exit(-1);
    }

    // Create the AmazonEC2Client object so we can call various APIs.
    AmazonEC2 ec2 = new AmazonEC2Client(credentials);

    // Initializes a Spot Instance Request
    RequestSpotInstancesRequest requestRequest = new RequestSpotInstancesRequest();

    // Request 1 x t1.micro instance with a bid price of $0.03.
    requestRequest.setSpotPrice("0.03");
    requestRequest.setInstanceCount(Integer.valueOf(1));

    // Setup the specifications of the launch. This includes the instance type (e.g. t1.micro)
    // and the latest Amazon Linux AMI id available. Note, you should always use the latest
    // Amazon Linux AMI id or another of your choosing.
    LaunchSpecification launchSpecification = new LaunchSpecification();
    launchSpecification.setImageId("ami-8c1fece5");
    launchSpecification.setInstanceType("t1.micro");

    // Add the security group to the request.
    ArrayList<String> securityGroups = new ArrayList<String>();
    securityGroups.add("default");
    launchSpecification.setSecurityGroups(securityGroups);

    // Add the launch specifications to the request.
    requestRequest.setLaunchSpecification(launchSpecification);

    // ============================================================================================//
    // =========================== Getting the Request ID from the Request ========================//
    // ============================================================================================//

    // Call the RequestSpotInstance API.
    RequestSpotInstancesResult requestResult = ec2.requestSpotInstances(requestRequest);
    List<SpotInstanceRequest> requestResponses = requestResult.getSpotInstanceRequests();

    // Setup an arraylist to collect all of the request ids we want to watch hit the running
    // state.
    ArrayList<String> spotInstanceRequestIds = new ArrayList<String>();

    // Add all of the request ids to the hashset, so we can determine when they hit the
    // active state.
    for (SpotInstanceRequest requestResponse : requestResponses) {
        System.out.println("Created Spot Request: " + requestResponse.getSpotInstanceRequestId());
        spotInstanceRequestIds.add(requestResponse.getSpotInstanceRequestId());
    }

    // ============================================================================================//
    // ====================================== Tag the Spot Requests ===============================//
    // ============================================================================================//

    // Create the list of tags we want to create
    ArrayList<Tag> requestTags = new ArrayList<Tag>();
    requestTags.add(new Tag("keyname1", "value1"));

    // Create a tag request for requests.
    CreateTagsRequest createTagsRequest_requests = new CreateTagsRequest();
    createTagsRequest_requests.setResources(spotInstanceRequestIds);
    createTagsRequest_requests.setTags(requestTags);

    // Try to tag the Spot request submitted.
    try {
        ec2.createTags(createTagsRequest_requests);
    } catch (AmazonServiceException e) {
        // Write out any exceptions that may have occurred.
        System.out.println("Error terminating instances");
        System.out.println("Caught Exception: " + e.getMessage());
        System.out.println("Reponse Status Code: " + e.getStatusCode());
        System.out.println("Error Code: " + e.getErrorCode());
        System.out.println("Request ID: " + e.getRequestId());
    }

    // ============================================================================================//
    // =========================== Determining the State of the Spot Request ======================//
    // ============================================================================================//

    // Create a variable that will track whether there are any requests still in the open state.
    boolean anyOpen;

    // Initialize variables.
    ArrayList<String> instanceIds = new ArrayList<String>();

    do {
        // Create the describeRequest with tall of the request id to monitor (e.g. that we started).
        DescribeSpotInstanceRequestsRequest describeRequest = new DescribeSpotInstanceRequestsRequest();
        describeRequest.setSpotInstanceRequestIds(spotInstanceRequestIds);

        // Initialize the anyOpen variable to false ?which assumes there are no requests open unless
        // we find one that is still open.
        anyOpen = false;

        try {
            // Retrieve all of the requests we want to monitor.
            DescribeSpotInstanceRequestsResult describeResult = ec2
                    .describeSpotInstanceRequests(describeRequest);
            List<SpotInstanceRequest> describeResponses = describeResult.getSpotInstanceRequests();

            // Look through each request and determine if they are all in the active state.
            for (SpotInstanceRequest describeResponse : describeResponses) {
                // If the state is open, it hasn't changed since we attempted to request it.
                // There is the potential for it to transition almost immediately to closed or
                // cancelled so we compare against open instead of active.
                if (describeResponse.getState().equals("open")) {
                    anyOpen = true;
                    break;
                }

                // Add the instance id to the list we will eventually terminate.
                instanceIds.add(describeResponse.getInstanceId());
            }
        } catch (AmazonServiceException e) {
            // If we have an exception, ensure we don't break out of the loop.
            // This prevents the scenario where there was blip on the wire.
            anyOpen = true;
        }

        try {
            // Sleep for 60 seconds.
            Thread.sleep(6 * 1000);
        } catch (Exception e) {
            // Do nothing because it woke up early.
        }
    } while (anyOpen);

    // ============================================================================================//
    // ====================================== Tag the Spot Instances ===============================//
    // ============================================================================================//

    // Create the list of tags we want to create
    ArrayList<Tag> instanceTags = new ArrayList<Tag>();
    instanceTags.add(new Tag("keyname1", "value1"));

    // Create a tag request for instances.
    CreateTagsRequest createTagsRequest_instances = new CreateTagsRequest();
    createTagsRequest_instances.setResources(instanceIds);
    createTagsRequest_instances.setTags(instanceTags);

    // Try to tag the Spot instance started.
    try {
        ec2.createTags(createTagsRequest_instances);
    } catch (AmazonServiceException e) {
        // Write out any exceptions that may have occurred.
        System.out.println("Error terminating instances");
        System.out.println("Caught Exception: " + e.getMessage());
        System.out.println("Reponse Status Code: " + e.getStatusCode());
        System.out.println("Error Code: " + e.getErrorCode());
        System.out.println("Request ID: " + e.getRequestId());
    }

    // ============================================================================================//
    // ====================================== Canceling the Request ==============================//
    // ============================================================================================//

    try {
        // Cancel requests.
        CancelSpotInstanceRequestsRequest cancelRequest = new CancelSpotInstanceRequestsRequest(
                spotInstanceRequestIds);
        ec2.cancelSpotInstanceRequests(cancelRequest);
    } catch (AmazonServiceException e) {
        // Write out any exceptions that may have occurred.
        System.out.println("Error cancelling instances");
        System.out.println("Caught Exception: " + e.getMessage());
        System.out.println("Reponse Status Code: " + e.getStatusCode());
        System.out.println("Error Code: " + e.getErrorCode());
        System.out.println("Request ID: " + e.getRequestId());
    }

    // ============================================================================================//
    // =================================== Terminating any Instances ==============================//
    // ============================================================================================//
    try {
        // Terminate instances.
        TerminateInstancesRequest terminateRequest = new TerminateInstancesRequest(instanceIds);
        ec2.terminateInstances(terminateRequest);
    } catch (AmazonServiceException e) {
        // Write out any exceptions that may have occurred.
        System.out.println("Error terminating instances");
        System.out.println("Caught Exception: " + e.getMessage());
        System.out.println("Reponse Status Code: " + e.getStatusCode());
        System.out.println("Error Code: " + e.getErrorCode());
        System.out.println("Request ID: " + e.getRequestId());
    }

}

From source file:com.appdynamics.connectors.AWSConnector.java

License:Apache License

public IMachine createMachine(IComputeCenter computeCenter, IImage image, IMachineDescriptor machineDescriptor)
        throws InvalidObjectException, ConnectorException {
    boolean succeeded = false;
    Exception createFailureRootCause = null;
    Instance instance = null;//from  ww w .j av  a 2s .  c  om

    try {
        IProperty[] macProps = machineDescriptor.getProperties();

        AmazonEC2 connector = getConnector(image, computeCenter, controllerServices);
        String amiName = Utils.getAMIName(image.getProperties(), controllerServices);
        List<String> securityGroups = getSecurityGroup(macProps);
        validateAndConfigureSecurityGroups(securityGroups, connector);

        controllerServices.getStringPropertyByName(macProps, Utils.SECURITY_GROUP)
                .setValue(getSecurityGroupsAsString(securityGroups));

        String keyPair = Utils.getKeyPair(macProps, controllerServices);

        InstanceType instanceType = getInstanceType(macProps);

        String zone = Utils.getZone(macProps, controllerServices);
        String kernel = Utils.getKernel(macProps, controllerServices);
        String ramdisk = Utils.getRamDisk(macProps, controllerServices);

        String controllerHost = System.getProperty(CONTROLLER_SERVICES_HOST_NAME_PROPERTY_KEY,
                InetAddress.getLocalHost().getHostName());

        int controllerPort = Integer.getInteger(CONTROLLER_SERVICES_PORT_PROPERTY_KEY,
                DEFAULT_CONTROLLER_PORT_VALUE);

        IAccount account = computeCenter.getAccount();

        String accountName = account.getName();
        String accountAccessKey = account.getAccessKey();

        AgentResolutionEncoder agentResolutionEncoder = new AgentResolutionEncoder(controllerHost,
                controllerPort, accountName, accountAccessKey);

        String userData = agentResolutionEncoder.encodeAgentResolutionInfo();

        String instanceName = Utils.getInstanceName(macProps, controllerServices);

        logger.info("Starting EC2 machine of Image :" + amiName + " Name :" + instanceName + " security :"
                + securityGroups + " keypair :" + keyPair + " instance :" + instanceType + " zone :" + zone
                + " kernel :" + kernel + " ramdisk :" + ramdisk + " userData :" + userData);

        RunInstancesRequest runInstancesRequest = new RunInstancesRequest(amiName, 1, 1);
        runInstancesRequest.setSecurityGroups(securityGroups);
        runInstancesRequest.setUserData(Base64.encodeAsString(userData.getBytes()));
        runInstancesRequest.setKeyName(keyPair);
        runInstancesRequest.setInstanceType(instanceType);
        runInstancesRequest.setKernelId(kernel);
        runInstancesRequest.setRamdiskId(ramdisk);

        Reservation reservation = connector.runInstances(runInstancesRequest).getReservation();
        List<Instance> instances = reservation.getInstances();

        if (instances.size() == 0)
            throw new ConnectorException("Cannot create instance for image :" + image.getName());

        instance = instances.get(0);

        //Set name for the instance
        if (!Strings.isNullOrEmpty(instanceName)) {
            CreateTagsRequest createTagsRequest = new CreateTagsRequest();
            createTagsRequest.withResources(instance.getInstanceId()).withTags(new Tag("Name", instanceName));
            connector.createTags(createTagsRequest);
        }

        logger.info("EC2 machine started; id:" + instance.getInstanceId());

        IMachine machine;

        if (Strings.isNullOrEmpty(instance.getPublicDnsName())) {
            machine = controllerServices.createMachineInstance(instance.getInstanceId(),
                    agentResolutionEncoder.getUniqueHostIdentifier(), computeCenter, machineDescriptor, image,
                    getAgentPort());
        } else {
            machine = controllerServices.createMachineInstance(instance.getInstanceId(),
                    agentResolutionEncoder.getUniqueHostIdentifier(), instance.getPublicDnsName(),
                    computeCenter, machineDescriptor, image, getAgentPort());
        }

        if (kernel == null) {
            controllerServices.getStringPropertyByName(macProps, Utils.KERNEL).setValue(instance.getKernelId());
        }

        if (zone == null) {
            DescribeAvailabilityZonesResult describeAvailabilityZonesResult = connector
                    .describeAvailabilityZones();
            List<AvailabilityZone> availabilityZones = describeAvailabilityZonesResult.getAvailabilityZones();
            controllerServices.getStringPropertyByName(macProps, Utils.ZONE)
                    .setValue(availabilityZones.get(0).getZoneName());
        }

        controllerServices.getStringPropertyByName(macProps, Utils.INSTANCE_TYPE)
                .setValue(instance.getInstanceType());

        succeeded = true;

        return machine;

    } catch (InvalidObjectException e) {
        createFailureRootCause = e;
        throw e;
    } catch (ConnectorException e) {
        createFailureRootCause = e;
        throw e;
    } catch (Exception e) {
        createFailureRootCause = e;
        throw new ConnectorException(e.getMessage(), e);
    } finally {
        // We have to make sure to terminate any orphan EC2 instances if 
        // the machine create fails.
        if (!succeeded && instance != null) {
            try {
                ConnectorLocator.getInstance().getConnector(computeCenter, controllerServices)
                        .terminateInstances(
                                new TerminateInstancesRequest(Lists.newArrayList(instance.getInstanceId())));
            } catch (Exception e) {
                throw new ConnectorException("Machine create failed, but terminate failed as well! "
                        + "We have an orphan EC2 instance with id: " + instance.getInstanceId()
                        + " that must be shut down manually. Root cause for machine "
                        + "create failure is following: ", createFailureRootCause);
            }
        }
    }
}

From source file:com.netflix.simianarmy.client.aws.AWSClient.java

License:Apache License

@Override
public void createTagsForResources(Map<String, String> keyValueMap, String... resourceIds) {
    Validate.notNull(keyValueMap);/*  www .ja  v  a 2s . co  m*/
    Validate.notEmpty(keyValueMap);
    Validate.notNull(resourceIds);
    Validate.notEmpty(resourceIds);
    AmazonEC2 ec2Client = ec2Client();
    List<Tag> tags = new ArrayList<Tag>();
    for (Map.Entry<String, String> entry : keyValueMap.entrySet()) {
        tags.add(new Tag(entry.getKey(), entry.getValue()));
    }
    CreateTagsRequest req = new CreateTagsRequest(Arrays.asList(resourceIds), tags);
    ec2Client.createTags(req);
}

From source file:com.urbancode.terraform.tasks.aws.helpers.AWSHelper.java

License:Apache License

/**
 *
 * @param instanceId//from  w  w  w.j  av a2s  . c  o m
 * @param tag
 * @param value
 * @param ec2Client
 */
public void tagInstance(String instanceId, String tag, String value, AmazonEC2 ec2Client) {
    //quick fix
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        // swallow
    }
    CreateTagsRequest request = new CreateTagsRequest();
    request = request.withResources(instanceId).withTags(new Tag(tag, value));
    ec2Client.createTags(request);
}

From source file:datameer.awstasks.ant.ec2.Ec2LaunchTask.java

License:Apache License

@Override
public void doExecute(AmazonEC2 ec2) throws BuildException {
    LOG.info("executing " + getClass().getSimpleName() + " with groupName '" + _groupName + "'");
    try {/*  ww w  . j a  v  a 2  s  . c o m*/
        boolean instancesRunning = Ec2Util.findByGroup(ec2, _groupName, false, InstanceStateName.Pending,
                InstanceStateName.Running) != null;
        if (!isReuseRunningInstances() && instancesRunning) {
            throw new IllegalStateException("found already running instances for group '" + _groupName + "'");
        }
        if (!Ec2Util.groupExists(ec2, _groupName)) {
            LOG.info("group '" + _groupName + "' does not exists - creating it");
            String groupDescription = getGroupDescription();
            if (groupDescription == null) {
                throw new BuildException("must specify groupDescription");
            }
            ec2.createSecurityGroup(new CreateSecurityGroupRequest(_groupName, groupDescription));
        }

        List<String> securityGroups = Arrays.asList("default", _groupName);
        List<IpPermission> existingPermissions = Ec2Util.getPermissions(ec2, securityGroups);
        for (GroupPermission groupPermission : _groupPermissions) {
            if (groupPermission.getToPort() == -1) {
                groupPermission.setToPort(groupPermission.getFromPort());
            }
            if (!permissionExists(groupPermission, existingPermissions)) {
                LOG.info("did not found permission '" + groupPermission + "' - creating it...");
                ec2.authorizeSecurityGroupIngress(new AuthorizeSecurityGroupIngressRequest()
                        .withGroupName(_groupName).withIpPermissions(groupPermission.toIpPermission()));
            }
        }

        InstanceGroup instanceGroup = new InstanceGroupImpl(ec2);
        RunInstancesRequest launchConfiguration = new RunInstancesRequest(_ami, _instanceCount, _instanceCount);
        if (_kernelId != null) {
            launchConfiguration.setKernelId(_kernelId);
        }
        if (_ramDiskId != null) {
            launchConfiguration.setKernelId(_ramDiskId);
        }
        launchConfiguration.setKeyName(_privateKeyName);
        launchConfiguration.setSecurityGroups(securityGroups);
        if (_userData != null) {
            launchConfiguration.setUserData(Base64.encodeBase64String(_userData.getBytes()));
        }
        if (_instanceType != null) {
            launchConfiguration.setInstanceType(_instanceType);
        }
        launchConfiguration.setPlacement(new Placement(_availabilityZone));
        if (instancesRunning) {
            instanceGroup.connectTo(_groupName);
        } else {
            instanceGroup.launch(launchConfiguration, TimeUnit.MINUTES, _maxStartTime);
            if (_instanceName != null) {
                LOG.info("tagging instances with name '" + _instanceName + " [<idx>]'");
                int idx = 1;
                for (Instance instance : instanceGroup.getInstances(false)) {
                    CreateTagsRequest createTagsRequest = new CreateTagsRequest();
                    createTagsRequest.withResources(instance.getInstanceId()) //
                            .withTags(new Tag("Name", _instanceName + " [" + idx + "]"));
                    ec2.createTags(createTagsRequest);
                    idx++;
                }
            }
        }
    } catch (Exception e) {
        LOG.error("execution " + getClass().getSimpleName() + " with groupName '" + _groupName + "' failed: "
                + e.getMessage());
        throw new BuildException(e);
    }
}

From source file:ec2.CreateInstance.java

License:Open Source License

public static void main(String[] args) {

    final String USAGE = "To run this example, supply an instance name and AMI image id\n"
            + "Ex: CreateInstance <instance-name> <ami-image-id>\n";

    if (args.length != 2) {
        System.out.println(USAGE);
        System.exit(1);/*from  w ww  .  ja va  2 s.  c  o  m*/
    }

    String instanceName = args[0];
    String amiImageId = args[1];

    final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient();

    RunInstancesRequest runInstancesRequest = new RunInstancesRequest().withImageId(amiImageId)
            .withInstanceType(InstanceType.T1Micro).withMaxCount(1).withMinCount(1);

    RunInstancesResult runInstanceResponse = ec2.runInstances(runInstancesRequest);

    String instanceId = runInstanceResponse.getReservation().getReservationId();

    Tag nameTag = new Tag().withKey("Name").withValue(instanceName);

    CreateTagsRequest createTagsRequest = new CreateTagsRequest().withTags(nameTag);

    CreateTagsResult createTagsResponse = ec2.createTags(createTagsRequest);

    System.out.printf("Successfully started EC2 instance %s based on AMI %s", instanceId, amiImageId);
}