如何使用jq条件删除AWS WAF规则JSON数组内的指定元素
报错原因
你写的jq语句直接遍历所有外层数组元素的Statement.ManagedRuleGroupStatement字段,但数组中第二个DDOS_rate_rule规则的Statement下没有ManagedRuleGroupStatement,访问到null值时迭代就会触发报错。
单条删除实现方案
以下语句可以安全删除ExcludedRules中指定Name的对象,不会修改不匹配的规则项:
jq 'map( if has("Statement") and (.Statement | has("ManagedRuleGroupStatement")) and (.Statement.ManagedRuleGroupStatement | has("ExcludedRules")) then .Statement.ManagedRuleGroupStatement.ExcludedRules |= map(select(.Name != "OS-Command-Injection-01")) else . end )' 你的JSON文件路径
逻辑说明:
- 外层用
map遍历所有规则项,先判断当前规则是否存在ExcludedRules字段,避免访问空值 - 对符合条件的规则,用
|=更新ExcludedRules数组,过滤掉Name等于待删除值的对象 - 没有
ExcludedRules的规则项直接原样返回,不会被改动
批量删除扩展
如果要同时删除多个规则,调整select的过滤条件即可,jq 1.6及以上版本可以用IN运算符简化写法:
jq 'map( if has("Statement") and (.Statement | has("ManagedRuleGroupStatement")) and (.Statement.ManagedRuleGroupStatement | has("ExcludedRules")) then .Statement.ManagedRuleGroupStatement.ExcludedRules |= map(select(.Name | IN("OS-Command-Injection-01", "Malicious-Robot", "SQL-Injection-01") | not)) else . end )' 你的JSON文件路径
低版本jq可以换成多条件判断:select(.Name != "OS-Command-Injection-01" and .Name != "Malicious-Robot" and .Name != "SQL-Injection-01")
如果需要直接修改原文件,可以配合sponge命令(需先安装moreutils包):
jq '上述jq逻辑' 你的JSON文件路径 | sponge 你的JSON文件路径
内容的提问来源于stack exchange,提问作者Tnimni
相关产品推荐
相关产品推荐

