如何在自定义Bazel规则中始终禁用沙箱且无需用户操作?
How to Disable Sandboxing for All Instances of a Custom Bazel Rule
To ensure sandboxing is always disabled for every instance of your custom Bazel rule—without requiring users to pass any extra flags or attributes—you can bake this requirement directly into your rule's implementation. Here's how to do it:
Step 1: Add Execution Requirements to Rule Actions
When defining the actions in your rule's implementation function, specify the no-sandbox execution requirement. This tells Bazel to skip sandboxing for that action, overriding any global or user-specific sandbox settings.
Example Rule Implementation
def _my_custom_rule_impl(ctx): # Define your rule's action(s) with sandboxing disabled ctx.actions.run( executable = ctx.executable._my_tool, arguments = [ "--input", ctx.file.input.path, "--output", ctx.outputs.output.path ], inputs = [ctx.file.input], outputs = [ctx.outputs.output], # Critical line: Disable sandboxing for this action execution_requirements = {"no-sandbox": ""}, ) return [DefaultInfo(files = depset([ctx.outputs.output]))] # Define the rule itself MyCustomRule = rule( implementation = _my_custom_rule_impl, attrs = { "input": attr.label(mandatory = True, allow_single_file = True), "_my_tool": attr.label( default = Label("//tools:my_tool"), executable = True, cfg = "exec" ), }, outputs = {"output": "%{name}.out"}, )
Why This Works
- The
no-sandboxexecution requirement is a built-in Bazel flag that forces the action to run outside a sandbox. - By including this in the rule's implementation, every instance of
MyCustomRulewill automatically use this setting—users don't need to add--no-sandboxto their build commands or any special attributes when declaring the rule.
Notes
- If your rule uses multiple actions (e.g.,
ctx.actions.run_shell()orctx.actions.run_binary()), add theexecution_requirements={"no-sandbox": ""}parameter to each action to ensure full sandboxing disablement. - This approach is robust because users can't accidentally re-enable sandboxing for the rule without modifying the rule's code itself, which aligns with your goal of no extra user steps.
内容的提问来源于stack exchange,提问作者Kerrick Staley
相关产品推荐
相关产品推荐

