Search code examples
powershellamazon-web-servicesamazon-ec2aws-powershell

How can I access properties of the IpPermissions property of Get-EC2SecurityGroup?


  1. I am trying to get a list of security groups. (Successful - Using Get-EC2SecurityGroup)
  2. Get a list of the specific IPPermissions associated with each security group. ( Successful - Using (Get-EC2SecurityGroup).IpPermissions )
  3. Only return results where the FromPort = "xxx" ( Unsuccessful - Not sure how to access the FromPort property that is returned in the result list )

Ultimately what I am trying to accomplish is:

  1. Get a list of existing security groups, and loop through each group.

  2. While looping through each group, call the IpPermissions, and look for the specific FromPort "xxx".

  3. If the FromPort is a match, record the other properties: (FromPort, IpProtocol, IpRanges, ToPort, UserIdGroupPairs)

Problem I am having

  1. I am not sure how to do a loop using the amazon objects

  2. I cant seem to access the properties even though they appear to be named and have values.

  3. I have tried using -Filter with many different iterations, with no success.

  4. The documentation seems self-referencing, and the examples I have run across dont get down to this level of detail.

Results returned from (Get-EC2SecurityGroup).IpPermissions

FromPort         : 123
IpProtocol       : tcp
IpRanges         : {0.0.0.0/0}
ToPort           : 123
UserIdGroupPairs : {}

Solution

  • Here's an example that does as you've described:

    • Filters security group objects by FromPort
    • Of the matched security groups, output IpProtocol, IpRanges, ToPort, and UserIdGroupPairs.

    Code:

    # Example using port 22
    PS C:\> $port = 22
    PS C:\> Get-EC2SecurityGroup | 
        ? { $_.IpPermissions.FromPort -eq $port } | 
        % { $_.IpPermissions } | 
        Select -property IpProtocol, IpRanges, ToPort, UserIdGroupPairs
    

    Output:

    IpProtocol    IpRanges        ToPort UserIdGroupPairs
    ----------    --------        ------ ----------------
    tcp           {0.0.0.0/0}     22     {}
    ...           ...             ...    ...