A minimal example repo demonstrating a workaround for
bazelbuild/bazel#10904 —
the long-standing request for environment variable interpolation inside
.bazelrc files.
Bazel's .bazelrc does not natively expand client environment variables,
which makes it awkward to thread values like build IDs, user names, or tokens
from the surrounding shell into the build graph. This repo shows one way
to get the effect using bazelisk's tools/bazel wrapper script with an
interpolation function such as envsubst.
To use this example, you must have bazelisk and envsubst installed.
.bazelrcdefined the flagbuild --action_env=GREETING_MESSAGE="Hello $MY_MESSAGE!".- When bazel is invoked, bazelisk invokes the
tools/bazelwrapper script, which callsenvsubstto render a copy of the workspace.bashrc. In this copy,$MY_MESSAGEis interpolated from the invoking shell environment. This rendered version of.bashrcis then inserted into the command flags used by the actual bazel invocation. BUILD.bazeldefines agenrulethat reads$GREETING_MESSAGEat action time and writes agreeting.hcontaining#define GREETING_MESSAGE "...".hello.ccincludes the generated header and prints the macro.
This results in the value of $MY_MESSAGE ending up in a string literal
compiled into the //:hello binary.
MY_MESSAGE="world" bazel run //:hello
INFO: Analyzed target //:hello (68 packages loaded, 477 targets configured).
INFO: Found 1 target...
Target //:hello up-to-date:
bazel-bin/hello
INFO: Elapsed time: 0.469s, Critical Path: 0.26s
INFO: 5 processes: 2 action cache hit, 2 internal, 3 linux-sandbox.
INFO: Build completed successfully, 5 total actions
INFO: Running command line: bazel-bin/hello
Hello world!
Change MY_MESSAGE and rerun to see the compiled string literal change
accordingly:
MY_MESSAGE="from bzlmod" bazel run //:hello
...
Hello from bzlmod!
- MODULE.bazel - bzlmod module declaration (
rules_cc) - BUILD.bazel -
genrule+cc_binary - hello.cc - consumes the generated macro
- .bazelrc - the
--action_envdirective being demonstrated - tools/bazel - the wrapper script performing the interpolation
0BSD.