Java Code Examples for com.amazonaws.services.ec2.model.DescribeSecurityGroupsResult#getSecurityGroups()

The following examples show how to use com.amazonaws.services.ec2.model.DescribeSecurityGroupsResult#getSecurityGroups() . 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: 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 2
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 3
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 4
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 5
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 6
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 7
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 8
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();
        }
    }
}