Search code examples
amazon-web-servicesamazon-ec2aws-cliaws-security-group

AWS EC2 CLI gives inconsistent results for describe-security-groups


I have two different security groups I want to query, lets call them sg-xxx and sg-yyy. I am running the following command to get details on which IPs are within each group:

aws ec2 describe-security-groups \
  --filters Name=ip-permission.to-port,Values=22 Name=ip-permission.from-port,Values=22 Name=ip-permission.protocol,Values=tcp \
  --group-ids sg-xxx --output text

When I run the command line with sg-xxx, I get output similar to:

SECURITYGROUPS  group-name created YYYY-MM-DDTHH:MM:SS.ZZZ+00:00    sg-xxx  group-name  xxxxxxxxxxxx    vpc-xxx
IPPERMISSIONS   22  tcp 22
IPRANGES    1.1.1.1/32
IPRANGES    2.2.2.2/32
IPPERMISSIONSEGRESS -1
IPRANGES    0.0.0.0/0

However, when I run the same command line with sg-yyy, it includes entries that are not using port 22:

SECURITYGROUPS  group-name  sg-yyy  group-tag   xxxxxxxxxxxx    vpc-yyy
IPPERMISSIONS   80  tcp 80
IPRANGES    0.0.0.0/0
IPPERMISSIONS   22  tcp 22
IPRANGES    1.1.1.1/32
IPRANGES    2.2.2.2/32
IPPERMISSIONS   10000   tcp 10000
IPRANGES    3.3.3.3/32
IPPERMISSIONS   25  tcp 25
IPRANGES    0.0.0.0/0
IPPERMISSIONSEGRESS -1
IPRANGES    0.0.0.0/0

Anyone experiencing similar issues with this command line, and anyone know how to fix this?

If this is expected behavior, is there any way of getting just the rules that match tcp port 22?


Solution

  • What you are asking the CLI is to describe the security group (which it includes it name, sg-id, vpc-id, account-id etc.,)The command describes the security group that matches your filter. It doesn't mean it will only list the SG rules that match the filter. The CLI describes the group, not the rules.

    sg-xxx seems to have only one rule. If it has other rules, you will see them listed.

    To get only the matching rules, add

    --query 'SecurityGroups[*].IpPermissions[?ToPort==`22`]'
    

    to end of your query.

    aws ec2 describe-security-groups --filters Name=ip-permission.to-port,Values=22\
       Name=ip-permission.from-port,Values=22 Name=ip-permission.protocol,Values=tcp\
       --group-ids sg-xxx --query 'SecurityGroups[*].IpPermissions[?ToPort==`22`]'\
       --output text
    

    Output

    22  tcp 22
    IPRANGES    1.1.1.1/32
    IPRANGES    2.2.2.2/32