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: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
## Unreleased

Improvements:
* Support `vault-client` agent images with the `vault.hashicorp.com/agent-binary` pod annotation and the injector's `-vault-binary` flag or `AGENT_INJECT_VAULT_BINARY` environment variable. Agent init, sidecar, and token-revoke commands use the selected binary; the default remains `vault`. [GH-928](https://github.com/hashicorp/vault-k8s/pull/928)

## 1.7.7 (October 27, 2026)

Changes:
Expand Down
11 changes: 11 additions & 0 deletions agent-inject/agent/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import (

const (
DefaultVaultImage = "hashicorp/vault:2.2.1"
DefaultVaultBinary = "vault"
DefaultVaultAuthType = "kubernetes"
DefaultVaultAuthPath = "auth/kubernetes"
DefaultAgentRunAsUser = 100
Expand Down Expand Up @@ -53,6 +54,7 @@ type Agent struct {
// ImageName is the name of the Vault image to use for the
// sidecar container.
ImageName string
Binary string

// Containers determine which containers should be injected
Containers []string
Expand Down Expand Up @@ -377,6 +379,7 @@ func New(pod *corev1.Pod) (*Agent, error) {
Annotations: pod.Annotations,
ConfigMapName: pod.Annotations[AnnotationAgentConfigMap],
ImageName: pod.Annotations[AnnotationAgentImage],
Binary: pod.Annotations[AnnotationAgentBinary],
DefaultTemplate: pod.Annotations[AnnotationAgentInjectDefaultTemplate],
LimitsCPU: pod.Annotations[AnnotationAgentLimitsCPU],
LimitsMem: pod.Annotations[AnnotationAgentLimitsMem],
Expand Down Expand Up @@ -736,6 +739,11 @@ func (a *Agent) Patch() ([]byte, error) {
return nil, nil
}

// IsInvalidBinary reports whether binary is not a supported Vault executable name.
func IsInvalidBinary(binary string) bool {
return binary != DefaultVaultBinary && binary != "vault-client"
}

// Validate the instance of Agent to ensure we have everything needed
// for basic functionality.
func (a *Agent) Validate() error {
Expand All @@ -753,6 +761,9 @@ func (a *Agent) Validate() error {
if a.ImageName == "" {
return errors.New("no Vault image found")
}
if IsInvalidBinary(a.binary()) {
return fmt.Errorf("invalid agent binary %q: must be vault or vault-client", a.Binary)
}

if a.ConfigMapName == "" {
if a.Vault.AuthType == "" {
Expand Down
11 changes: 11 additions & 0 deletions agent-inject/agent/annotations.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,10 @@ const (
// AnnotationAgentImage is the name of the Vault docker image to use.
AnnotationAgentImage = "vault.hashicorp.com/agent-image"

// AnnotationAgentBinary selects the executable used to run the injected Agent.
// Supported values are "vault" and "vault-client"; defaults to "vault".
AnnotationAgentBinary = "vault.hashicorp.com/agent-binary"
Comment thread
vijayavelsekar marked this conversation as resolved.
Resolved

// AnnotationAgentRequestNamespace is the Kubernetes namespace where the request
// originated from.
AnnotationAgentRequestNamespace = "vault.hashicorp.com/agent-request-namespace"
Expand Down Expand Up @@ -348,6 +352,7 @@ const (

type AgentConfig struct {
Image string
Binary string
Address string
AuthType string
AuthPath string
Expand Down Expand Up @@ -435,6 +440,12 @@ func Init(pod *corev1.Pod, cfg AgentConfig) error {
}
pod.ObjectMeta.Annotations[AnnotationAgentImage] = cfg.Image
}
if _, ok := pod.ObjectMeta.Annotations[AnnotationAgentBinary]; !ok {
Comment thread
Siddharth-Kannan marked this conversation as resolved.
Resolved
if cfg.Binary == "" {
cfg.Binary = DefaultVaultBinary
}
pod.ObjectMeta.Annotations[AnnotationAgentBinary] = cfg.Binary
}

if _, ok := pod.ObjectMeta.Annotations[AnnotationAgentRequestNamespace]; !ok {
pod.ObjectMeta.Annotations[AnnotationAgentRequestNamespace] = cfg.Namespace
Expand Down
30 changes: 30 additions & 0 deletions agent-inject/agent/annotations_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,36 @@ func basicAgentConfig() AgentConfig {
}
}

func TestAgentBinaryConfiguration(t *testing.T) {
for _, defaultBinary := range []string{"", "vault", "vault-client", "invalid"} {
for _, override := range []string{"unset", "", "vault", "vault-client", "invalid", "vault; echo unsafe", "/bin/vault-client"} {
t.Run(fmt.Sprintf("default=%s/override=%s", defaultBinary, override), func(t *testing.T) {
annotations := map[string]string{AnnotationVaultRole: "foobar"}
want := defaultBinary
if want == "" {
want = DefaultVaultBinary
}
if override != "unset" {
annotations[AnnotationAgentBinary] = override
want = override
}
pod := testPod(annotations)
cfg := basicAgentConfig()
cfg.Binary = defaultBinary
require.NoError(t, Init(pod, cfg))
agent, err := New(pod)
require.NoError(t, err)
assert.Equal(t, want, agent.Binary)
if want == "" || want == "vault" || want == "vault-client" {
require.NoError(t, agent.Validate())
} else {
require.ErrorContains(t, agent.Validate(), "invalid agent binary")
}
})
}
}
}

func TestInitCanSet(t *testing.T) {
annotations := make(map[string]string)
pod := testPod(annotations)
Expand Down
4 changes: 2 additions & 2 deletions agent-inject/agent/container_init_sidecar.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,15 +50,15 @@ func (a *Agent) ContainerInitSidecar() (corev1.Container, error) {
volumeMounts = append(volumeMounts, a.copyVolumeMounts(a.CopyVolumeMounts)...)
}

arg := DefaultContainerArg
arg := defaultContainerArgPrefix + a.binary() + defaultContainerArgSuffix
Comment thread
vijayavelsekar marked this conversation as resolved.
Resolved

if a.ConfigMapName != "" {
volumeMounts = append(volumeMounts, corev1.VolumeMount{
Name: configVolumeName,
MountPath: configVolumePath,
ReadOnly: true,
})
arg = fmt.Sprintf("touch %s && vault agent -config=%s/config-init.hcl", TokenFile, configVolumePath)
arg = fmt.Sprintf("touch %s && %s agent -config=%s/config-init.hcl", TokenFile, a.binary(), configVolumePath)
}

if a.Vault.TLSSecret != "" {
Expand Down
17 changes: 13 additions & 4 deletions agent-inject/agent/container_sidecar.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,9 @@ const (
DefaultResourceLimitMem = "128Mi"
DefaultResourceRequestCPU = "250m"
DefaultResourceRequestMem = "64Mi"
DefaultContainerArg = "echo ${VAULT_CONFIG?} | base64 -d > /home/vault/config.json && vault agent -config=/home/vault/config.json"
defaultContainerArgPrefix = "echo ${VAULT_CONFIG?} | base64 -d > /home/vault/config.json && "
defaultContainerArgSuffix = " agent -config=/home/vault/config.json"
DefaultContainerArg = defaultContainerArgPrefix + DefaultVaultBinary + defaultContainerArgSuffix
DefaultRevokeGrace = 5
DefaultAgentLogLevel = "info"
DefaultAgentLogFormat = "standard"
Expand Down Expand Up @@ -62,15 +64,15 @@ func (a *Agent) ContainerSidecar() (corev1.Container, error) {
volumeMounts = append(volumeMounts, a.copyVolumeMounts(a.CopyVolumeMounts)...)
}

arg := DefaultContainerArg
arg := defaultContainerArgPrefix + a.binary() + defaultContainerArgSuffix

if a.ConfigMapName != "" {
volumeMounts = append(volumeMounts, corev1.VolumeMount{
Name: configVolumeName,
MountPath: configVolumePath,
ReadOnly: true,
})
arg = fmt.Sprintf("touch %s && vault agent -config=%s/config.hcl", TokenFile, configVolumePath)
arg = fmt.Sprintf("touch %s && %s agent -config=%s/config.hcl", TokenFile, a.binary(), configVolumePath)
}

if a.Vault.TLSSecret != "" {
Expand Down Expand Up @@ -209,6 +211,13 @@ func parseQuantity(raw string) (resource.Quantity, error) {
return resource.ParseQuantity(raw)
}

func (a *Agent) binary() string {
if a.Binary == "" {
return DefaultVaultBinary
}
return a.Binary
}

// This should only be run for a sidecar container
func (a *Agent) createLifecycle() corev1.Lifecycle {
lifecycle := corev1.Lifecycle{}
Expand All @@ -219,7 +228,7 @@ func (a *Agent) createLifecycle() corev1.Lifecycle {

lifecycle.PreStop = &corev1.LifecycleHandler{
Exec: &corev1.ExecAction{
Command: []string{"/bin/sh", "-c", fmt.Sprintf("/bin/sleep %d && /bin/vault token revoke %s", a.RevokeGrace, strings.Join(flags[:], " "))},
Command: []string{"/bin/sh", "-c", fmt.Sprintf("/bin/sleep %d && /bin/%s token revoke %s", a.RevokeGrace, a.binary(), strings.Join(flags[:], " "))},
},
}
}
Expand Down
49 changes: 49 additions & 0 deletions agent-inject/agent/container_sidecar_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,55 @@ import (
"k8s.io/apimachinery/pkg/api/resource"
)

func TestAgentBinaryCommands(t *testing.T) {
for _, binary := range []string{"", "vault", "vault-client"} {
for _, configMap := range []string{"", "agent-config"} {
t.Run(fmt.Sprintf("binary=%s/configMap=%s", binary, configMap), func(t *testing.T) {
annotations := map[string]string{
AnnotationVaultRole: "foobar",
AnnotationAgentConfigMap: configMap,
}
if binary != "" {
annotations[AnnotationAgentBinary] = binary
}
pod := testPod(annotations)
require.NoError(t, Init(pod, basicAgentConfig()))
agent, err := New(pod)
require.NoError(t, err)
require.NoError(t, agent.Validate())
wantBinary := binary
if wantBinary == "" {
wantBinary = "vault"
}
for _, init := range []bool{false, true} {
var container corev1.Container
if init {
container, err = agent.ContainerInitSidecar()
} else {
container, err = agent.ContainerSidecar()
}
require.NoError(t, err)
want := fmt.Sprintf("echo ${VAULT_CONFIG?} | base64 -d > /home/vault/config.json && %s agent -config=/home/vault/config.json", wantBinary)
if configMap != "" {
config := "config.hcl"
if init {
config = "config-init.hcl"
}
want = fmt.Sprintf("touch %s && %s agent -config=%s/%s", TokenFile, wantBinary, configVolumePath, config)
}
assert.Equal(t, []string{"/bin/sh", "-ec"}, container.Command)
assert.Equal(t, []string{want}, container.Args)
if init {
assert.Nil(t, container.Lifecycle)
} else {
assert.Equal(t, []string{"/bin/sh", "-c", fmt.Sprintf("/bin/sleep 5 && /bin/%s token revoke -address=http://foobar:8200 -self", wantBinary)}, container.Lifecycle.PreStop.Exec.Command)
}
}
})
}
}
}

func TestContainerSidecarVolume(t *testing.T) {
annotations := map[string]string{
AnnotationVaultRole: "foobar",
Expand Down
2 changes: 2 additions & 0 deletions agent-inject/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ type Handler struct {
VaultNamespace string
ProxyAddress string
ImageVault string
BinaryVault string
Clientset *kubernetes.Clientset
Log hclog.Logger
RevokeOnShutdown bool
Expand Down Expand Up @@ -223,6 +224,7 @@ func (h *Handler) Mutate(req *admissionv1.AdmissionRequest) MutateResponse {
h.Log.Debug("setting default annotations..")
cfg := agent.AgentConfig{
Image: h.ImageVault,
Binary: h.BinaryVault,
Address: h.VaultAddress,
AuthType: h.VaultAuthType,
AuthPath: h.VaultAuthPath,
Expand Down
50 changes: 50 additions & 0 deletions agent-inject/handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,56 @@ func basicHandler() Handler {
}
}

func TestHandlerAgentBinary(t *testing.T) {
for _, defaultBinary := range []string{"", "vault-client"} {
for _, override := range []string{"unset", "vault", "vault-client", "invalid"} {
t.Run(defaultBinary+"/"+override, func(t *testing.T) {
handler := basicHandler()
handler.BinaryVault = defaultBinary
handler.RevokeOnShutdown = true
annotations := map[string]string{
agent.AnnotationAgentInject: "true",
agent.AnnotationVaultRole: "demo",
}
want := defaultBinary
if want == "" {
want = "vault"
}
if override != "unset" {
annotations[agent.AnnotationAgentBinary] = override
want = override
}
pod := corev1.Pod{
ObjectMeta: metav1.ObjectMeta{Annotations: annotations},
Spec: corev1.PodSpec{Containers: []corev1.Container{{
Name: "app",
VolumeMounts: []corev1.VolumeMount{{Name: "serviceaccount", MountPath: "/var/run/secrets/kubernetes.io/serviceaccount"}},
}}},
}
request := admissionv1.AdmissionRequest{Namespace: "default", Object: encodeRaw(t, &pod)}
response := handler.Mutate(&request).Resp
if want == "invalid" {
require.False(t, response.Allowed)
require.Contains(t, response.Result.Message, "invalid agent binary")
return
}
require.True(t, response.Allowed, "%v", response.Result)
patch, err := jsonpatch.DecodePatch(response.Patch)
require.NoError(t, err)
mutated, err := patch.Apply(request.Object.Raw)
require.NoError(t, err)
require.NoError(t, json.Unmarshal(mutated, &pod))
require.Len(t, pod.Spec.InitContainers, 1)
require.Len(t, pod.Spec.Containers, 2)
require.Contains(t, pod.Spec.InitContainers[0].Args[0], "&& "+want+" agent -config=")
sidecar := pod.Spec.Containers[1]
require.Contains(t, sidecar.Args[0], "&& "+want+" agent -config=")
require.Contains(t, sidecar.Lifecycle.PreStop.Exec.Command[2], "&& /bin/"+want+" token revoke ")
})
}
}
}

func TestHandlerHandle(t *testing.T) {
basicSpec := corev1.PodSpec{
InitContainers: []corev1.Container{
Expand Down
Loading
Loading