Practical Bazel: A Simpler Way to Wrap Run Targets
Practical Bazel bazel
Published: 2020-11-20
Practical Bazel: A Simpler Way to Wrap Run Targets

Yesterday, I explained how you can wrap a bazel run target with a sh_binary() to execute arbitrary code both before and after the run target, which is particularly useful for retrieving secrets from a secret management system and passing them to the run target.

If you are passing secrets via environment variables that are retrieved by command-line programs, there’s an even easier way to do it – use the command rule from Atlassian’s bazel-tools repo and its raw_environment attribute.

For example, yesterday’s code can be simplified to:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
# WORKSPACE
load("@bazel_tools//tools/build_defs/repo:git.bzl", "git_repository")

git_repository(
    name = "com_github_atlassian_bazel_tools",
    # TODO: Change this from a branch reference to a specific commit and
    # shallow_since
    branch = "master",
    remote = "https://github.com/atlassian/bazel-tools.git",
)

load("@com_github_atlassian_bazel_tools//multirun:deps.bzl", "multirun_dependencies")
multirun_dependencies()
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
# BUILD
load("@com_github_atlassian_bazel_tools//multirun:def.bzl", "command")

my_push(
    name = "my_push",
    ...
)

command(
    name = "authenticated_my_push",
    environment = {
        "MY_PUSH_USERNAME": "foo",
    },
    raw_environment = {
        "MY_PUSH_PASSWORD": "$(az keyvault secret show \
            --name 'secret_name' --vault-name 'vault_name' \
            --query 'value' -o tsv)",
    },
)

You can then perform an authenticated push using bazel run //:authenticated_my_push.