List of usage examples for com.amazonaws.services.ec2.model SecurityGroup getGroupId
public String getGroupId()
The ID of the security group.
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 2s . 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:aws.example.ec2.DescribeSecurityGroups.java
License:Open Source License
public static void main(String[] args) { final String USAGE = "To run this example, supply a group id\n" + "Ex: DescribeSecurityGroups <group-id>\n"; if (args.length != 1) { System.out.println(USAGE); System.exit(1);/*from w w w .ja v a 2s . c om*/ } String group_id = args[0]; final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient(); DescribeSecurityGroupsRequest request = new DescribeSecurityGroupsRequest().withGroupIds(group_id); DescribeSecurityGroupsResult response = ec2.describeSecurityGroups(request); for (SecurityGroup group : response.getSecurityGroups()) { System.out.printf("Found security group with id %s, " + "vpc id %s " + "and description %s", group.getGroupId(), group.getVpcId(), group.getDescription()); } }
From source file:com.jaspersoft.jasperserver.api.engine.jasperreports.util.AwsDataSourceRecovery.java
License:Open Source License
private String recoverVpcSecurityGroup(AwsReportDataSource awsReportDataSource, String vpcId, String ingressPublicIp) { AWSCredentials awsCredentials = AwsCredentialUtil.getAWSCredentials(awsReportDataSource.getAWSAccessKey(), awsReportDataSource.getAWSSecretKey(), awsReportDataSource.getRoleARN()); //Security/* w ww . ja v a 2s. c o m*/ AmazonEC2Client amazonEc2Client = new AmazonEC2Client(awsCredentials); SecurityGroup vpcSecurityGroup = null; try { DescribeSecurityGroupsResult describeSecurityGroupsResult = amazonEc2Client.describeSecurityGroups(); if (describeSecurityGroupsResult != null && describeSecurityGroupsResult.getSecurityGroups() != null && describeSecurityGroupsResult.getSecurityGroups().size() > 0) { for (SecurityGroup securityGroup : describeSecurityGroupsResult.getSecurityGroups()) { if (securityGroup.getVpcId() != null && securityGroup.getVpcId().equals(vpcId) && securityGroup.getGroupName().equals(awsProperties.getSecurityGroupName())) { vpcSecurityGroup = securityGroup; break; } } } } catch (Exception ex) { //Have to be empty. } boolean ingressIpMaskExist = false; String vpcSecurityGroupId; if (vpcSecurityGroup != null) { vpcSecurityGroupId = vpcSecurityGroup.getGroupId(); List<IpPermission> ipPermissions = vpcSecurityGroup.getIpPermissions(); if (ipPermissions != null && ipPermissions.size() > 0) { for (IpPermission ipPermission : ipPermissions) { if (ipPermission.getIpRanges() != null && ipPermission.getIpRanges().size() > 0 && ipPermission.getIpRanges().contains(ingressPublicIp)) { ingressIpMaskExist = true; } } } if (!ingressIpMaskExist && ipPermissions != null && ipPermissions.size() > 0) { RevokeSecurityGroupIngressRequest revokeSecurityGroupIngressRequest = new RevokeSecurityGroupIngressRequest() .withGroupId(vpcSecurityGroup.getGroupId()).withIpPermissions() .withIpPermissions(vpcSecurityGroup.getIpPermissions()); amazonEc2Client.revokeSecurityGroupIngress(revokeSecurityGroupIngressRequest); } } else { vpcSecurityGroupId = amazonEc2Client .createSecurityGroup( new CreateSecurityGroupRequest().withGroupName(awsProperties.getSecurityGroupName()) .withVpcId(vpcId).withDescription(awsProperties.getSecurityGroupDescription())) .getGroupId(); } if (!ingressIpMaskExist) { IpPermission ipPermission = new IpPermission().withIpProtocol("tcp").withIpRanges(ingressPublicIp) .withFromPort(0).withToPort(65535); List<IpPermission> ipPermissions = new ArrayList<IpPermission>(); ipPermissions.add(ipPermission); AuthorizeSecurityGroupIngressRequest authorizeRequest = new AuthorizeSecurityGroupIngressRequest() .withIpPermissions(ipPermissions).withGroupId(vpcSecurityGroupId); amazonEc2Client.authorizeSecurityGroupIngress(authorizeRequest); } return vpcSecurityGroupId; }
From source file:com.netflix.dynomitemanager.sidecore.aws.AWSMembership.java
License:Apache License
protected String getVpcGroupId() { AmazonEC2 client = null;/*from w w w .jav a2 s .c o m*/ try { client = getEc2Client(); Filter nameFilter = new Filter().withName("group-name").withValues(config.getACLGroupName()); //SG Filter vpcFilter = new Filter().withName("vpc-id").withValues(config.getVpcId()); DescribeSecurityGroupsRequest req = new DescribeSecurityGroupsRequest().withFilters(nameFilter, vpcFilter); DescribeSecurityGroupsResult result = client.describeSecurityGroups(req); for (SecurityGroup group : result.getSecurityGroups()) { logger.debug(String.format("got group-id:%s for group-name:%s,vpc-id:%s", group.getGroupId(), config.getACLGroupName(), config.getVpcId())); return group.getGroupId(); } logger.error(String.format("unable to get group-id for group-name=%s vpc-id=%s", config.getACLGroupName(), config.getVpcId())); return ""; } finally { if (client != null) client.shutdown(); } }
From source file:com.netflix.edda.EddaEc2Client.java
License:Apache License
public DescribeSecurityGroupsResult describeSecurityGroups(DescribeSecurityGroupsRequest request) { validateEmpty("Filter", request.getFilters()); TypeReference<List<SecurityGroup>> ref = new TypeReference<List<SecurityGroup>>() { };//from w w w . ja v a 2 s . c o m String url = config.url() + "/api/v2/aws/securityGroups;_expand"; try { List<SecurityGroup> securityGroups = parse(ref, doGet(url)); List<String> names = request.getGroupNames(); List<String> ids = request.getGroupIds(); if (shouldFilter(names) || shouldFilter(ids)) { List<SecurityGroup> sgs = new ArrayList<SecurityGroup>(); for (SecurityGroup sg : securityGroups) { if (matches(names, sg.getGroupName()) && matches(ids, sg.getGroupId())) sgs.add(sg); } securityGroups = sgs; } return new DescribeSecurityGroupsResult().withSecurityGroups(securityGroups); } catch (IOException e) { throw new AmazonClientException("Faled to parse " + url, e); } }
From source file:com.netflix.simianarmy.chaos.BlockAllNetworkTrafficChaosType.java
License:Apache License
/** * Takes the instance off the network.// www . j av a 2s.c om */ @Override public void apply(ChaosInstance instance) { String vpcId = getVpcId(instance); if (vpcId == null) { throw new IllegalStateException("canApply should have returned false"); } AWSClient awsClient = (AWSClient) instance.getCloudClient(); SecurityGroup found = null; List<SecurityGroup> securityGroups = awsClient.describeSecurityGroups(blockedSecurityGroupName); for (SecurityGroup sg : securityGroups) { if (Objects.equal(vpcId, sg.getVpcId())) { if (found != null) { throw new IllegalStateException("Duplicate security groups found"); } found = sg; } } String groupId; if (found == null) { LOGGER.info("Auto-creating security group {}", blockedSecurityGroupName); String description = "Empty security group for blocked instances"; groupId = awsClient.createSecurityGroup(vpcId, blockedSecurityGroupName, description); } else { groupId = found.getGroupId(); } String instanceId = instance.getInstanceId(); LOGGER.info("Blocking network traffic by applying security group {} to instance {}", groupId, instanceId); List<String> groups = Lists.newArrayList(); groups.add(groupId); awsClient.setInstanceSecurityGroups(instanceId, groups); }
From source file:com.netflix.simianarmy.client.aws.AWSClient.java
License:Apache License
/** {@inheritDoc} */ @Override//from ww w. j a v a 2 s.c o m public String findSecurityGroup(String instanceId, String groupName) { String vpcId = getVpcId(instanceId); SecurityGroup found = null; List<SecurityGroup> securityGroups = describeSecurityGroups(vpcId, groupName); for (SecurityGroup sg : securityGroups) { if (Objects.equal(vpcId, sg.getVpcId())) { if (found != null) { throw new IllegalStateException("Duplicate security groups found"); } found = sg; } } if (found == null) { return null; } return found.getGroupId(); }
From source file:com.netflix.spinnaker.clouddriver.aws.deploy.handlers.MigrateLoadBalancerStrategy.java
License:Apache License
/** * Creates the app specific security group, or returns the ID of one if it already exists * * @param appGroups list of existing security groups in which to look for existing app security group * @param elbGroup the elb specific security group, which will allow ingress permission from the * app specific security group */// w w w . java 2s. co m protected void buildApplicationSecurityGroup(LoadBalancerDescription sourceDescription, List<SecurityGroup> appGroups, MigrateSecurityGroupResult elbGroup) { if (getDeployDefaults().getAddAppGroupToServerGroup()) { AmazonEC2 targetAmazonEC2 = getAmazonClientProvider().getAmazonEC2(target.getCredentials(), target.getRegion(), true); Optional<SecurityGroup> existing = appGroups.stream().filter(isAppSecurityGroup()).findFirst(); MigrateSecurityGroupReference appGroupReference = new MigrateSecurityGroupReference(); appGroupReference.setAccountId(target.getCredentials().getAccountId()); appGroupReference.setVpcId(target.getVpcId()); appGroupReference.setTargetName(applicationName); if (existing.isPresent()) { elbGroup.getReused().add(appGroupReference); } else { elbGroup.getCreated().add(appGroupReference); if (!dryRun) { UpsertSecurityGroupDescription upsertDescription = new UpsertSecurityGroupDescription(); upsertDescription.setDescription("Application security group for " + applicationName); upsertDescription.setName(applicationName); upsertDescription.setVpcId(target.getVpcId()); upsertDescription.setRegion(target.getRegion()); upsertDescription.setCredentials(target.getCredentials()); getTask().updateStatus(LoadBalancerMigrator.BASE_PHASE, "Creating security group " + upsertDescription.getName() + " in " + target.getCredentialAccount() + "/" + target.getRegion() + "/" + target.getVpcId()); String newGroupId = targetLookup.createSecurityGroup(upsertDescription).getSecurityGroup() .getGroupId(); // After the create request completes, there is a brief period where the security group might not be // available and subsequent operations on it will fail, so make sure it's there OperationPoller.retryWithBackoff(o -> appGroups.addAll(targetAmazonEC2 .describeSecurityGroups(new DescribeSecurityGroupsRequest().withGroupIds(newGroupId)) .getSecurityGroups()), 200, 5); } } if (!dryRun) { String elbGroupId = elbGroup.getTarget().getTargetId(); SecurityGroup appGroup = appGroups.stream().filter(isAppSecurityGroup()).findFirst().get(); if (allowIngressFromClassic) { addClassicLinkIngress(targetLookup, getDeployDefaults().getClassicLinkSecurityGroupName(), appGroup.getGroupId(), target.getCredentials(), target.getVpcId()); } boolean hasElbIngressPermission = appGroup.getIpPermissions().stream().anyMatch( p -> p.getUserIdGroupPairs().stream().anyMatch(u -> u.getGroupId().equals(elbGroupId))); if (!hasElbIngressPermission) { sourceDescription.getListenerDescriptions().forEach(l -> { Listener listener = l.getListener(); IpPermission newPermission = new IpPermission().withIpProtocol("tcp") .withFromPort(listener.getInstancePort()).withToPort(listener.getInstancePort()) .withUserIdGroupPairs( new UserIdGroupPair().withGroupId(elbGroupId).withVpcId(target.getVpcId())); targetAmazonEC2.authorizeSecurityGroupIngress(new AuthorizeSecurityGroupIngressRequest() .withGroupId(appGroup.getGroupId()).withIpPermissions(newPermission)); }); } } } }
From source file:com.netflix.spinnaker.clouddriver.aws.deploy.handlers.MigrateSecurityGroupStrategy.java
License:Apache License
private Set<MigrateSecurityGroupReference> getTargetReferences(SecurityGroupUpdater source) { SecurityGroup group = source.getSecurityGroup(); if (getInfrastructureApplications().contains(Names.parseName(group.getGroupName()).getApp())) { return new HashSet<>(); }/*from w w w. j a v a2 s . com*/ return group.getIpPermissions().stream().map(IpPermission::getUserIdGroupPairs).flatMap(List::stream) .filter(pair -> !pair.getGroupId().equals(group.getGroupId()) || !pair.getUserId().equals(group.getOwnerId())) .map(pair -> { NetflixAmazonCredentials account = sourceLookup.getCredentialsForId(pair.getUserId()); if (pair.getGroupName() == null) { if (account == null) { pair.setGroupName(pair.getGroupId()); } else { sourceLookup.getSecurityGroupById(account.getName(), pair.getGroupId(), pair.getVpcId()) .ifPresent(u -> pair.setGroupName(u.getSecurityGroup().getGroupName())); } } return new MigrateSecurityGroupReference(pair, account); }).collect(Collectors.toSet()); }
From source file:com.netflix.spinnaker.clouddriver.aws.deploy.ops.loadbalancer.IngressLoadBalancerBuilder.java
License:Apache License
public IngressLoadBalancerGroupResult ingressApplicationLoadBalancerGroup(String application, String region, String credentialAccount, NetflixAmazonCredentials credentials, String vpcId, Collection<Integer> ports, SecurityGroupLookupFactory securityGroupLookupFactory) throws FailedSecurityGroupIngressException { SecurityGroupLookupFactory.SecurityGroupLookup securityGroupLookup = securityGroupLookupFactory .getInstance(region);//from w w w . j av a2s . c om // 1. get app load balancer security group & app security group. create if doesn't exist SecurityGroupLookupFactory.SecurityGroupUpdater applicationLoadBalancerSecurityGroupUpdater = getOrCreateSecurityGroup( application + "-elb", region, "Application ELB Security Group for " + application, credentialAccount, credentials, vpcId, securityGroupLookup); SecurityGroupLookupFactory.SecurityGroupUpdater applicationSecurityGroupUpdater = getOrCreateSecurityGroup( application, region, "Application Security Group for " + application, credentialAccount, credentials, vpcId, securityGroupLookup); SecurityGroup source = applicationLoadBalancerSecurityGroupUpdater.getSecurityGroup(); SecurityGroup target = applicationSecurityGroupUpdater.getSecurityGroup(); List<IpPermission> currentPermissions = SecurityGroupIngressConverter.flattenPermissions(target); List<IpPermission> targetPermissions = ports.stream() .map(port -> newIpPermissionWithSourceAndPort(source.getGroupId(), port)) .collect(Collectors.toList()); filterOutExistingPermissions(targetPermissions, currentPermissions); if (!targetPermissions.isEmpty()) { try { applicationSecurityGroupUpdater.addIngress(targetPermissions); } catch (Exception e) { throw new FailedSecurityGroupIngressException(e); } } return new IngressLoadBalancerGroupResult(source.getGroupId(), source.getGroupName()); }