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

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

Introduction

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

Prototype

@Deprecated
void setRegion(com.amazonaws.regions.Region region);

Source Link

Document

An alternative to AmazonEC2#setEndpoint(String) , sets the regional endpoint for this client's service calls.

Usage

From source file:AwsAuto.java

License:Open Source License

public static void main(String[] args) throws Exception {

    // initialize/determine parameters
    String instanceType = "m3.medium";
    String loadGeneratorAmi = "ami-8ac4e9e0";
    String dataCenterAmi = "ami-349fbb5e";
    String bidPrice = "0.1";
    String loadGeneratorDns = null; // load generator DNS
    String dashboardUrl = null; // the URL where we check our performance
    String testId = null;//from www. j  av a  2  s .c  o  m

    // create project tag for instances
    ArrayList<com.amazonaws.services.ec2.model.Tag> loadGeneratorTags = new ArrayList<>();
    com.amazonaws.services.ec2.model.Tag loadGeneratorTag = new com.amazonaws.services.ec2.model.Tag("Project",
            "2.1");
    loadGeneratorTags.add(loadGeneratorTag);

    // create project tag for auto-scaling
    com.amazonaws.services.autoscaling.model.Tag asgTag = new com.amazonaws.services.autoscaling.model.Tag();
    asgTag.setKey("Project");
    asgTag.setValue("2.1");

    // create project tag for load balancer
    ArrayList<com.amazonaws.services.elasticloadbalancing.model.Tag> loadBalancerTags = new ArrayList<>();
    com.amazonaws.services.elasticloadbalancing.model.Tag loadBalancerTag = new com.amazonaws.services.elasticloadbalancing.model.Tag();
    loadBalancerTag.setKey("Project");
    loadBalancerTag.setValue("2.1");
    loadBalancerTags.add(loadBalancerTag);

    /**
     * =========================================================================
     * ================= Create security groups
     * =========================================================================
     * =================
     */

    String loadGeneratorSecurityName = "LoadGeneratorSGP2";
    String allPurposeSecurityName = "AllPurposeSGP2";
    SecurityGroup loadGeneratorSecurityGroup = new SecurityGroup(loadGeneratorSecurityName);
    SecurityGroup allPurposeSecurityGroup = new SecurityGroup(allPurposeSecurityName);

    /**
     * =========================================================================
     * ================= Grant permission and credentials
     * =========================================================================
     * =================
     */

    AWSCredentials credentials = null;
    try {
        credentials = new ProfileCredentialsProvider("School").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 (C:\\Users\\Jiabei\\.aws\\credentials), and is in valid format.", e);
    }

    // set region
    AmazonEC2 ec2 = new AmazonEC2Client(credentials);
    Region usEast1 = Region.getRegion(Regions.US_EAST_1);
    ec2.setRegion(usEast1);

    /**
     * =========================================================================
     * ================= Create a load generator and submit password
     * =========================================================================
     * =================
     */

    Requests requestsLg = new Requests(instanceType, loadGeneratorAmi, bidPrice, loadGeneratorSecurityName,
            loadGeneratorTags);
    loadGeneratorDns = requestsLg.submitRequests();
    String submissionUrl = "http://" + loadGeneratorDns
            + "/password?passwd=0WSb4ufhYI7SkxfLWnnIWU0MC1NdcNKT&andrewId=jiabeip";
    sendGET(submissionUrl);

    try {

        /**
         * =======================================================================
         * =================== Create a load balancer
         * =======================================================================
         * ===================
         */

        String loadBalancerDns = null;
        String loadBalancerName = "LoadBalancerProj2";
        String healthCheckPage = "/heartbeat?lg=" + loadGeneratorDns;
        AmazonElasticLoadBalancingClient loadBalancerClient = new AmazonElasticLoadBalancingClient(credentials);

        // configure a request
        CreateLoadBalancerRequest loadBalancerRequest = new CreateLoadBalancerRequest()
                .withAvailabilityZones("us-east-1b").withListeners(new Listener("HTTP", 80, 80))
                .withLoadBalancerName(loadBalancerName).withSecurityGroups(allPurposeSecurityGroup.getGroupId())
                .withTags(loadBalancerTags);

        CreateLoadBalancerResult loadBalancerResult = loadBalancerClient
                .createLoadBalancer(loadBalancerRequest);
        loadBalancerDns = loadBalancerResult.getDNSName();

        // configure health check setting
        HealthCheck loadBalancerHealthCheck = new HealthCheck().withTarget("HTTP:80" + healthCheckPage)
                .withTimeout(5).withInterval(30).withUnhealthyThreshold(2).withHealthyThreshold(10);

        ConfigureHealthCheckRequest healthCheckRequest = new ConfigureHealthCheckRequest()
                .withLoadBalancerName(loadBalancerName).withHealthCheck(loadBalancerHealthCheck);

        // attach health check setting to load balancer
        ConfigureHealthCheckResult healthCheckResult = loadBalancerClient
                .configureHealthCheck(healthCheckRequest);

        System.out.println("Load balancer created!\nDNS: " + loadBalancerDns);

        /**
         * =======================================================================
         * =================== Create launch configuration
         * =======================================================================
         * ===================
         */

        String launchConfigName = "LaunchConfigProj2";
        String autoScalingGroupName = "AutoScalingGroupProj2";

        AmazonAutoScalingClient autoScalingGroupClient = new AmazonAutoScalingClient(credentials);
        AmazonCloudWatchClient cloudWatchClient = new AmazonCloudWatchClient(credentials);

        System.out.println("Creating launch configuration...");

        // configure the request
        CreateLaunchConfigurationRequest launchConfigRequest = new CreateLaunchConfigurationRequest()
                .withImageId(dataCenterAmi).withInstanceType(instanceType)
                .withLaunchConfigurationName(launchConfigName)
                .withSecurityGroups(allPurposeSecurityGroup.getGroupId()).withSpotPrice(bidPrice)
                .withKeyName("primary");

        // enable detail monitoring
        InstanceMonitoring monitor = new InstanceMonitoring();
        monitor.setEnabled(true);
        launchConfigRequest.setInstanceMonitoring(monitor);

        // attach the configuration to the ASG client
        autoScalingGroupClient.createLaunchConfiguration(launchConfigRequest);

        System.out.println("Configuration complete!\nCreating auto-scaling group...");

        /**
         * =======================================================================
         * =================== Create auto-scaling group
         * =======================================================================
         * ===================
         */

        // configure ASG request
        CreateAutoScalingGroupRequest asgRequest = new CreateAutoScalingGroupRequest()
                .withAutoScalingGroupName(autoScalingGroupName).withAvailabilityZones("us-east-1b")
                .withLoadBalancerNames(loadBalancerName).withNewInstancesProtectedFromScaleIn(false)
                .withTags(asgTag).withDefaultCooldown(120).withMinSize(1).withMaxSize(8).withDesiredCapacity(1) // Start
                // from
                // one
                .withHealthCheckGracePeriod(120).withHealthCheckType("ELB")
                .withLaunchConfigurationName(launchConfigName);

        // attach group configuration to ASG client
        autoScalingGroupClient.createAutoScalingGroup(asgRequest);

        /**
         * =======================================================================
         * =================== Create scaling up policy for ASG
         * =======================================================================
         * ===================
         */

        StepAdjustment upRule1 = new StepAdjustment().withMetricIntervalLowerBound(0.0)
                .withMetricIntervalUpperBound(25.0).withScalingAdjustment(1);

        StepAdjustment upRule2 = new StepAdjustment().withMetricIntervalLowerBound(25.0)
                .withMetricIntervalUpperBound(30.0).withScalingAdjustment(2);

        StepAdjustment upRule3 = new StepAdjustment().withMetricIntervalLowerBound(30.0)
                .withMetricIntervalUpperBound(null).withScalingAdjustment(3);

        String upPolicyName = "Scaling Up";

        PutScalingPolicyRequest scalingUpPolicy = new PutScalingPolicyRequest()
                .withAdjustmentType("ChangeInCapacity").withPolicyType("StepScaling")
                .withStepAdjustments(upRule1, upRule2, upRule3).withAutoScalingGroupName(autoScalingGroupName)
                .withPolicyName(upPolicyName).withEstimatedInstanceWarmup(120);

        StepAdjustment downRule1 = new StepAdjustment().withMetricIntervalLowerBound(-20.0)
                .withMetricIntervalUpperBound(-0.0).withScalingAdjustment(-1);

        StepAdjustment downRule2 = new StepAdjustment().withMetricIntervalLowerBound(-30.0)
                .withMetricIntervalUpperBound(-20.0).withScalingAdjustment(-2);

        StepAdjustment downRule3 = new StepAdjustment().withMetricIntervalLowerBound(null)
                .withMetricIntervalUpperBound(-30.0).withScalingAdjustment(-3);

        String downPolicyName = "Scaling Down";

        PutScalingPolicyRequest scalingDownPolicy = new PutScalingPolicyRequest().withAdjustmentType("")
                .withPolicyType("ChangeInCapacity").withStepAdjustments(downRule1, downRule2, downRule3)
                .withAutoScalingGroupName(autoScalingGroupName).withPolicyName(downPolicyName)
                .withEstimatedInstanceWarmup(60);

        // attach policies to ASG and get ARN for setting alarm
        PutScalingPolicyResult scaleUpResult = autoScalingGroupClient.putScalingPolicy(scalingUpPolicy);
        String upArn = scaleUpResult.getPolicyARN();
        PutScalingPolicyResult scaleDownResult = autoScalingGroupClient.putScalingPolicy(scalingDownPolicy);
        String downArn = scaleDownResult.getPolicyARN();

        /**
         * =======================================================================
         * =================== Create alarms for policies
         * =======================================================================
         * ===================
         */

        String upAlarmName = "UpAlarm_Mild";
        String downAlarmName = "DownAlarm_Mild";
        Dimension dimension = new Dimension();
        dimension.setName("AutoScalingGroupName");
        dimension.setValue(autoScalingGroupName);

        PutMetricAlarmRequest upAlarmRequest = new PutMetricAlarmRequest().withAlarmName(upAlarmName)
                .withMetricName("CPUUtilization").withNamespace("AWS/EC2").withDimensions(dimension)
                .withStatistic(Statistic.SampleCount)
                .withComparisonOperator(ComparisonOperator.GreaterThanOrEqualToThreshold).withThreshold(65.0)
                .withEvaluationPeriods(1).withPeriod(120).withAlarmActions(upArn);

        PutMetricAlarmRequest downAlarmRequest = new PutMetricAlarmRequest().withAlarmName(downAlarmName)
                .withNamespace("AWS/EC2").withDimensions(dimension).withMetricName("CPUUtilization")
                .withStatistic(Statistic.Average)
                .withComparisonOperator(ComparisonOperator.LessThanOrEqualToThreshold).withThreshold(60.0)
                .withEvaluationPeriods(1).withPeriod(120).withAlarmActions(downArn);

        cloudWatchClient.putMetricAlarm(upAlarmRequest);
        cloudWatchClient.putMetricAlarm(downAlarmRequest);

        System.out.println("All settings complete! \nReady for warmup...");

        /**
         * =======================================================================
         * =================== Warm up ELB
         * =======================================================================
         * ===================
         */

        String warmUpUrl = "http://" + loadGeneratorDns + "/warmup?dns=" + loadBalancerDns;
        sendGET(warmUpUrl);
        System.out.println("Warmup link: " + warmUpUrl);

        try {
            Thread.sleep(15 * 60 * 1000);
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("Warmup complete!\nReady for battle...");

        /**
         * =======================================================================
         * =================== Start the test
         * =======================================================================
         * ===================
         */

        String testUrl = "http://" + loadGeneratorDns + "/junior?dns=" + loadBalancerDns;
        testId = sendGET(testUrl);
        System.out.println("Test ID is: " + testId);

        System.out.println("Test link: " + testUrl);

        try {
            Thread.sleep(60 * 60 * 1000);
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("Test finished!");

        /**
         * =======================================================================
         * =================== Delete resources
         * =======================================================================
         * ===================
         */

        // clear ASG
        UpdateAutoScalingGroupRequest asgClearRequest = new UpdateAutoScalingGroupRequest()
                .withAutoScalingGroupName(autoScalingGroupName).withMaxSize(0).withMinSize(0);
        autoScalingGroupClient.updateAutoScalingGroup(asgClearRequest);

        // delete policies
        DeletePolicyRequest upPolicyDeleteRequest = new DeletePolicyRequest()
                .withAutoScalingGroupName(autoScalingGroupName).withPolicyName(upPolicyName);
        autoScalingGroupClient.deletePolicy(upPolicyDeleteRequest);

        DeletePolicyRequest downPolicyDeleteRequest = new DeletePolicyRequest()
                .withAutoScalingGroupName(autoScalingGroupName).withPolicyName(downPolicyName);
        autoScalingGroupClient.deletePolicy(downPolicyDeleteRequest);
        System.out.println("Policies deleted...");

        // delete alarms
        DeleteAlarmsRequest alarmsDeleteRequest = new DeleteAlarmsRequest().withAlarmNames(upAlarmName,
                downAlarmName);
        cloudWatchClient.deleteAlarms(alarmsDeleteRequest);
        System.out.println("Alarms deleted...");

        // delete load balancer
        DeleteLoadBalancerRequest lgDeleteRequest = new DeleteLoadBalancerRequest()
                .withLoadBalancerName(loadBalancerName);
        loadBalancerClient.deleteLoadBalancer(lgDeleteRequest);
        System.out.println("Load generator deleted...");

        // delete ASG
        DeleteAutoScalingGroupRequest asgDeleteRequest = new DeleteAutoScalingGroupRequest()
                .withForceDelete(true).withAutoScalingGroupName(autoScalingGroupName);
        autoScalingGroupClient.deleteAutoScalingGroup(asgDeleteRequest);
        System.out.println("ASG deleted...");

        // delete launch configuration
        DeleteLaunchConfigurationRequest launchConfigDeleteRequest = new DeleteLaunchConfigurationRequest()
                .withLaunchConfigurationName(launchConfigName);
        autoScalingGroupClient.deleteLaunchConfiguration(launchConfigDeleteRequest);
        System.out.println("Launch configuration deleted...");

        // delete security group
        DeleteSecurityGroupRequest sgDeleteRequest = new DeleteSecurityGroupRequest()
                .withGroupName(allPurposeSecurityName);
        ec2.deleteSecurityGroup(sgDeleteRequest);
        System.out.println("Security group deleted...");

        /**
         * =======================================================================
         * =================== All done
         * =======================================================================
         * ===================
         */
        System.out.println("All done :)");

    } catch (AmazonServiceException ase) {
        // Write out any exceptions that may have occurred.
        System.out.println("Caught Exception: " + ase.getMessage());
        System.out.println("Reponse Status Code: " + ase.getStatusCode());
        System.out.println("Error Code: " + ase.getErrorCode());
        System.out.println("Request ID: " + ase.getRequestId());

    } catch (Exception e) {
        System.out.println("Unexcepted error!");
        System.out.println(e.getMessage());
    }

}

From source file:SecurityGroup.java

License:Open Source License

public void create(String groupName) {

    AWSCredentials credentials = null;//from ww w . ja v  a 2  s . co  m
    try {
        credentials = new ProfileCredentialsProvider("School").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 (C:\\Users\\Jiabei\\.aws\\credentials), and is in valid format.", e);
    }

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

    // Create a new security group.
    try {

        CreateSecurityGroupRequest securityGroupRequest = new CreateSecurityGroupRequest(groupName,
                "Security created for P2");
        CreateSecurityGroupResult result = ec2.createSecurityGroup(securityGroupRequest);

        System.out.println(String.format("Security group created: [%s]", result.getGroupId()));

        groupId = result.getGroupId();

    } catch (AmazonServiceException ase) {
        // Likely this means that the group is already created, so ignore.
        System.out.println(ase.getMessage());
    }

    // Create a range that you would like to populate.
    List<String> ipRanges = Collections.singletonList("0.0.0.0/0");

    // Open all port
    IpPermission ipPermission = new IpPermission().withIpProtocol("-1").withFromPort(new Integer(0))
            .withToPort(new Integer(65535)).withIpRanges(ipRanges);

    List<IpPermission> ipPermissions = Collections.singletonList(ipPermission);

    try {
        // Authorize the ports to the used.
        AuthorizeSecurityGroupIngressRequest ingressRequest = new AuthorizeSecurityGroupIngressRequest(
                groupName, ipPermissions);
        ec2.authorizeSecurityGroupIngress(ingressRequest);

        System.out.println(String.format("Ingress port authroized: [%s]", ipPermissions.toString()));
    } catch (AmazonServiceException ase) {
        // Ignore because this likely means the zone has already been authorized.
        System.out.println(ase.getMessage());
    }

}

From source file:InlineGettingStartedCodeSampleApp.java

License:Open Source License

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

    /*//from w  w  w .j ava  2 s  . c  o m
     * The ProfileCredentialsProvider will return your [default]
     * credential profile by reading from the credentials file located at
     * (/Users/zunzunwang/.aws/credentials).
     */
    AWSCredentials credentials = null;
    try {
        credentials = new ProfileCredentialsProvider("default").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/zunzunwang/.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());
    }

    //============================================================================================//
    //=========================== 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);

    //============================================================================================//
    //====================================== 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:CreateSecurityGroupApp.java

License:Open Source License

public static void main(String[] args) {

    /*// w w w .j a v  a  2s  . c  o m
     * The ProfileCredentialsProvider will return your [New Profile]
     * credential profile by reading from the credentials file located at
     * (C:\\Users\\Accolite\\.aws\\credentials).
     */
    AWSCredentials credentials = null;
    try {
        credentials = new ProfileCredentialsProvider("New Profile").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 (C:\\Users\\Accolite\\.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);

    // Create a new security group.
    try {
        CreateSecurityGroupRequest securityGroupRequest = new CreateSecurityGroupRequest("Muneer_SG",
                "My Security Group");
        CreateSecurityGroupResult result = ec2.createSecurityGroup(securityGroupRequest);
        System.out.println(String.format("Security group created: [%s]", result.getGroupId()));
    } catch (AmazonServiceException ase) {
        // Likely this means that the group is already created, so ignore.
        System.out.println(ase.getMessage());
    }

    String ipAddr = "0.0.0.0/0";

    // Get the IP of the current host, so that we can limit the Security Group
    // by default to the ip range associated with your subnet.
    try {
        InetAddress addr = InetAddress.getLocalHost();

        // Get IP Address
        ipAddr = addr.getHostAddress() + "/10";
    } catch (UnknownHostException e) {
    }

    // Create a range that you would like to populate.
    List<String> ipRanges = Collections.singletonList(ipAddr);

    // Open up port 23 for TCP traffic to the associated IP from above (e.g. ssh traffic).
    IpPermission ipPermission = new IpPermission().withIpProtocol("tcp").withFromPort(new Integer(22))
            .withToPort(new Integer(22)).withIpRanges(ipRanges);

    List<IpPermission> ipPermissions = Collections.singletonList(ipPermission);

    try {
        // Authorize the ports to the used.
        AuthorizeSecurityGroupIngressRequest ingressRequest = new AuthorizeSecurityGroupIngressRequest(
                "GettingStartedGroup", ipPermissions);
        ec2.authorizeSecurityGroupIngress(ingressRequest);
        System.out.println(String.format("Ingress port authroized: [%s]", ipPermissions.toString()));
    } catch (AmazonServiceException ase) {
        // Ignore because this likely means the zone has already been authorized.
        System.out.println(ase.getMessage());
    }
}

From source file:InlineGettingStartedCodeApp.java

License:Open Source License

/**
 * @param args//from   w ww.java  2s  .  c  o  m
 */
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 usEast1 = Region.getRegion(Regions.US_EAST_1);
    ec2.setRegion(usEast1);

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

    //*************************** Required Parameters Settings ************************//
    // 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);

    //*************************** Bid Type Settings ************************//
    // Set the type of the bid to persistent.
    requestRequest.setType("persistent");

    //*************************** Valid From/To Settings ************************//
    // Set the valid start time to be two minutes from now.
    Calendar from = Calendar.getInstance();
    from.add(Calendar.MINUTE, 2);
    requestRequest.setValidFrom(from.getTime());

    // Set the valid end time to be two minutes and two hours from now.
    Calendar until = (Calendar) from.clone();
    until.add(Calendar.HOUR, 2);
    requestRequest.setValidUntil(until.getTime());

    //*************************** Launch Group Settings ************************//
    // Set the launch group.
    requestRequest.setLaunchGroup("ADVANCED-DEMO-LAUNCH-GROUP");

    //*************************** Availability Zone Group Settings ************************//
    // Set the availability zone group.
    requestRequest.setAvailabilityZoneGroup("ADVANCED-DEMO-AZ-GROUP");

    //*************************** Add the block device mapping ************************//

    // Goal: Setup block device mappings to ensure that we will not delete
    // the root partition on termination.

    // Create the block device mapping to describe the root partition.
    BlockDeviceMapping blockDeviceMapping = new BlockDeviceMapping();
    blockDeviceMapping.setDeviceName("/dev/sda1");

    // Set the delete on termination flag to false.
    EbsBlockDevice ebs = new EbsBlockDevice();
    ebs.setDeleteOnTermination(Boolean.FALSE);
    blockDeviceMapping.setEbs(ebs);

    // Add the block device mapping to the block list.
    ArrayList<BlockDeviceMapping> blockList = new ArrayList<BlockDeviceMapping>();
    blockList.add(blockDeviceMapping);

    // Set the block device mapping configuration in the launch specifications.
    launchSpecification.setBlockDeviceMappings(blockList);

    //*************************** Add the availability zone ************************//
    // Setup the availability zone to use. Note we could retrieve the availability
    // zones using the ec2.describeAvailabilityZones() API. For this demo we will just use
    // us-east-1b.
    SpotPlacement placement = new SpotPlacement("us-east-1b");
    launchSpecification.setPlacement(placement);

    //*************************** Add the placement group ************************//
    // Setup the placement group to use with whatever name you desire.
    // For this demo we will just use "ADVANCED-DEMO-PLACEMENT-GROUP".
    // Note: We have commented this out, because we are not leveraging cc1.4xlarge or
    // cg1.4xlarge in this example.
    /*
    SpotPlacement pg = new SpotPlacement();
    pg.setGroupName("ADVANCED-DEMO-PLACEMENT-GROUP");
    launchSpecification.setPlacement(pg);
    */

    //*************************** Add the launch specification ************************//
    // Add the launch specification.
    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());
    }

    //============================================================================================//
    //=========================== 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);

    //============================================================================================//
    //====================================== 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:InlineTaggingCodeApp.java

License:Open Source License

/**
 * @param args//from www.ja v  a 2 s  .c o m
 */
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 a2  s.co  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:InstallYarn.java

License:Open Source License

public static void main(String[] args) throws JSchException, IOException, InterruptedException {

    /*//w w  w.j a  v a 2s.  co  m
     * The ProfileCredentialsProvider will return your [default]
     * credential profile by reading from the credentials file located at
     * (C:\\Users\\CH\\.aws\\credentials).
     */

    AWSCredentials credentials = null;
    try {
        credentials = new BasicAWSCredentials("Your Access Key ID", "Your Secret Access Key");

    } 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 (C:\\Users\\CH\\.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);

    /*
    // Create a new security group.
    try {
    CreateSecurityGroupRequest securityGroupRequest = new CreateSecurityGroupRequest(
            "GettingStartedGroup", "Getting Started Security Group");
    CreateSecurityGroupResult result = ec2
            .createSecurityGroup(securityGroupRequest);
    System.out.println(String.format("Security group created: [%s]",
            result.getGroupId()));
    } catch (AmazonServiceException ase) {
    // Likely this means that the group is already created, so ignore.
    System.out.println(ase.getMessage());
    }
            
    String ipAddr = "0.0.0.0/0";
            
    // Get the IP of the current host, so that we can limit the Security Group
    // by default to the ip range associated with your subnet.
    try {
    InetAddress addr = InetAddress.getLocalHost();
            
    // Get IP Address
    ipAddr = addr.getHostAddress()+"/10";
    } catch (UnknownHostException e) {
    }
            
    // Create a range that you would like to populate.
    List<String> ipRanges = Collections.singletonList(ipAddr);
            
    // Open up port 23 for TCP traffic to the associated IP from above (e.g. ssh traffic).
    IpPermission ipPermission = new IpPermission()
        .withIpProtocol("tcp")
        .withFromPort(new Integer(22))
        .withToPort(new Integer(22))
        .withIpRanges(ipRanges);
            
    List<IpPermission> ipPermissions = Collections.singletonList(ipPermission);
            
    try {
    // Authorize the ports to the used.
    AuthorizeSecurityGroupIngressRequest ingressRequest = new AuthorizeSecurityGroupIngressRequest(
            "GettingStartedGroup", ipPermissions);
    ec2.authorizeSecurityGroupIngress(ingressRequest);
    System.out.println(String.format("Ingress port authroized: [%s]",
            ipPermissions.toString()));
    } catch (AmazonServiceException ase) {
    // Ignore because this likely means the zone has already been authorized.
    System.out.println(ase.getMessage());
    }
    */
    //CreateKeyPairRequest createKeyPairRequest = new CreateKeyPairRequest()
    //.withKeyName("CHENHAO");

    //CreateKeyPairResult createKeyPairResult = ec2.createKeyPair(createKeyPairRequest);

    //KeyPair keyPair = new KeyPair();
    //keyPair = createKeyPairResult.getKeyPair();
    //String privateKey = keyPair.getKeyMaterial();

    int cluster_size = Integer
            .parseInt(JOptionPane.showInputDialog("Enter number of machines you want to set"));
    String ami_name = JOptionPane.showInputDialog("Enter your ami name");
    String key_name = JOptionPane.showInputDialog("Enter your key name");
    String s_group_name = JOptionPane.showInputDialog("Enter your security group name");

    RunInstancesRequest runInstancesRequest = new RunInstancesRequest();
    runInstancesRequest.withImageId(ami_name).withInstanceType("t2.micro").withMinCount(cluster_size)
            .withMaxCount(cluster_size).withKeyName(key_name).withSecurityGroups(s_group_name);

    RunInstancesResult runInstancesResult = ec2.runInstances(runInstancesRequest);

    Thread.sleep(10000);

    Vector<String> instanceId = new Vector<String>();
    for (Instance ins : runInstancesResult.getReservation().getInstances())
        instanceId.add(ins.getInstanceId());

    DescribeInstancesRequest request = new DescribeInstancesRequest();
    request.setInstanceIds(instanceId);
    DescribeInstancesResult result = ec2.describeInstances(request);
    List<Reservation> reservations = result.getReservations();

    List<Instance> instances_list = new Vector<Instance>();
    for (int i = 0; i < reservations.size(); i++)
        instances_list.addAll(reservations.get(i).getInstances());

    System.out.println("Plan cluster size:" + cluster_size + " Real size:" + instances_list.size());

    JSch jsch = new JSch();
    JFileChooser chooser = new JFileChooser();
    chooser.setDialogTitle("Choose your privatekey");
    chooser.setFileHidingEnabled(false);
    int returnVal = chooser.showOpenDialog(null);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        System.out.println("You chose " + chooser.getSelectedFile().getAbsolutePath() + ".");
        jsch.addIdentity(chooser.getSelectedFile().getAbsolutePath());
    }

    Session session;
    UserInfo ui = new MyUserInfo();
    for (int i = 0; i < instances_list.size(); i++) {
        if (instances_list.get(i).getPublicIpAddress() == null)
            System.out.println("Error, public ip is null\n");

        System.out.println("Connect to:" + instances_list.get(i).getPublicIpAddress() + "\n");
        session = jsch.getSession("ubuntu", instances_list.get(i).getPublicIpAddress(), 22);
        session.setUserInfo(ui);
        session.connect();

        //
        //if(i==0)
        //{
        //  transfer_file_to("/home/ubuntu","C:/Users/CH/Downloads/ch.pem",session);
        // exec("chmod 400 /home/ubuntu/ch.pem",session);
        //}

        //slaves file
        for (int j = 0; j < instances_list.size(); j++) {
            if (j != 0)
                exec("echo " + instances_list.get(j).getPrivateIpAddress()
                        + "\n >> /usr/local/hadoop/etc/hadoop/slaves", session);
        }
        //core-site file
        String command = "sed -i 's#Master#" + instances_list.get(0).getPrivateIpAddress()
                + "#g' /usr/local/hadoop/etc/hadoop/core-site.xml";
        exec(command, session);

        //hdfs-size file
        command = "sed -i 's#Master#" + instances_list.get(0).getPrivateIpAddress()
                + "#g' /usr/local/hadoop/etc/hadoop/core-site.xml";
        exec(command, session);

        command = "sed -i 's#replication#" + Integer.toString(cluster_size - 1)
                + "#g' /usr/local/hadoop/etc/hadoop/core-site.xml";
        exec(command, session);

        //yarn-size file
        command = "sed -i 's#Master#" + instances_list.get(0).getPrivateIpAddress()
                + "#g' /usr/local/hadoop/etc/hadoop/core-site.xml";
        exec(command, session);

        session.disconnect();
    }

    //username and passphrase will be given via UserInfo interface.

    //slaves file

}

From source file:com.brighttag.agathon.security.ec2.Ec2SecurityGroupService.java

License:Apache License

private AmazonEC2 client(String dataCenter) {
    AmazonEC2 client = amazonEC2Provider.get();
    client.setRegion(regions.get(dataCenter));
    return client;
}

From source file:com.epam.dlab.automation.cloud.aws.AmazonHelper.java

License:Apache License

private static List<Instance> getInstances(String instanceName) {
    AWSCredentials credentials = getCredentials();
    AmazonEC2 ec2 = new AmazonEC2Client(credentials);
    ec2.setRegion(getRegion());

    List<String> valuesT1 = new ArrayList<>();
    valuesT1.add(instanceName + "*");
    Filter filter = new Filter("tag:" + NamingHelper.getServiceBaseName() + "-Tag", valuesT1);

    DescribeInstancesRequest describeInstanceRequest = new DescribeInstancesRequest().withFilters(filter);
    DescribeInstancesResult describeInstanceResult = ec2.describeInstances(describeInstanceRequest);

    List<Reservation> reservations = describeInstanceResult.getReservations();

    if (reservations.isEmpty()) {
        throw new CloudException("Instance " + instanceName + " in Amazon not found");
    }/* ww  w . ja va  2s  .c om*/

    List<Instance> instances = reservations.get(0).getInstances();
    if (instances.isEmpty()) {
        throw new CloudException("Instance " + instanceName + " in Amazon not found");
    }

    return instances;
}