Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion .bcr/presubmit.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,16 @@
bcr_test_module:
module_path: "."
matrix:
platform: ["macos_arm64", "ubuntu2004", "windows"]
platform: ["macos_arm64", "ubuntu2404", "windows"]
bazel: ["7.x", "8.x", "9.x"]
tasks:
run_tests:
name: "Run test module"
platform: ${{ platform }}
bazel: ${{ bazel }}
build_targets:
- "--"
- "//..."
test_targets:
- "--"
- "//..."
16 changes: 16 additions & 0 deletions docs/src/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,22 @@ kubectl_binary(
bazel run //deploy:apply -- --namespace my-namespace
```

`kubectl` accepts flags ahead of the verb, so `args` can fix the file a command
operates on while leaving the verb to the caller:

```python
kubectl_binary(
name = "kubectl",
args = ["--filename=$(rlocationpath :manifests)"],
data = [":manifests"],
)
```

```bash
bazel run //deploy:kubectl -- diff
bazel run //deploy:kubectl -- apply --server-side
```

`env` takes the same references, for example to point `KUBECONFIG` at a file in
the repository. Clusters, contexts and namespaces stay in your hands.

Expand Down
17 changes: 17 additions & 0 deletions kubectl/private/kubectl_binary.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,23 @@ def kubectl_binary(name, args = [], data = [], env = {}, kubectl = None, **kwarg
bazel run //deploy:apply -- --namespace my-namespace
```

`kubectl` accepts flags ahead of the verb, so `args` can fix the file a \
command operates on while leaving the verb to the caller. Only positional \
arguments have to follow the verb:

```python
kubectl_binary(
name = "kubectl",
args = ["--filename=$(rlocationpath :manifests)"],
data = [":manifests"],
)
```

```bash
bazel run //deploy:kubectl -- diff
bazel run //deploy:kubectl -- apply --server-side
```

Nothing about clusters, contexts or namespaces is decided here; that is \
left to the arguments and the environment.

Expand Down
23 changes: 20 additions & 3 deletions tests/BUILD.bazel
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
load("@rules_go//go:def.bzl", "go_test")
load("@rules_shell//shell:sh_test.bzl", "sh_test")
load("//kubectl:defs.bzl", "kubectl_binary")

Expand Down Expand Up @@ -113,17 +114,33 @@ kubectl_binary(
env = {"KUBECONFIG": "$(rlocationpath kubeconfig.yaml)"},
)

sh_test(
# `kubectl_binary` with a generated manifest but no verb, which the caller
# supplies on the command line.
genrule(
name = "manifest",
outs = ["manifest.yaml"],
cmd = "printf 'apiVersion: v1\\nkind: ConfigMap\\nmetadata:\\n name: manifest-test\\n' > $@",
)

kubectl_binary(
name = "manifest_kubectl",
args = ["--filename=$(rlocationpath :manifest)"],
data = [":manifest"],
)

go_test(
name = "binary_test",
size = "small",
srcs = ["binary_test.sh"],
srcs = ["binary_test.go"],
data = [
":config_view",
":configmap_dry_run",
":manifest_kubectl",
],
env = {
"CONFIGMAP_DRY_RUN": "$(rlocationpath :configmap_dry_run)",
"CONFIG_VIEW": "$(rlocationpath :config_view)",
"MANIFEST_KUBECTL": "$(rlocationpath :manifest_kubectl)",
},
deps = ["@bazel_tools//tools/bash/runfiles"],
deps = ["@rules_go//go/runfiles"],
)
128 changes: 128 additions & 0 deletions tests/binary_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
// Checks that `kubectl_binary` wires generated files, environment and extra
// arguments through to kubectl, from any working directory.
package tests

import (
"os"
"os/exec"
"path/filepath"
"strings"
"testing"

"github.com/bazelbuild/rules_go/go/runfiles"
)

// binaries holds the `kubectl_binary` targets under test, resolved through
// runfiles from the rlocationpaths in the test environment.
type binaries struct {
configmapDryRun string
configView string
manifestKubectl string
// env is passed to every binary: the test's environment with runfiles
// variables for the launcher, a scratch HOME and no kubeconfig, so the
// tests are independent of anything on the host.
env []string
// elsewhere is a directory with nothing in it, used as the working
// directory to show that generated files are found through runfiles.
elsewhere string
}

func setup(t *testing.T) *binaries {
t.Helper()

r, err := runfiles.New()
if err != nil {
t.Fatalf("failed to locate runfiles: %v", err)
}
locate := func(variable string) string {
path, err := r.Rlocation(os.Getenv(variable))
if err != nil {
t.Fatalf("failed to locate %s: %v", variable, err)
}
return path
}

tmp := t.TempDir()
home := filepath.Join(tmp, "home")
elsewhere := filepath.Join(tmp, "elsewhere")
for _, dir := range []string{home, elsewhere} {
if err := os.Mkdir(dir, 0o755); err != nil {
t.Fatal(err)
}
}

env := append(os.Environ(), r.Env()...)
env = append(env, "HOME="+home, "KUBECONFIG=", "BUILD_WORKING_DIRECTORY=")

return &binaries{
configmapDryRun: locate("CONFIGMAP_DRY_RUN"),
configView: locate("CONFIG_VIEW"),
manifestKubectl: locate("MANIFEST_KUBECTL"),
env: env,
elsewhere: elsewhere,
}
}

// run executes a binary from `elsewhere` and returns its combined output.
func (b *binaries) run(t *testing.T, binary string, extraEnv []string, args ...string) (string, error) {
t.Helper()
cmd := exec.Command(binary, args...)
cmd.Dir = b.elsewhere
cmd.Env = append(append([]string{}, b.env...), extraEnv...)
output, err := cmd.CombinedOutput()
return strings.TrimSpace(string(output)), err
}

func (b *binaries) mustRun(t *testing.T, binary string, extraEnv []string, args ...string) string {
t.Helper()
output, err := b.run(t, binary, extraEnv, args...)
if err != nil {
t.Fatalf("%s %s failed: %v\n%s", filepath.Base(binary), strings.Join(args, " "), err, output)
}
return output
}

func TestKubectlBinary(t *testing.T) {
b := setup(t)

t.Run("a generated file referenced with $(rlocationpath) is found from another directory", func(t *testing.T) {
output := b.mustRun(t, b.configmapDryRun, []string{"BUILD_WORKING_DIRECTORY=" + b.elsewhere})
for _, want := range []string{"name: binary-test", "generated by bazel"} {
if !strings.Contains(output, want) {
t.Errorf("expected %q in the output, got:\n%s", want, output)
}
}
})

t.Run("arguments on the command line are appended", func(t *testing.T) {
output := b.mustRun(t, b.configmapDryRun, nil, "--namespace=appended")
if !strings.Contains(output, "namespace: appended") {
t.Errorf("expected the namespace from the command line, got:\n%s", output)
}
})

t.Run("env is set for kubectl", func(t *testing.T) {
output := b.mustRun(t, b.configView, nil)
if want := "https://binary-test.invalid:6443"; output != want {
t.Errorf("expected the server from the generated kubeconfig %q, got: %q", want, output)
}
})

t.Run("kubectl takes a configured flag ahead of a verb given on the command line", func(t *testing.T) {
// `--local` keeps kubectl off the network, which the sandbox has none of.
output := b.mustRun(t, b.manifestKubectl, nil, "label", "--local", "--dry-run=client", "--output=name", "checked=yes")
if want := "configmap/manifest-test"; output != want {
t.Errorf("expected the manifest to be labelled as %q, got: %q", want, output)
}
})

t.Run("a verb that takes no file rejects the flag", func(t *testing.T) {
output, err := b.run(t, b.manifestKubectl, nil, "version", "--client")
if err == nil {
t.Fatalf("expected kubectl to reject --filename for 'version', got:\n%s", output)
}
if !strings.Contains(output, "unknown flag: --filename") {
t.Errorf("expected an unknown flag error, got:\n%s", output)
}
})
}
43 changes: 0 additions & 43 deletions tests/binary_test.sh

This file was deleted.

Loading