Goal
Inject custom sidecar containers into Kubernetes agent script pods during execution.
Prerequisites
- Access to the Kubernetes cluster where the Octopus Kubernetes agent is deployed.
-
kubectlconfigured with permissions to create and apply Mutating Admission Policies and bindings. - Basic understanding of Kubernetes admission policies and pod injection.
Steps
-
Be Aware of the Design Limitation: Direct sidecar injection via Helm chart values (e.g.,
scriptPods.podTemplate.podSpec.containersorextraContainers) is unsupported by design. The Kubernetes agent manages thescriptContainerSpecandwatchdogContainerSpecinternally to ensure reliable script execution. - Implement a Kubernetes Mutating Admission Policy: Use a cluster-level mutating policy to inject sidecar configurations at the pod creation level, bypassing the Helm chart limitations.
-
Configure the Policy and Binding: Create a
MutatingAdmissionPolicyand corresponding binding that targets the namespace where script pods are created. An example configuration can be found directly below these steps. -
Apply the Configuration: Deploy the policy and binding to your cluster via
kubectl. The mutating policy will automatically inject the specified sidecar container into matching script pods at runtime.
Example Configuration:
apiVersion: admissionregistration.k8s.io/v1
kind: MutatingAdmissionPolicy
metadata:
name: "octopus-script-pod-sidecar"
spec:
failurePolicy: Ignore
matchConstraints:
namespaceSelector:
matchExpressions:
- key: kubernetes.io/metadata.name
operator: In
values:
- EXAMPLE-KUBERNETES-AGENT-NAMESPACE
resourceRules:
- apiGroups: [""]
apiVersions: ["v1"]
operations: ["CREATE"]
resources: ["pods"]
matchConditions:
- name: is-octopus-script-pod
expression: >
has(object.metadata.labels) &&
"octopus.com/scriptTicketId" in object.metadata.labels
- name: not-already-injected
expression: >
!has(object.spec.initContainers) ||
!object.spec.initContainers.exists(ic, ic.name == 'my-sidecar')
reinvocationPolicy: IfNeeded
mutations:
- patchType: "ApplyConfiguration"
applyConfiguration:
expression: >
Object{
spec: Object.spec{
initContainers: [
Object.spec.initContainers{
name: "my-sidecar",
image: "EXAMPLE-IMAGE",
restartPolicy: "Always"
}
]
}
}
---
apiVersion: admissionregistration.k8s.io/v1
kind: MutatingAdmissionPolicyBinding
metadata:
name: "octopus-script-pod-sidecar-binding"
spec:
policyName: "octopus-script-pod-sidecar"
Verify
- Trigger a deployment step that runs on the Kubernetes agent, using a longer-running deployment step (e.g., a
sleepstep). - Inspect the running script pod using
kubectl get podsandkubectl describe [pod-name]in the target namespace. - Confirm that your custom sidecar container is present alongside the standard
scriptContainerSpecandwatchdogContainerSpeccontainers.