Jsonnet是否支持调用Shell?能否将Shell命令输出赋值给变量?
curl Directly in Code? Short answer: No, Jsonnet doesn't support directly executing external commands (like your curl example) within its code. Here's why, plus how to achieve your goal:
Why It Doesn't Work
Jsonnet is built as a pure, side-effect-free configuration language. Its core design focuses on static evaluation and generating structured data (JSON/YAML) without interacting with the external system during its own evaluation process. Running shell commands would introduce unpredictable side effects and tie your Jsonnet code to specific runtime environments—something that goes against its intended purpose as a portable, declarative config tool.
How to Get the Region Value Into Your Jsonnet Code
You’ll need to pass the output of the curl command into Jsonnet from the outside. Here are the most common, reliable approaches:
1. Use Command-Line External Variables
Jsonnet lets you pass string values via the --ext-str flag (or code snippets with --ext-code). For your use case, run this in your shell:
jsonnet --ext-str region=$(curl http://100.100.100.200/latest/metadata/region_id) your_file.jsonnet
Then reference the variable in your Jsonnet code using std.extVar:
local region = std.extVar("region"); { deployment_config: { target_region: region, // Rest of your configuration here } }
2. Use Environment Variables (With a Wrapper)
If you prefer working with environment variables, wrap the curl call and pass the value to Jsonnet:
export REGION_ID=$(curl http://100.100.100.200/latest/metadata/region_id) jsonnet --ext-str region=$REGION_ID your_file.jsonnet
Note: Core Jsonnet doesn’t read environment variables natively, but this shell-based workaround gets the job done. Tools built on Jsonnet (like Tanka) may have built-in support for env vars if you’re using those.
3. Preprocess the Value Into a Reusable File
If you need the region value to be part of a shared config, write it to a small Jsonnet library file first:
echo "local region = '$(curl http://100.100.100.200/latest/metadata/region_id)'; export region;" > region.libsonnet
Then import it in your main Jsonnet file:
local region = import "region.libsonnet"; { app_settings: { region: region } }
All these methods keep your Jsonnet code clean, portable, and true to its design, while still getting the dynamic region value you need.
内容的提问来源于stack exchange,提问作者che yang

