如何在OPA服务器模式下使用动态数据?解决请求报错问题
OPA服务器模式下"input" key缺失报错的修复方案
问题背景
你使用静态Rego规则处理事件驱动的动态输入数据,启动OPA服务器的命令为:
./opa run --server --set=default_decision=example/allow ./example.rego
Rego规则代码:
package example default python3 = false python3 { pythonVersion := regex.split("python", input.runtime)[1] to_number(pythonVersion) >= 3.0 }
通过opa eval命令可得到正确结果:
./opa eval --data example.rego --input input.json "data.example.python3"
但使用curl调用OPA服务器API时收到报错:
{"result":false,"warning":{"code":"api_usage_warning","message":"'input' key missing from request"}}
curl调用命令:
curl localhost:8181/v1/data/example/python3 -i -d @input.json -H "Content-Type: application/json"
修复方案
OPA的Data API要求请求体必须是包含input键的JSON对象,你当前直接传递了原始输入数据,未包裹在input键下,有两种修复方式:
方式1:修改输入文件格式
将input.json的原有数据包裹在input顶层键中,例如:
原input.json(假设内容):
{"runtime": "python3.8"}
修改为:
{"input": {"runtime": "python3.8"}}
之后用原curl命令调用即可正常获取结果。
方式2:在curl命令中动态包装输入数据
如果不想修改输入文件,可借助jq工具在命令行中给数据动态加上input键:
curl localhost:8181/v1/data/example/python3 -i -H "Content-Type: application/json" -d "$(jq -n --argfile data input.json '{input: $data}')"
原因说明
opa eval的--input参数会直接将文件内容作为规则中input变量的值,而OPA服务器的Data API要求请求体是结构化JSON对象,其中input键对应规则中使用的input变量数据,两种运行模式的输入格式差异导致了本次报错。
内容的提问来源于stack exchange,提问作者Greg
相关产品推荐
相关产品推荐

