如何让Rego Playground的输出按策略定义的行顺序排序?
首先澄清参数误区
--profile-sort 是OPA命令行工具专为性能分析结果设计的排序参数,仅作用于性能 profiling 输出,和普通策略评估的输出排序逻辑无关,因此你在策略中添加profile-sort = "line"的配置不会生效。
具体实现方案分两种场景:
1. 在Rego Playground中使用
Rego Playground默认对JSON输出的键做字母序排序,你可以通过两种方式保留策略定义的顺序:
- 关闭排序开关:直接在Playground设置中关闭「Sort output keys」选项,输出就会按照策略定义的顺序展示
- 调整输出结构:如果需要跨环境保证顺序,将输出从对象改为数组,数组天然保留元素定义顺序,示例写法:
# 原对象写法(会被默认排序) default output = {} output = { "rule_a": res_a, "rule_c": res_c, "rule_b": res_b } # 调整为数组写法(严格保留定义顺序) default output = [] output = [ {"rule_name": "rule_a", "result": res_a}, {"rule_name": "rule_c", "result": res_c}, {"rule_name": "rule_b", "result": res_b} ]
2. 本地使用OPA CLI运行策略
执行opa eval命令时添加--pretty-nondeterministic参数即可关闭默认的字母序排序,输出键的顺序会和策略中定义的顺序保持一致,示例命令:opa eval --data your_policy.rego --input your_input.json "data.your_package.output" --pretty-nondeterministic
内容的提问来源于stack exchange,提问作者Tom Turner
相关产品推荐
相关产品推荐

