Found some similar questions on here but none that specifically answered this question. I have several security groups that have rules that allow all traffic from all source IPs. I would like to concoct a simple CLI command that grabs these for me.
After scouring some sources, I thought for sure this command would work:
$ aws ec2 describe-security-groups
--filters "Name=ip-permission.protocol,Values=-1"
--query 'SecurityGroups[?length(IpPermissions[?IpProtocol==`-1` && contains(IpRanges[].CidrIp, `0.0.0.0/0`)]) > `0`]'
[]
However, this returns an empty list. In fact, narrowing it down to just the first condition of the query returns an empty list
$ aws ec2 describe-security-groups
--filters "Name=ip-permission.protocol,Values=-1"
--query 'SecurityGroups[?length(IpPermissions[?IpProtocol==`-1`]) > `0`]'
[]
even though taking out the above query (which I thought matches the filter) returns several security groups:
aws ec2 describe-security-groups
--filters "Name=ip-permission.protocol,Values=-1"
[sg-1, sg-2, sg-3 ...]
What am I not understanding? Thanks in advance.
UPDATE
This new query is closer. It is retrieving every security group that has both a rule that allows all protocols and a rule that allows traffic from all IPs. However, the security groups currently being retrieved do not explicitly have those two conditions in the same rule as I'd like.
aws ec2 describe-security-groups
--filters "Name=ip-permission.protocol,Values=-1"
--query "SecurityGroups[?IpPermissions[?IpProtocol == '-1']] |
[?length(IpPermissions[?contains(IpRanges[].CidrIp, `0.0.0.0/0`)]) > `0`]"
Also, I figure it would be helpful to show the JSON object for those unfamiliar with its structure. You can find it on this page towards the bottom
Turns out, my original command was actually very close. I took out the logic with the length()
function and now it works.
aws ec2 describe-security-groups
--filters "Name=ip-permission.protocol,Values=-1"
--query "SecurityGroups[?IpPermissions[?IpProtocol == '-1' &&
contains(IpRanges[].CidrIp,'0.0.0.0/0')]].GroupId"
Hope this helps someone in the future.