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

The following examples show how to use com.amazonaws.services.ec2.model.DescribeSecurityGroupsResult. 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: InventoryUtil.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch security groups.
 *
 * @param temporaryCredentials the temporary credentials
 * @param skipRegions the skip regions
 * @param accountId the accountId
 * @param accountName the account name
 * @return the map
 */
public static Map<String,List<SecurityGroup>> fetchSecurityGroups(BasicSessionCredentials temporaryCredentials, String skipRegions,String accountId,String accountName){
	log.info("skipRegionseee" + skipRegions);
	Map<String,List<SecurityGroup>> secGrpList = new LinkedHashMap<>();
	AmazonEC2 ec2Client ;
	String expPrefix = InventoryConstants.ERROR_PREFIX_CODE+accountId + "\",\"Message\": \"Exception in fetching info for resource in specific region\" ,\"type\": \"Security Group\" , \"region\":\"" ;
	log.info("sgregion" + RegionUtils.getRegions().toString());
	for(Region region : RegionUtils.getRegions()) {
		try{
			if(!skipRegions.contains(region.getName())){
				ec2Client = AmazonEC2ClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(temporaryCredentials)).withRegion(region.getName()).build();
				DescribeSecurityGroupsResult rslt =  ec2Client.describeSecurityGroups();
				List<SecurityGroup> secGrpListTemp = rslt.getSecurityGroups();
				if( !secGrpListTemp.isEmpty() ) {
					log.debug(InventoryConstants.ACCOUNT + accountId +" Type : Security Group "+region.getName()+" >> " + secGrpListTemp.size());
					secGrpList.put(accountId+delimiter+accountName+delimiter+region.getName(),secGrpListTemp);
				}

			}
		}catch(Exception e){
			log.warn(expPrefix+ region.getName()+InventoryConstants.ERROR_CAUSE +e.getMessage()+"\"}");
			ErrorManageUtil.uploadError(accountId,region.getName(),"sg",e.getMessage());
		}
	}
	return secGrpList;
}
 
Example #3
Source File: InventoryUtilTest.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch security groups test.
 *
 * @throws Exception the exception
 */
@SuppressWarnings("static-access")
@Test
public void fetchSecurityGroupsTest() throws Exception {
    
    mockStatic(AmazonEC2ClientBuilder.class);
    AmazonEC2 ec2Client = PowerMockito.mock(AmazonEC2.class);
    AmazonEC2ClientBuilder amazonEC2ClientBuilder = PowerMockito.mock(AmazonEC2ClientBuilder.class);
    AWSStaticCredentialsProvider awsStaticCredentialsProvider = PowerMockito.mock(AWSStaticCredentialsProvider.class);
    PowerMockito.whenNew(AWSStaticCredentialsProvider.class).withAnyArguments().thenReturn(awsStaticCredentialsProvider);
    when(amazonEC2ClientBuilder.standard()).thenReturn(amazonEC2ClientBuilder);
    when(amazonEC2ClientBuilder.withCredentials(anyObject())).thenReturn(amazonEC2ClientBuilder);
    when(amazonEC2ClientBuilder.withRegion(anyString())).thenReturn(amazonEC2ClientBuilder);
    when(amazonEC2ClientBuilder.build()).thenReturn(ec2Client);
    
    DescribeSecurityGroupsResult describeSecurityGroupsResult = new DescribeSecurityGroupsResult();
    List<SecurityGroup> secGrpList = new ArrayList<>();
    secGrpList.add(new SecurityGroup());
    describeSecurityGroupsResult.setSecurityGroups(secGrpList);
    when(ec2Client.describeSecurityGroups()).thenReturn(describeSecurityGroupsResult);
    assertThat(inventoryUtil.fetchSecurityGroups(new BasicSessionCredentials("awsAccessKey", "awsSecretKey", "sessionToken"), 
            "skipRegions", "account","accountName").size(), is(1));
    
}
 
Example #4
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 #5
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 #6
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 #7
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 #8
Source File: SecurityGroupsCheckerImplTest.java    From fullstop with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #9
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 #10
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 #11
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 #12
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 #13
Source File: EC2Mockup.java    From development with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example #14
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 #15
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 #16
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 #17
Source File: GroupController.java    From sequenceiq-samples with Apache License 2.0 4 votes vote down vote up
@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));
}
 
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: EC2Communication.java    From development with Apache License 2.0 4 votes vote down vote up
/**
 * 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;
}
 
Example #20
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 #21
Source File: SecurityGroupService.java    From sequenceiq-samples with Apache License 2.0 votes vote down vote up
DescribeSecurityGroupsResult describeSecurityGroups(AWSCredentials credentials);