Héctor Valls
Héctor Valls

Reputation: 26094

How to pass variables to Bazel target build?

I am trying to build a Docker image with this code:

container_image(
    name = "docker_image",
    base = "@java_base//image",
    files = [":executable_deploy.jar"],
    cmd = ["java", "-jar", "executable_deploy.jar"],
    env = { "VERSION" : "$(VERSION)" }
)

I want to pass a variable to the target built so it can be replaced in $(VERSION). Is this possible?

I have tried with VERSION=1.0.0 bazel build :docker_image, but I get an error:

$(VERSION) not defined.

How can I pass that variable?

According docs:

The values of this field (env) support make variables (e.g., $(FOO)) and stamp variables; keys support make variables as well. But I don't understand exactly what that means.

Upvotes: 5

Views: 13680

Answers (1)

Matt Mackay
Matt Mackay

Reputation: 1329

Those variables can be set via the --define flag.

There is a section on the rules_docker page about stamping which covers this.

Essentially you can do something like: bazel build --define=VERSION=1.0.0 //:docker_image

It is also possible to source these key / value pairs from the stable-status.txt and volatile-status.txt files. The user manual page for bazel shows how to use these files, and the use of the --workspace_status_command to populate them.

For setting defaults, you could use a .bazelrc file, with something like the following as the contents:

build --define=VERSION=0.0.0-PLACEHOLDER

The flags passed on the command line will take precedence over those in the .bazelrc file.

It's worth mentioning, that changing define values will cause bazel to analyze everything again, which depending on the graph may take some time, but only affected actions will be executed.

Upvotes: 5

Related Questions