9

I am building my Java project with Bazel. I want to use environment variables at build/run time. According to the documentation --action_env=APP_ENV=Development should work.

So I do bazel run myproject:app --action_env=APP_ENV=Development

But System.getenv("APP_ENV"); is null

In my IntelliJ IDE, I have the following. Neither --action_env=APP_ENV=Development nor --action_env APP_ENV=Development work.

Using IntelliJ

Did I get something wrong here?

Dmitriy Popov
  • 2,150
  • 3
  • 25
  • 34
flexxxit
  • 2,440
  • 5
  • 42
  • 69
  • https://github.com/bazelbuild/intellij/issues might be a better place to ask. Plug-in developer may need to provide the environment variable options to the run configuration like many other configurations in the IDE already do. – CrazyCoder Aug 13 '18 at 20:00
  • @CrazyCoder But how do i do this on the cli. `bazel run myproject:app --action_env=APP_ENV=Development` does not work – flexxxit Aug 14 '18 at 10:10

3 Answers3

14

You can use --run_under to add a prefix to the Bazel run command. This can be used in the IntelliJ Run/Debug configuration to set environment variables.

--run_under='export VAR1=FOO VAR2=BAR && '
Dane White
  • 3,443
  • 18
  • 16
1

Launch Intellij from a terminal so it has the environment variables that it needs during bazel sync (build) and bazel run.

On MacOS, use the open command to launch it.

$ export POSTGRES_USER=dev_user
$ open -a "IntelliJ IDEA CE"
$

Bazel will only pass variables to the build processes if you provide them on the command line:

$ bazel build --action_env=POSTGRES_USER //...

Or specify them in .bazelrc:

build --action_env=POSTGRES_USER
M. Leonhard
  • 1,332
  • 1
  • 18
  • 20
0

The current version of the Intellij bazel plugin allows you to specify a bazel binary. You can take advantage of this to add specific environment variables per run configuration.

Let's say you want to add the following to the runtime environment:

VAR1=VAL1
VAR2=VAL2

Then create a file called say bazel_custom with the following contents (replace /path/to/bazel with the correct path to bazel):

#!/usr/bin/env bash

export VAR1=VAL1
export VAR2=VAL2

/path/to/bazel "$@"

Save the file and mark it as executable: chmod +x bazel_custom

Then edit your Intellij bazel run configuration and set the path to the task-specific bazel binary to /path/to/bazel_custom.