public DeferredResult<DescribeSecurityGroupsResult> getSecurityGroups(List<String> secGroupIds, String vpcId, String nicName, String vmName) { DescribeSecurityGroupsRequest req = new DescribeSecurityGroupsRequest() .withFilters(new Filter(AWS_GROUP_ID_FILTER, secGroupIds)) .withFilters(new Filter(AWS_VPC_ID_FILTER, singletonList(vpcId))); String msg = "Getting AWS Security Groups by id [" + secGroupIds + "] for [" + nicName + "] NIC for [" + vmName + "] VM"; AWSDeferredResultAsyncHandler<DescribeSecurityGroupsRequest, DescribeSecurityGroupsResult> handler = new AWSDeferredResultAsyncHandler<>(this.service, msg); this.client.describeSecurityGroupsAsync(req, handler); return handler.toDeferredResult(); }
@Override protected DeferredResult<RemoteResourcesPage> getExternalResources( String nextPageLink) { this.service.logFine(() -> "Getting SecurityGroups from AWS"); DescribeSecurityGroupsRequest securityGroupsRequest = new DescribeSecurityGroupsRequest(); String msg = "Getting AWS Security Groups [" + this.request.original.resourceReference + "]"; AWSDeferredResultAsyncHandler<DescribeSecurityGroupsRequest, DescribeSecurityGroupsResult> asyncHandler = new AWSDeferredResultAsyncHandler<>(this.service, msg); this.amazonEC2Client.describeSecurityGroupsAsync(securityGroupsRequest, asyncHandler); return asyncHandler.toDeferredResult().thenCompose((securityGroupsResult) -> { RemoteResourcesPage page = new RemoteResourcesPage(); for (SecurityGroup securityGroup : securityGroupsResult.getSecurityGroups()) { page.resourcesPage.put(securityGroup.getGroupId(), securityGroup); } return DeferredResult.completed(page); }); }
/** * This method fetches all security groups in an aws account. * @return List<SecurityGroup> returns all security groups. * @throws AmazonClientException */ public List<SecurityGroup> getAllSecurityGroups() throws AmazonClientException { List<SecurityGroup> allSecurityGroups; try { DescribeSecurityGroupsResult describeSecurityGroupsResult = this.amazonEc2.describeSecurityGroups(); allSecurityGroups = describeSecurityGroupsResult.getSecurityGroups(); } catch(AmazonClientException e) { System.out.println("ERROR : fetching all security groups in the account."); throw e; } List<String> allSecurityGroupsNames = allSecurityGroups.stream().map(e -> e.getGroupName()).collect(Collectors.toList()); System.out.println("INFO : Security Groups Names : " + allSecurityGroupsNames); return allSecurityGroups; }
/** * Validates the actual security group permissions against the pre-defined network rules. * * @param client the EC2 client * @param configuration the configuration to be validated * @param accumulator the exception condition accumulator * @param localizationContext the localization context */ private void checkSecurityGroups(AmazonEC2Client client, Configured configuration, PluginExceptionConditionAccumulator accumulator, LocalizationContext localizationContext) { List<String> securityGroupIds = EC2InstanceTemplate.CSV_SPLITTER.splitToList( configuration.getConfigurationValue(SECURITY_GROUP_IDS, localizationContext)); List<SecurityGroup> securityGroups = Collections.emptyList(); try { DescribeSecurityGroupsResult result = client.describeSecurityGroups( new DescribeSecurityGroupsRequest().withGroupIds(securityGroupIds)); securityGroups = result.getSecurityGroups(); } catch (AmazonServiceException e) { if (!e.getErrorCode().startsWith(INVALID_SECURITY_GROUP)) { throw Throwables.propagate(e); } // Otherwise, the error should be caught in anther validation, // EC2InstanceTemplateConfigurationValidator.checkSecurityGroupIds() } for (Direction direction : Direction.values()) { checkRulesForSecurityGroups(securityGroups, direction, accumulator, localizationContext); } }
public static String getSecurityGroupId() { connect(); DescribeSecurityGroupsRequest req = new DescribeSecurityGroupsRequest(); ArrayList<String> groupNames = new ArrayList<String>(); groupNames.add(Configuration.SECURITY_GROUP_NAME); req.setGroupNames(groupNames); DescribeSecurityGroupsResult res = client.describeSecurityGroups(req); List<SecurityGroup> securityGroups = res.getSecurityGroups(); if (securityGroups == null || securityGroups.size() == 0) return null; return securityGroups.get(0).getGroupId(); }
@Override public Map<String, SecurityGroupCheckDetails> check(final Collection<String> groupIds, final String account, final Region region) { final DescribeSecurityGroupsRequest describeSecurityGroupsRequest = new DescribeSecurityGroupsRequest(); describeSecurityGroupsRequest.setGroupIds(groupIds); final AmazonEC2Client amazonEC2Client = clientProvider.getClient( AmazonEC2Client.class, account, region); final DescribeSecurityGroupsResult describeSecurityGroupsResult = amazonEC2Client.describeSecurityGroups( describeSecurityGroupsRequest); final ImmutableMap.Builder<String, SecurityGroupCheckDetails> result = ImmutableMap.builder(); for (final SecurityGroup securityGroup : describeSecurityGroupsResult.getSecurityGroups()) { final List<String> offendingRules = securityGroup.getIpPermissions().stream() .filter(isOffending) .map(Object::toString) .collect(toList()); if (!offendingRules.isEmpty()) { final SecurityGroupCheckDetails details = new SecurityGroupCheckDetails( securityGroup.getGroupName(), ImmutableList.copyOf(offendingRules)); result.put(securityGroup.getGroupId(), details); } } return result.build(); }
@SuppressWarnings("unchecked") @Before public void setUp() throws Exception { final ClientProvider mockClientProvider = mock(ClientProvider.class); final AmazonEC2Client mockEC2 = mock(AmazonEC2Client.class); mockPredicate = (Predicate<IpPermission>) mock(Predicate.class); when(mockClientProvider.getClient(any(), any(), any())).thenReturn(mockEC2); securityGroupsChecker = new SecurityGroupsCheckerImpl(mockClientProvider, mockPredicate); final DescribeSecurityGroupsResult securityGroups = new DescribeSecurityGroupsResult() .withSecurityGroups(new SecurityGroup() .withGroupId("sg-12345678") .withGroupName("my-sec-group") .withIpPermissions(new IpPermission() .withIpProtocol("tcp") .withIpv4Ranges(new IpRange().withCidrIp("0.0.0.0/0")) .withFromPort(0) .withToPort(65535) .withIpv6Ranges(new Ipv6Range().withCidrIpv6("::/0")) .withUserIdGroupPairs(new UserIdGroupPair() .withUserId("111222333444") .withGroupId("sg-11223344")))); when(mockEC2.describeSecurityGroups(any())).thenReturn(securityGroups); }
@Test public void testJsonException(){ final DescribeSecurityGroupsResult mockResult = spy(new DescribeSecurityGroupsResult()); when(clientProviderMock.getClient(any(), anyString(), any(Region.class))).thenReturn(amazonEC2ClientMock); when(mockResult.getSecurityGroups()).thenThrow(new IllegalStateException()); when(amazonEC2ClientMock.describeSecurityGroups(any(DescribeSecurityGroupsRequest.class))).thenReturn(mockResult); securityGroupProvider = new SecurityGroupProvider(clientProviderMock); final String securityGroup = securityGroupProvider.getSecurityGroup(Lists.newArrayList("sg.1234"), REGION, "9876"); Assertions.assertThat(securityGroup).isEqualTo(null); verify(clientProviderMock).getClient(any(), anyString(), any(Region.class)); verify(amazonEC2ClientMock).describeSecurityGroups(any(DescribeSecurityGroupsRequest.class)); }
/** * {@inheritDoc} */ @Override public List<SecurityGroup> getSecurityGroups(Long userNo, Long platformNo) { // セキュリティグループを取得 AwsProcessClient awsProcessClient = awsProcessClientFactory.createAwsProcessClient(userNo, platformNo); DescribeSecurityGroupsRequest request = new DescribeSecurityGroupsRequest(); PlatformAws platformAws = platformAwsDao.read(platformNo); if (BooleanUtils.isTrue(platformAws.getVpc())) { // VPCの場合、VPC IDが同じものを抽出 request.withFilters(new Filter().withName("vpc-id").withValues(platformAws.getVpcId())); } else { // 非VPCの場合、VPC IDが空のものを抽出 request.withFilters(new Filter().withName("vpc-id").withValues("")); } DescribeSecurityGroupsResult result = awsProcessClient.getEc2Client().describeSecurityGroups(request); List<SecurityGroup> securityGroups = result.getSecurityGroups(); // ソート Collections.sort(securityGroups, Comparators.COMPARATOR_SECURITY_GROUP); return securityGroups; }
@Override public Collection<String> listRuleSets() { DescribeSecurityGroupsRequest request = new DescribeSecurityGroupsRequest(); DescribeSecurityGroupsResult result = null; try { result = client.describeSecurityGroups( request ); } catch ( Exception e ) { LOG.warn( "Error while getting security groups", e ); return new LinkedList<String>(); } Collection<String> groups = new ArrayList<String>(); for( SecurityGroup group : result.getSecurityGroups() ) { groups.add( group.getGroupName() ); } return groups; }
@Override public Collection<IpRule> getRules( final String name, final boolean inbound ) { DescribeSecurityGroupsRequest request = new DescribeSecurityGroupsRequest().withGroupNames( name ); DescribeSecurityGroupsResult result = client.describeSecurityGroups( request ); if( result.getSecurityGroups().size() != 1 ) { return null; } Collection<IpRule> ipRules = new ArrayList<IpRule>(); List<IpPermission> permissions; if( inbound ) { permissions = result.getSecurityGroups().get( 0 ).getIpPermissions(); } else { permissions = result.getSecurityGroups().get( 0 ).getIpPermissionsEgress(); } for( IpPermission permission : permissions ) { ipRules.add( toIpRule( permission ) ); } return ipRules; }
public void createDescribeSecurityGroupResult(String vpcId, String SecurityGroupIds) { Collection<SecurityGroup> securityGroup = new ArrayList<SecurityGroup>(); for (int i = 0; i < SecurityGroupIds.split(",").length; i++) { securityGroup.add(new SecurityGroup() .withGroupId(SecurityGroupIds.split(",")[i]) .withGroupName(SecurityGroupIds.split(",")[i]) .withVpcId(vpcId)); } DescribeSecurityGroupsResult securityGroupResult = new DescribeSecurityGroupsResult() .withSecurityGroups(securityGroup); doReturn(securityGroupResult).when(ec2).describeSecurityGroups(); }
public SecurityGroup getSecurityGroupById(String groupId) { SecurityGroup cellGroup = null; DescribeSecurityGroupsRequest req = new DescribeSecurityGroupsRequest() .withGroupIds(groupId); DescribeSecurityGroupsResult cellGroups = this.client.describeSecurityGroups(req); if (cellGroups != null) { cellGroup = cellGroups.getSecurityGroups().get(0); } return cellGroup; }
public List<SecurityGroup> getSecurityGroups(List<String> names, String vpcId) { DescribeSecurityGroupsRequest req = new DescribeSecurityGroupsRequest(); req.withFilters(new Filter(AWS_GROUP_NAME_FILTER, names)); if (vpcId != null) { req.withFilters(new Filter(AWS_VPC_ID_FILTER, Collections.singletonList(vpcId))); } DescribeSecurityGroupsResult groups = this.client.describeSecurityGroups(req); return groups != null ? groups.getSecurityGroups() : Collections.emptyList(); }
public SecurityGroup getSecurityGroup(String name, String vpcId) { SecurityGroup cellGroup = null; DescribeSecurityGroupsRequest req = new DescribeSecurityGroupsRequest() .withFilters(new Filter("group-name", Collections.singletonList(name))); if (vpcId != null) { req.withFilters(new Filter("vpc-id", Collections.singletonList(vpcId))); } DescribeSecurityGroupsResult cellGroups = this.client.describeSecurityGroups(req); if (cellGroups != null && !cellGroups.getSecurityGroups().isEmpty()) { cellGroup = cellGroups.getSecurityGroups().get(0); } return cellGroup; }
public SecurityGroup getDefaultSecurityGroup(String vpcId) { SecurityGroup cellGroup = null; DescribeSecurityGroupsRequest req = new DescribeSecurityGroupsRequest() .withFilters(new Filter("group-name", Collections.singletonList(DEFAULT_SECURITY_GROUP_NAME))); if (vpcId != null) { req.withFilters(new Filter("vpc-id", Collections.singletonList(vpcId))); } DescribeSecurityGroupsResult cellGroups = this.client.describeSecurityGroups(req); if (cellGroups != null && !cellGroups.getSecurityGroups().isEmpty()) { cellGroup = cellGroups.getSecurityGroups().get(0); } return cellGroup; }
public static SecurityGroup getSecurityGroupsIdUsingEC2Client(AmazonEC2AsyncClient client, String awsGroupId) { if (awsGroupId == null) { return null; } DescribeSecurityGroupsRequest describeSGsRequest = new DescribeSecurityGroupsRequest() .withFilters(new Filter(AWSConstants.AWS_GROUP_ID_FILTER,Collections.singletonList(awsGroupId))); DescribeSecurityGroupsResult describeSGResult = client.describeSecurityGroups(describeSGsRequest); if (describeSGResult.getSecurityGroups().size() > 0) { return describeSGResult.getSecurityGroups().get(0); } else { return null; } }
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); } 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()); } }
@Override public void run(final WhitelistCidrForVpcAccessCommand command) { final BaseOutputs baseStackOutputs = configStore.getBaseStackOutputs(); logger.info("Revoking the previous ingress rules..."); final DescribeSecurityGroupsResult securityGroupsResult = ec2Client.describeSecurityGroups( new DescribeSecurityGroupsRequest().withGroupIds(baseStackOutputs.getToolsIngressSgId())); securityGroupsResult.getSecurityGroups().forEach(securityGroup -> { if (!securityGroup.getIpPermissions().isEmpty()) { RevokeSecurityGroupIngressRequest revokeIngressRequest = new RevokeSecurityGroupIngressRequest() .withGroupId(baseStackOutputs.getToolsIngressSgId()) .withIpPermissions(securityGroup.getIpPermissions()); ec2Client.revokeSecurityGroupIngress(revokeIngressRequest); } }); logger.info("Done."); logger.info("Authorizing the new ingress rules..."); final List<IpPermission> ipPermissionList = Lists.newArrayListWithCapacity(command.getPorts().size()); command.getPorts().forEach(port -> { IpPermission ipPermission = new IpPermission() .withIpRanges(command.getCidrs()) .withIpProtocol("tcp") .withFromPort(port) .withToPort(port); ipPermissionList.add(ipPermission); }); AuthorizeSecurityGroupIngressRequest ingressRequest = new AuthorizeSecurityGroupIngressRequest() .withGroupId(baseStackOutputs.getToolsIngressSgId()) .withIpPermissions(ipPermissionList); ec2Client.authorizeSecurityGroupIngress(ingressRequest); logger.info("Done."); }
/** * Validates the configured security group IDs. * * @param client the EC2 client * @param configuration the configuration to be validated * @param accumulator the exception condition accumulator * @param localizationContext the localization context * * @return the vpc id to security group ids mapping */ @VisibleForTesting Map<String, Set<String>> checkSecurityGroupIds(AmazonEC2Client client, Configured configuration, PluginExceptionConditionAccumulator accumulator, LocalizationContext localizationContext) { List<String> securityGroupsIds = EC2InstanceTemplate.CSV_SPLITTER.splitToList( configuration.getConfigurationValue(SECURITY_GROUP_IDS, localizationContext)); Map<String, Set<String>> vpcSgMap = Maps.newHashMap(); for (String securityGroupId : securityGroupsIds) { LOG.info(">> Describing security group '{}'", securityGroupId); try { DescribeSecurityGroupsResult result = client.describeSecurityGroups( new DescribeSecurityGroupsRequest().withGroupIds(securityGroupId)); checkCount(accumulator, SECURITY_GROUP_IDS, localizationContext, securityGroupId, result.getSecurityGroups() ); if (result.getSecurityGroups().size() == 1) { String vpcId = Iterables.getOnlyElement(result.getSecurityGroups()).getVpcId(); Set<String> sgSet = vpcSgMap.get(vpcId); if (sgSet == null) { sgSet = Sets.newHashSet(); vpcSgMap.put(vpcId, sgSet); } sgSet.add(securityGroupId); } } catch (AmazonServiceException e) { if (e.getErrorCode().startsWith(INVALID_SECURITY_GROUP)) { addError(accumulator, SECURITY_GROUP_IDS, localizationContext, null, INVALID_SECURITY_GROUP_MSG, securityGroupId); } else { throw Throwables.propagate(e); } } } return vpcSgMap; }
public List<SecurityGroup> describeSecurityGroupsByVpcId(AwsProcessClient awsProcessClient, String vpcId) { DescribeSecurityGroupsRequest request = new DescribeSecurityGroupsRequest(); request.withFilters(new Filter().withName("vpc-id").withValues(vpcId)); DescribeSecurityGroupsResult result = awsProcessClient.getEc2Client().describeSecurityGroups(request); List<SecurityGroup> securityGroups = result.getSecurityGroups(); return securityGroups; }
@Test public void getPermissions_groupDoesNotExist() { amazonEc2.setRegion(region); expect(amazonEc2.describeSecurityGroups()) .andReturn(new DescribeSecurityGroupsResult() .withSecurityGroups(ImmutableList.<SecurityGroup>of())); replayAll(); assertEquals(ImmutableSet.of(), service().getPermissions("securityGroupName", "dc1")); }
private void securityGroupStartingRules(IpPermission... ipPermissions) { amazonEc2.setRegion(region); SecurityGroup group = new SecurityGroup().withGroupName("securityGroupName") .withIpPermissions(ipPermissions); expect(amazonEc2.describeSecurityGroups()).andReturn( new DescribeSecurityGroupsResult().withSecurityGroups(ImmutableList.of(group))); }
@Override public List<AbstractResource<?>> describeSecurityGroups(Account account, Region region, DateTime dt, Ec2Filter... filters) { AmazonEC2 ec2 = findClient(account, region); DescribeSecurityGroupsRequest req = new DescribeSecurityGroupsRequest(); for (Ec2Filter filter : filters) { Filter f = new Filter().withName(filter.getName()).withValues(filter.getValues()); req.withFilters(f); } log.debug("start describing security groups for account:{} in region:{} via api", account.getId() + "=>" + account.getName(), region); DescribeSecurityGroupsResult res = ec2.describeSecurityGroups(req); return converter.toEc2SecurityGroups(res.getSecurityGroups(), account.getId(), region, dt); }
private void synchronizeIngressRules(AmazonEC2 client, String groupName, Network network) { DescribeSecurityGroupsResult result = client.describeSecurityGroups( new DescribeSecurityGroupsRequest().withGroupNames(groupName)); Set<IpPermission> existingPermissions = ImmutableSet.copyOf(getOnlyElement( result.getSecurityGroups()).getIpPermissions()); Set<IpPermission> expectedPermissions = ImmutableSet.copyOf( Iterables.transform(network.getIngress(), ConvertRuleToIpPermission.FUNCTION)); authorizeIngressRules(client, groupName, difference(expectedPermissions, existingPermissions)); revokeIngressRules(client, groupName, difference(existingPermissions, expectedPermissions)); }
public void assertSecurityGroupExistsWithRules(String groupName, final Set<Rule> ingressRules) { DescribeSecurityGroupsResult result = client.describeSecurityGroups( new DescribeSecurityGroupsRequest().withGroupNames(groupName)); assertThat(result.getSecurityGroups()).hasSize(1); SecurityGroup group = getOnlyElement(result.getSecurityGroups()); assertThat(group.getIpPermissions()).hasSize(ingressRules.size()); assertThat(ingressRules).containsAll(transform(group.getIpPermissions(), ConvertIpPermissionToRule.FUNCTION)); }
private static void deleteGroupIfPresent() { try { DescribeSecurityGroupsRequest describeSecurityGroupsRequest = new DescribeSecurityGroupsRequest().withGroupNames(GROUP_NAME); DescribeSecurityGroupsResult existing = ec2Client.describeSecurityGroups(describeSecurityGroupsRequest); if (existing.getSecurityGroups().size()>0) { DeleteSecurityGroupRequest deleteGroup = new DeleteSecurityGroupRequest().withGroupName(GROUP_NAME); ec2Client.deleteSecurityGroup(deleteGroup); } } catch (AmazonServiceException exception) { // no op } }
@Test public void testShouldAddAndDeleteAnIpToASecurityGroup() throws UnknownHostException { Integer port = 8080; InetAddress adddress = Inet4Address.getByName("192.168.0.1"); String cidr = "192.168.0.1/32"; //add client.addIpToSecGroup(groupId, port , adddress); DescribeSecurityGroupsRequest request = new DescribeSecurityGroupsRequest().withGroupIds(groupId); DescribeSecurityGroupsResult result = ec2Client.describeSecurityGroups(request); List<SecurityGroup> securityGroups = result.getSecurityGroups(); assertEquals(1, securityGroups.size()); SecurityGroup group = securityGroups.get(0); List<IpPermission> perms = group.getIpPermissions(); assertEquals(1, perms.size()); IpPermission ipPermission = perms.get(0); assertEquals(port, ipPermission.getToPort()); assertEquals(port, ipPermission.getFromPort()); assertEquals(1, ipPermission.getIpv4Ranges().size()); assertEquals(cidr, ipPermission.getIpv4Ranges().get(0).getCidrIp()); //remove client.deleteIpFromSecGroup(groupId, port, adddress); result = ec2Client.describeSecurityGroups(request); securityGroups = result.getSecurityGroups(); assertEquals(1, securityGroups.size()); group = securityGroups.get(0); perms = group.getIpPermissions(); assertEquals(0, perms.size()); }
/** * Describe security group. * * @return SecurityGroup */ protected final SecurityGroup getSecurityGroup() { SecurityGroup cellGroup = null; DescribeSecurityGroupsRequest req = new DescribeSecurityGroupsRequest(); DescribeSecurityGroupsResult result = amazonEC2Client.describeSecurityGroups(req); if (result != null && !result.getSecurityGroups().isEmpty()) { cellGroup = result.getSecurityGroups().get(0); } return cellGroup; }
@Override public DescribeSecurityGroupsResult describeSecurityGroups(DescribeSecurityGroupsRequest describeSecurityGroupsRequest) throws AmazonServiceException, AmazonClientException { throw new UnsupportedOperationException("Not supported in mock"); }
@Override public DescribeSecurityGroupsResult describeSecurityGroups() throws AmazonServiceException, AmazonClientException { throw new UnsupportedOperationException("Not supported in mock"); }
/** * Checks whether exiting SecurityGroups is present. * * @param securityGroupNames * @param vpcId * The ID of the VPC the subnet is in.A virtual private cloud * (VPC) is a virtual network dedicated to your AWS account. It * is logically isolated from other virtual networks in the AWS * cloud. You can launch your AWS resources, such as Amazon EC2 * instances, into your VPC. * @return <code>Collection<String> </code> if the matches one of the * securityGroupNames and vpcId * */ public Collection<String> resolveSecurityGroups( Collection<String> securityGroupNames, String vpcId) throws APPlatformException { Collection<String> input = new HashSet<String>(); Collection<String> result = new HashSet<String>(); if (vpcId != null && vpcId.trim().length() == 0) { vpcId = null; } if (securityGroupNames != null && !securityGroupNames.isEmpty()) { input.addAll(securityGroupNames); DescribeSecurityGroupsResult securityGroups = getEC2() .describeSecurityGroups(); LOGGER.debug("Search for securityGroups" + securityGroupNames.toString()); for (SecurityGroup group : securityGroups.getSecurityGroups()) { boolean vpcMatch = false; if (vpcId == null) { vpcMatch = isNullOrEmpty(group.getVpcId()); } else { vpcMatch = vpcId.equals(group.getVpcId()); } if (vpcMatch && input.contains(group.getGroupName())) { result.add(group.getGroupId()); input.remove(group.getGroupName()); } } if (!input.isEmpty()) { StringBuffer sb = new StringBuffer(); for (String name : input) { if (sb.length() > 0) { sb.append(","); } sb.append(name); } throw new APPlatformException( Messages.getAll("error_invalid_security_group") + sb.toString()); } } LOGGER.debug("Done with Searching for securityGroups " + result); return result; }
public void execute() { AmazonEC2 client = null; try { client = getEc2Client(); //Get All the Existing Sec Group Ids String[] securityGroupIds = SystemUtils.getSecurityGroupIds(config.getMacIdForInstance()); DescribeSecurityGroupsRequest req = new DescribeSecurityGroupsRequest().withGroupIds(securityGroupIds); DescribeSecurityGroupsResult result = client.describeSecurityGroups(req); boolean securityGroupFound = false; for (SecurityGroup securityGroup : result.getSecurityGroups()) { logger.info("Read " + securityGroup.getGroupName()); if (securityGroup.getGroupName().equals(config.getACLGroupNameForVPC())) { logger.info("Found matching security group name: " + securityGroup.getGroupName()); // Setting configuration value with the correct SG ID config.setACLGroupIdForVPC(securityGroup.getGroupId()); securityGroupFound = true; break; } } // If correct SG was not found, throw Exception if (!securityGroupFound) { throw new RuntimeException("Cannot find matching security group for " + config.getACLGroupNameForVPC()); } } catch (Exception e) { throw new RuntimeException(e); } finally { if (client != null) { client.shutdown(); } } }
@RequestMapping(method = RequestMethod.GET, value = {"/groups"}) @ResponseBody public DescribeSecurityGroupsResult describeSecurityGroups(@RequestParam("accessKey") String accessKey, @RequestParam("secretKey") String secretKey) { return awsec2Service.describeSecurityGroups(awsCredentialsFactory.createSimpleAWSCredentials(accessKey, secretKey)); }
@Override public boolean load(DescribeSecurityGroupsRequest request, ResultCapture<DescribeSecurityGroupsResult> extractor) { return resource.load(request, extractor); }
private Optional<SecurityGroup> getSecurityGroup(String groupName, String dataCenter) { DescribeSecurityGroupsResult result = client(dataCenter).describeSecurityGroups(); // Specifying non-existent group in the request throws exception. Request all and filter instead. return Iterables.tryFind(result.getSecurityGroups(), withGroupName(groupName)); }
private void validateAndConfigureSecurityGroups(List<String> securityGroupNamesOrIds, AmazonEC2 connector, boolean withNames) throws ConnectorException { DescribeSecurityGroupsRequest describeSecurityGroupsRequest = new DescribeSecurityGroupsRequest(); if (withNames) { describeSecurityGroupsRequest.withGroupNames(securityGroupNamesOrIds); } else { describeSecurityGroupsRequest.withGroupIds(securityGroupNamesOrIds); } DescribeSecurityGroupsResult describeSecurityGroupsResult = connector.describeSecurityGroups(describeSecurityGroupsRequest); String controllerIp = "0.0.0.0/0"; int agentPort = controllerServices.getDefaultAgentPort(); // check if any one of the security group // already has agent port and controller ip List<SecurityGroup> securityGroups = describeSecurityGroupsResult.getSecurityGroups(); for (SecurityGroup securityGroup : securityGroups) { List<IpPermission> ipPermissions = securityGroup.getIpPermissions(); for (IpPermission permission : ipPermissions) { if (permission.getIpRanges().contains(controllerIp) && (agentPort >= permission.getFromPort() && agentPort <= permission.getToPort())) { return; } } } String securityGroupIdOrName = null; if (withNames) { if (securityGroupNamesOrIds.contains(Utils.DEFAULT_SECURITY_GROUP)) { securityGroupIdOrName = Utils.DEFAULT_SECURITY_GROUP; } else { securityGroupIdOrName = securityGroups.get(0).getGroupName(); } } else { securityGroupIdOrName = securityGroups.get(0).getGroupId(); } IpPermission ipPermission = new IpPermission(); ipPermission.setFromPort(agentPort); ipPermission.setToPort(agentPort); ipPermission.setIpProtocol("tcp"); ipPermission.setIpRanges(Lists.newArrayList(controllerIp)); AuthorizeSecurityGroupIngressRequest securityGroupIngressRequest = new AuthorizeSecurityGroupIngressRequest(); securityGroupIngressRequest.withIpPermissions(ipPermission); if (withNames) { securityGroupIngressRequest.withGroupName(securityGroupIdOrName); } else { securityGroupIngressRequest.withGroupId(securityGroupIdOrName); } connector.authorizeSecurityGroupIngress(securityGroupIngressRequest); }
/** * Makes a call to the service to load this resource's attributes if they * are not loaded yet, and use a ResultCapture to retrieve the low-level * client response * The following request parameters will be populated from the data of this * <code>SecurityGroup</code> resource, and any conflicting parameter value * set in the request will be overridden: * <ul> * <li> * <b><code>GroupIds.0</code></b> * - mapped from the <code>Id</code> identifier. * </li> * </ul> * * <p> * * @return Returns {@code true} if the resource is not yet loaded when this * method was invoked, which indicates that a service call has been * made to retrieve the attributes. * @see DescribeSecurityGroupsRequest */ boolean load(DescribeSecurityGroupsRequest request, ResultCapture<DescribeSecurityGroupsResult> extractor);