gatekeeper
gatekeeper copied to clipboard
Not able to put multiple conditions in rego.
I have use case where i want for a specific container name, it should run as root, I have following rego code for this but it is not working as expected.
apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata:
name: k8sallowedcontainers
annotations:
description: >-
Requires container names to begin with a string from the specified list.
spec:
crd:
spec:
names:
kind: K8sAllowedcontainers
validation:
# Schema for the `parameters` field
openAPIV3Schema:
type: object
properties:
privcontainers:
description: The list of prefixes a container name is allowed to have.
type: array
items:
type: string
targets:
- target: admission.k8s.gatekeeper.sh
rego: |
package k8sallowedcontainers
violation[{"msg": msg}] {
container := input.review.object.spec.containers[_]
satisfied := [good | repo = input.parameters.privcontainers[_] ; good = startswith(container.name, repo)]
not any(satisfied); container.securityContext.runAsUser == 0
msg := "container <%v> has an invalid name repo <%v>, allowed repos are %v"
}
```
The following rego should work:
package k8sallowedcontainers
violation[{"msg": msg}] {
container := input.review.object.spec.containers[_]
repo := input.parameters.privcontainers[_]
startswith(container.name, repo)
container.securityContext.runAsUser != 0
msg := sprintf("container <%v> is not running as root", [container.name])
}
Hi @chewong Thank you for the reply but this does not seem to work i applied this code,
Constraint :
kind: K8sAllowedcontainers
metadata:
name: repo-is-container
spec:
match:
kinds:
- apiGroups: [""]
kinds: ["Pod"]
parameters:
privcontainers:
- "nginx"
I was able to able the following Yaml which is not expected,
kind: Pod
metadata:
name: nginx
labels:
env: test
spec:
securityContext:
runAsUser: 10
containers:
- name: feedback
image: nginxs
securityContext:
runAsUser: 10
@chewong Could you help me with this?
Can you try the following YAML:
kind: K8sAllowedcontainers
apiVersion: constraints.gatekeeper.sh/v1beta1
metadata:
name: repo-is-container
spec:
match:
kinds:
- apiGroups: [""]
kinds: ["Pod"]
parameters:
privcontainers:
- "nginx"
@chewong Its not working!!
Example has the container name nginxs
, but constraint lists nginx
, does that change things?
nvm "startswith" is satisfied
in @chewong 's example, change startswith(container.name, repo)
to startswith(container.image, repo)
Got it Thanks @maxsmythe
This issue has been automatically marked as stale because it has not had recent activity. It will be closed in 14 days if no further activity occurs. Thank you for your contributions.
This issue has been automatically marked as stale because it has not had recent activity. It will be closed in 14 days if no further activity occurs. Thank you for your contributions.
Closing, looks like the question has been answered. If not, please feel free to re-open the issue.