Cynial
Cynial

Reputation: 680

How to export environment variables from files in bazel

bazel --action_env can specify variables one by one

If there is .env file, how can I export it?

Upvotes: 0

Views: 2351

Answers (1)

Ondrej K.
Ondrej K.

Reputation: 9664

If you run it on a U*X like system, for the format of your file one var=val pair per each line, you can run something like this (note this is a bit naive and will break if there are whitespace characters in any variable value):

bazel build $(while read l; do echo "--action_env $l"; done < .env) //target

It literally adds --action_env line_of_input_from_your_file for each line of input onto the command line.

Or (this is a little more robust and should not care about spaces, but it also needs xargs to work):

while read l; do echo -ne "--action_env\0$l\0"; done < .env \
    | xargs -x0 bazel build //target

This reads each line of input and prints --action_env and the line itself both terminated by a null character. xargs will then run bazel build //target followed by each null separated item (-0) from the previous step as an additional argument. The -x is there to make sure we fail instead of splitting the inputs into multiple bazel invocations if the resulting line was too long (exceeding permissible limits).

But no, bazel does not have a dedicated command line option to read a file of the format you have described (or any for that matter) and use it to define environment for its actions. Generally speaking, such manipulation would appear to have very broad impact and is not entirely likely to be well justifiable. I.e. if you really need to do that and you are sure that is the way to proceed, you need to use another tool, such as shell, to prepare the command line to run bazel or populate the environment in which bazel command is to run.

Upvotes: 2

Related Questions