List of usage examples for com.amazonaws.services.ec2.model DeleteSecurityGroupRequest DeleteSecurityGroupRequest
public DeleteSecurityGroupRequest()
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 w w w . j a v a 2 s. com // 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:aws.example.ec2.DeleteSecurityGroup.java
License:Open Source License
public static void main(String[] args) { final String USAGE = "To run this example, supply a security group id\n" + "Ex: DeleteSecurityGroup <security-group-id>\n"; if (args.length != 1) { System.out.println(USAGE); System.exit(1);/*from w w w .j av a2 s . c om*/ } String group_id = args[0]; final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient(); DeleteSecurityGroupRequest request = new DeleteSecurityGroupRequest().withGroupId(group_id); DeleteSecurityGroupResult response = ec2.deleteSecurityGroup(request); System.out.printf("Successfully deleted security group with id %s", group_id); }
From source file:com.axemblr.provisionr.amazon.activities.DeleteSecurityGroup.java
License:Apache License
@Override public void execute(AmazonEC2 client, Pool pool, DelegateExecution execution) { final String groupName = SecurityGroups.formatNameFromBusinessKey(execution.getProcessBusinessKey()); try {// www. j ava 2 s .c o m LOG.info(">> Deleting Security Group {}", groupName); client.deleteSecurityGroup(new DeleteSecurityGroupRequest().withGroupName(groupName)); } catch (AmazonServiceException e) { if (e.getErrorCode().equals(ErrorCodes.SECURITY_GROUP_NOT_FOUND)) { LOG.info("<< Security Group {} not found. Ignoring this error.", groupName); } else { throw Throwables.propagate(e); } } }
From source file:com.lunabeat.dooper.HadoopCluster.java
License:Apache License
/** * * @return boolean success/* w ww . j a va 2 s . c om*/ */ public boolean removeSecurityGroups() { if (!groupsExist()) { return true; } if (_master != null || _slaves.size() > 0) { return false; } UserIdGroupPair slaveUserIdGroupPair = new UserIdGroupPair().withGroupName(_groupName) .withUserId(_config.get(ClusterConfig.ACCOUNT_ID_KEY)); UserIdGroupPair masterUserIdGroupPair = new UserIdGroupPair().withGroupName(_masterGroupName) .withUserId(_config.get(ClusterConfig.ACCOUNT_ID_KEY)); ArrayList<IpPermission> ipPerms = new ArrayList<IpPermission>(); ipPerms.add(new IpPermission().withToPort(22).withFromPort(22).withIpProtocol(TCP).withIpRanges(ALL_IPS)); ipPerms.add(new IpPermission().withUserIdGroupPairs(masterUserIdGroupPair).withIpProtocol(TCP) .withToPort(HI_PORT).withFromPort(LOW_PORT)); ipPerms.add(new IpPermission().withUserIdGroupPairs(masterUserIdGroupPair).withIpProtocol(UDP) .withToPort(HI_PORT).withFromPort(LOW_PORT)); ipPerms.add(new IpPermission().withUserIdGroupPairs(masterUserIdGroupPair).withIpProtocol(ICMP) .withToPort(-1).withFromPort(-1)); ipPerms.add(new IpPermission().withUserIdGroupPairs(slaveUserIdGroupPair).withIpProtocol(TCP) .withToPort(HI_PORT).withFromPort(LOW_PORT)); ipPerms.add(new IpPermission().withUserIdGroupPairs(slaveUserIdGroupPair).withIpProtocol(UDP) .withToPort(HI_PORT).withFromPort(LOW_PORT)); ipPerms.add(new IpPermission().withUserIdGroupPairs(slaveUserIdGroupPair).withIpProtocol(ICMP) .withToPort(-1).withFromPort(-1)); RevokeSecurityGroupIngressRequest srsgi = new RevokeSecurityGroupIngressRequest().withGroupName(_groupName) .withIpPermissions(ipPerms); _ec2.revokeSecurityGroupIngress(srsgi); RevokeSecurityGroupIngressRequest mrsgi = new RevokeSecurityGroupIngressRequest() .withGroupName(_masterGroupName).withIpPermissions(ipPerms); _ec2.revokeSecurityGroupIngress(mrsgi); _ec2.deleteSecurityGroup(new DeleteSecurityGroupRequest().withGroupName(_groupName)); _ec2.deleteSecurityGroup(new DeleteSecurityGroupRequest().withGroupName(_masterGroupName)); return true; }
From source file:com.urbancode.terraform.tasks.aws.helpers.AWSHelper.java
License:Apache License
/** * * @param groupId//from w w w .j ava 2 s .com * @param ec2Client */ public void deleteSecurityGroup(String groupId, AmazonEC2 ec2Client) { try { log.info("Deleting Securty Group (" + groupId + ")"); DeleteSecurityGroupRequest request = new DeleteSecurityGroupRequest().withGroupId(groupId); ec2Client.deleteSecurityGroup(request); } catch (AmazonServiceException e) { log.error("Failed to delete Security Group", e); if (!"InvalidGroup.NotFound".equals(e.getErrorCode())) { throw e; } } }
From source file:com.vmware.photon.controller.model.adapters.awsadapter.AWSFirewallService.java
License:Open Source License
public void deleteSecurityGroup(AmazonEC2AsyncClient client, String groupId) { DeleteSecurityGroupRequest req = new DeleteSecurityGroupRequest().withGroupId(groupId); client.deleteSecurityGroup(req);/* ww w . j a v a 2s . co m*/ }
From source file:com.zotoh.cloudapi.aws.SecurityGroup.java
License:Open Source License
@Override public void delete(String group) throws InternalException, CloudException { tstEStrArg("group-name", group); try {// ww w .j a va 2 s . com _svc.getCloud().getEC2().deleteSecurityGroup(new DeleteSecurityGroupRequest().withGroupName(group)); } catch (AmazonServiceException e) { if (!testSafeNonExistError(e, "InvalidGroup.NotFound")) { throw new CloudException(e); } } }
From source file:ec2.DeleteSecurityGroup.java
License:Open Source License
public static void main(String[] args) { final String USAGE = "To run this example, supply a security group id\n" + "Ex: DeleteSecurityGroup <security-group-id>\n"; if (args.length != 1) { System.out.println(USAGE); System.exit(1);// w w w. j av a2s .c om } String groupId = args[0]; final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient(); DeleteSecurityGroupRequest request = new DeleteSecurityGroupRequest().withGroupId(groupId); DeleteSecurityGroupResult response = ec2.deleteSecurityGroup(request); System.out.printf("Successfully deleted security group with id %s", groupId); }
From source file:jp.classmethod.aws.gradle.ec2.AmazonEC2DeleteSecurityGroupTask.java
License:Apache License
@TaskAction public void authorizeIngress() { // to enable conventionMappings feature String groupName = getGroupName(); String groupId = getGroupId(); AmazonEC2PluginExtension ext = getProject().getExtensions().getByType(AmazonEC2PluginExtension.class); AmazonEC2 ec2 = ext.getClient();/* w ww . j a v a2 s. c o m*/ if (groupName == null && groupId == null) { throw new GradleException("groupName nor groupId is not specified"); } try { ec2.deleteSecurityGroup(new DeleteSecurityGroupRequest().withGroupId(groupId).withGroupName(groupName)); } catch (AmazonServiceException e) { if (e.getErrorCode().equals("InvalidPermission.Duplicate")) { getLogger().warn(e.getMessage()); } else { throw e; } } }
From source file:n3phele.factory.ec2.VirtualServerResource.java
License:Open Source License
private boolean makeSecurityGroup(String groupName, String id, String secret, URI location, String to, String firstName, String lastName) { AmazonEC2Client client = null;/*from w ww . ja va2 s .co m*/ client = getEC2Client(id, secret, location); boolean found = true; boolean failed = false; try { client.createSecurityGroup(new CreateSecurityGroupRequest().withGroupName("n3phele-" + groupName) .withDescription("n3phele " + groupName + " security group")); String ownerId = null; DescribeSecurityGroupsResult newGroupResult = client.describeSecurityGroups(); for (SecurityGroup g : newGroupResult.getSecurityGroups()) { if (g.getGroupName().equals("n3phele-" + groupName)) { ownerId = g.getOwnerId(); } } if (ownerId == null) return false; log.info("found ownerId of " + ownerId); log.info("adding ssh ports"); try { client.authorizeSecurityGroupIngress( new AuthorizeSecurityGroupIngressRequest().withGroupName("n3phele-" + groupName) .withCidrIp("0.0.0.0/0").withIpProtocol("tcp").withFromPort(22).withToPort(22)); } catch (Exception e) { log.log(Level.SEVERE, "Create security group " + groupName, e); failed = true; } log.info("adding agent ports"); try { client.authorizeSecurityGroupIngress( new AuthorizeSecurityGroupIngressRequest().withGroupName("n3phele-" + groupName) .withCidrIp("0.0.0.0/0").withIpProtocol("tcp").withFromPort(8887).withToPort(8887)); } catch (Exception e) { log.log(Level.SEVERE, "Create security group " + groupName, e); failed = true; } if (!failed) { log.info("adding self access"); try { List<IpPermission> permissions = new ArrayList<IpPermission>(); UserIdGroupPair userIdGroupPairs = new UserIdGroupPair().withUserId(ownerId) .withGroupName("n3phele-" + groupName); permissions.add(new IpPermission().withIpProtocol("icmp").withFromPort(-1).withToPort(-1) .withUserIdGroupPairs(userIdGroupPairs)); permissions.add(new IpPermission().withIpProtocol("tcp").withFromPort(1).withToPort(65535) .withUserIdGroupPairs(userIdGroupPairs)); permissions.add(new IpPermission().withIpProtocol("udp").withFromPort(1).withToPort(65535) .withUserIdGroupPairs(userIdGroupPairs)); log.info("adding icmp/tcp/udp"); client.authorizeSecurityGroupIngress( new AuthorizeSecurityGroupIngressRequest("n3phele-" + groupName, permissions)); } catch (Exception e) { log.log(Level.WARNING, "Error adding self access to group " + groupName, e); } } if (failed) { client.deleteSecurityGroup(new DeleteSecurityGroupRequest().withGroupName("n3phele-" + groupName)); found = false; } else { sendSecurityGroupNotificationEmail("n3phele-" + groupName, to, firstName, lastName, location); } } catch (Exception e) { log.log(Level.SEVERE, "Create security group " + groupName, e); client.deleteSecurityGroup(new DeleteSecurityGroupRequest().withGroupName("n3phele-" + groupName)); found = false; } return found; }