com.amazonaws.services.ec2.model.DescribeSecurityGroupsRequest Java Examples

The following examples show how to use com.amazonaws.services.ec2.model.DescribeSecurityGroupsRequest. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SecurityGroupsTableProviderTest.java    From aws-athena-query-federation with Apache License 2.0 6 votes vote down vote up
@Override
protected void setUpRead()
{
    when(mockEc2.describeSecurityGroups(any(DescribeSecurityGroupsRequest.class)))
            .thenAnswer((InvocationOnMock invocation) -> {
                DescribeSecurityGroupsRequest request = (DescribeSecurityGroupsRequest) invocation.getArguments()[0];

                assertEquals(getIdValue(), request.getGroupIds().get(0));
                DescribeSecurityGroupsResult mockResult = mock(DescribeSecurityGroupsResult.class);
                List<SecurityGroup> values = new ArrayList<>();
                values.add(makeSecurityGroup(getIdValue()));
                values.add(makeSecurityGroup(getIdValue()));
                values.add(makeSecurityGroup("fake-id"));
                when(mockResult.getSecurityGroups()).thenReturn(values);
                return mockResult;
            });
}
 
Example #2
Source File: SGLookupService.java    From Gatekeeper with Apache License 2.0 6 votes vote down vote up
private List<String> loadSgsForAccountRegion(AWSEnvironment environment) {
    logger.info("Grabbing SGs for environment " + environment);
    DescribeSecurityGroupsRequest describeSecurityGroupsRequest = new DescribeSecurityGroupsRequest();

    Filter groupNameFilter = new Filter();
    groupNameFilter.setName("group-name");
    groupNameFilter.setValues(Arrays.asList(securityGroupNames.split(",")));

    AmazonEC2Client amazonEC2Client = awsSessionService.getEC2Session(environment);
    DescribeSecurityGroupsResult result = amazonEC2Client.describeSecurityGroups(describeSecurityGroupsRequest.withFilters(groupNameFilter));

    logger.info("found " + result.getSecurityGroups().size() + " Security Groups with name(s) '" + securityGroupNames + "'");
    return result.getSecurityGroups().stream()
            .map(SecurityGroup::getGroupId)
            .collect(Collectors.toList());

}
 
Example #3
Source File: SecurityGroupsCheckerImpl.java    From fullstop with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #4
Source File: SecurityGroupProviderTest.java    From fullstop with Apache License 2.0 6 votes vote down vote up
@Test
public void testAmazonException(){
    final AmazonServiceException amazonServiceException = new AmazonServiceException("");
    amazonServiceException.setErrorCode("InvalidGroup.NotFound");

    when(clientProviderMock.getClient(any(), anyString(), any(Region.class))).thenReturn(amazonEC2ClientMock);
    when(amazonEC2ClientMock.describeSecurityGroups(any(DescribeSecurityGroupsRequest.class))).thenThrow(amazonServiceException);

    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));
}
 
Example #5
Source File: SecurityGroupProviderTest.java    From fullstop with Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example #6
Source File: AwsDescribeServiceImpl.java    From primecloud-controller with GNU General Public License v2.0 6 votes vote down vote up
/**
 * {@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;
}
 
Example #7
Source File: AmazonIpRuleManager.java    From usergrid with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #8
Source File: AmazonIpRuleManager.java    From usergrid with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #9
Source File: PublicAccessAutoFix.java    From pacbot with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the existing security group details.
 *
 * @param securityGroupList the security group list
 * @param ec2Client the ec 2 client
 * @return the existing security group details
 */
public static List<SecurityGroup> getExistingSecurityGroupDetails(Set<String> securityGroupList, AmazonEC2 ec2Client) {
	RetryConfig config = RetryConfig.custom().maxAttempts(MAX_ATTEMPTS).waitDuration(Duration.ofSeconds(WAIT_INTERVAL)).build();
	RetryRegistry registry = RetryRegistry.of(config);
	DescribeSecurityGroupsRequest securityGroups = new DescribeSecurityGroupsRequest();
  		securityGroups.setGroupIds(securityGroupList);
	Retry retry = registry.retry(securityGroups.toString());
  		
	Function<Integer, List<SecurityGroup>> decorated
	  =  Retry.decorateFunction(retry, (Integer s) -> {
		  DescribeSecurityGroupsResult  groupsResult =  ec2Client.describeSecurityGroups(securityGroups);
		  return groupsResult.getSecurityGroups();
	    });
	return decorated.apply(1);
}
 
Example #10
Source File: BaseTest.java    From aws-mock with MIT License 5 votes vote down vote up
/**
 * 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;
}
 
Example #11
Source File: AwsPlatformResources.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private List<SecurityGroup> fetchSecurityGroups(AmazonEC2Client ec2Client, DescribeSecurityGroupsRequest describeSecurityGroupsRequest) {
    try {
        return ec2Client.describeSecurityGroups(describeSecurityGroupsRequest).getSecurityGroups();
    } catch (AmazonEC2Exception e) {
        if (e.getStatusCode() == HttpStatus.BAD_REQUEST.value() || e.getStatusCode() == HttpStatus.NOT_FOUND.value()) {
            throw new PermanentlyFailedException(e.getErrorMessage(), e);
        } else {
            throw e;
        }
    }
}
 
Example #12
Source File: AwsPlatformResources.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Override
public CloudSecurityGroups securityGroups(CloudCredential cloudCredential, Region region, Map<String, String> filters) {
    Map<String, Set<CloudSecurityGroup>> result = new HashMap<>();
    Set<CloudSecurityGroup> cloudSecurityGroups = new HashSet<>();
    AmazonEC2Client ec2Client = awsClient.createAccess(new AwsCredentialView(cloudCredential), region.value());

    //create securitygroup filter view
    PlatformResourceSecurityGroupFilterView filter = new PlatformResourceSecurityGroupFilterView(filters);

    DescribeSecurityGroupsRequest describeSecurityGroupsRequest = new DescribeSecurityGroupsRequest();
    // If the filtervalue is provided then we should filter only for those securitygroups
    if (!Strings.isNullOrEmpty(filter.getVpcId())) {
        describeSecurityGroupsRequest.withFilters(new Filter("vpc-id", singletonList(filter.getVpcId())));
    }
    if (!Strings.isNullOrEmpty(filter.getGroupId())) {
        describeSecurityGroupsRequest.withGroupIds(filter.getGroupId());
    }
    if (!Strings.isNullOrEmpty(filter.getGroupName())) {
        describeSecurityGroupsRequest.withGroupNames(filter.getGroupName());
    }

    for (SecurityGroup securityGroup : fetchSecurityGroups(ec2Client, describeSecurityGroupsRequest)) {
        Map<String, Object> properties = new HashMap<>();
        properties.put("vpcId", securityGroup.getVpcId());
        properties.put("description", securityGroup.getDescription());
        properties.put("ipPermissions", securityGroup.getIpPermissions());
        properties.put("ipPermissionsEgress", securityGroup.getIpPermissionsEgress());
        cloudSecurityGroups.add(new CloudSecurityGroup(securityGroup.getGroupName(), securityGroup.getGroupId(), properties));
    }
    result.put(region.value(), cloudSecurityGroups);
    return new CloudSecurityGroups(result);
}
 
Example #13
Source File: EC2Impl.java    From aws-sdk-java-resources with Apache License 2.0 5 votes vote down vote up
@Override
public SecurityGroupCollection getSecurityGroups(
        DescribeSecurityGroupsRequest request) {

    ResourceCollectionImpl result = service.getCollection("SecurityGroups",
            request);

    if (result == null) return null;
    return new SecurityGroupCollectionImpl(result);
}
 
Example #14
Source File: VpcImpl.java    From aws-sdk-java-resources with Apache License 2.0 5 votes vote down vote up
@Override
public SecurityGroupCollection getSecurityGroups(
        DescribeSecurityGroupsRequest request) {

    ResourceCollectionImpl result = resource.getCollection("SecurityGroups",
            request);

    if (result == null) return null;
    return new SecurityGroupCollectionImpl(result);
}
 
Example #15
Source File: AwsCommonProcess.java    From primecloud-controller with GNU General Public License v2.0 5 votes vote down vote up
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;
}
 
Example #16
Source File: DescribeSecurityGroups.java    From aws-doc-sdk-examples with Apache License 2.0 5 votes vote down vote up
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());
    }
}
 
Example #17
Source File: SecurityGroupImpl.java    From aws-sdk-java-resources with Apache License 2.0 4 votes vote down vote up
@Override
public boolean load(DescribeSecurityGroupsRequest request) {
    return load(request, null);
}
 
Example #18
Source File: SecurityGroupImpl.java    From aws-sdk-java-resources with Apache License 2.0 4 votes vote down vote up
@Override
public boolean load(DescribeSecurityGroupsRequest request,
        ResultCapture<DescribeSecurityGroupsResult> extractor) {

    return resource.load(request, extractor);
}
 
Example #19
Source File: EC2Impl.java    From aws-sdk-java-resources with Apache License 2.0 4 votes vote down vote up
@Override
public SecurityGroupCollection getSecurityGroups() {
    return getSecurityGroups((DescribeSecurityGroupsRequest)null);
}
 
Example #20
Source File: SetVPCSecurityGroupID.java    From Raigad with Apache License 2.0 4 votes vote down vote up
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();
        }
    }
}
 
Example #21
Source File: EC2.java    From aws-sdk-java-resources with Apache License 2.0 2 votes vote down vote up
/**
 * Retrieves the SecurityGroups collection referenced by this resource.
 */
SecurityGroupCollection getSecurityGroups(DescribeSecurityGroupsRequest
        request);
 
Example #22
Source File: SecurityGroup.java    From aws-sdk-java-resources with Apache License 2.0 2 votes vote down vote up
/**
 * 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);
 
Example #23
Source File: SecurityGroup.java    From aws-sdk-java-resources with Apache License 2.0 2 votes vote down vote up
/**
 * Makes a call to the service to load this resource's attributes if they
 * are not loaded yet.
 * 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);
 
Example #24
Source File: Vpc.java    From aws-sdk-java-resources with Apache License 2.0 2 votes vote down vote up
/**
 * Retrieves the SecurityGroups collection referenced by this resource.
 */
SecurityGroupCollection getSecurityGroups(DescribeSecurityGroupsRequest
        request);