It is a really hard task to remove rules from nftables in a reliable way and it looks like nobody is going to make this task easier. delete-by-name feature has been shelved. I've read mailing lists: some guys tried but failed.
Everyone is trying to get handles using grep, awk, etc but this way is not reliable. Something will change in the next 10 years, and all your software will be auto-converted to pumpkin.
Redhat is forcing everyone to move from iptables to nftables, so we have to deal with deletion somehow, no matter how complex this bicycle will be. Lets rock!
sudo nft "add rule ip nat POSTROUTING oifname \"wg0\" masquerade"
sudo nft --json --handle list ruleset |
jq -r '
.nftables |
map(
.rule |
select(
.family == "ip" and
.table == "nat" and
.chain == "POSTROUTING" and
.expr != null and
(
.expr |
map(
select(
.match.left.meta.key == "oifname" and
.match.op == "==" and
.match.right == "wg0"
)
) | length > 0
) and
(
.expr |
map(
select(has("masquerade")
) | length > 0
)
)
) |
.handle
)[]' |
xargs -I {} sudo nft "delete rule ip nat POSTROUTING handle {}"
PS I am reading Simple rule management, doing facepalm and crying at the same time. It was not possible for nftables developers to understand that release without delete-by-name feature is a pain for users. Low quality engineers from Redhat are trying to force nftables release in the following form.