Skip to content

Instantly share code, notes, and snippets.

View makocchi-git's full-sized avatar
:octocat:
(^ω^)

makocchi makocchi-git

:octocat:
(^ω^)
View GitHub Profile
$ conftest test sample.yaml
FAIL - sample.yaml - sample in the Deployment makocchi/docker-nginx-hostname has an image, sample-deployment, using the latest tag
1 test, 0 passed, 0 warnings, 1 failure
@makocchi-git
makocchi-git / sample.rego
Last active June 8, 2020 05:21
Validate your Kubernetes manifests with Conftest in the GitHub Actions
package main
import data.lib.kubernetes
violation[msg] {
kubernetes.containers[container]
[image_name, "latest"] = kubernetes.split_image(container.image)
msg = kubernetes.format(sprintf("%s in the %s %s has an image, %s, using the latest tag", [container.name, kubernetes.kind, image_name, kubernetes.name]))
}
name: Pull Request Check
on: [pull_request]
jobs:
validation:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: validate manifests in dir1 and dir2
$ kubeval invalid-deployment2.yaml
PASS - invalid-deployment2.yaml contains a valid Deployment

# --strict を付けることで WARN になる
$ kubeval --strict invalid-deployment2.yaml
WARN - invalid-deployment2.yaml contains an invalid Deployment - location: Additional property location is not allowed
apiVersion: apps/v1
kind: Deployment
metadata:
name: invalid-deployment
spec:
replicas: 1
selector:
matchLabels:
app: example
template:
$ kubeval valid-deployment.yaml
PASS - valid-deployment.yaml contains a valid Deployment

$ echo $?
0
$ kubeval invalid-deployment.yaml
WARN - invalid-deployment.yaml contains an invalid Deployment - spec.replicas: Invalid type. Expected: [integer,null], given: string
WARN - invalid-deployment.yaml contains an invalid Deployment - port: Additional property port is not allowed

$ echo $?
1
$ kubectl apply --validate --dry-run -f invalid-deployment.yaml
error: error validating "invalid-deployment.yaml": error validating data: [ValidationError(Deployment.spec.replicas): invalid type for io.k8s.api.apps.v1.DeploymentSpec.replicas: got "string", expected "integer", ValidationError(Deployment.spec.template.spec.containers[0]): unknown field "port" in io.k8s.api.core.v1.Container]; if you choose to ignore these errors, turn validation off with --validate=false
apiVersion: apps/v1
kind: Deployment
metadata:
name: invalid-deployment
spec:
replicas: "1"
selector:
matchLabels:
app: example
template:
                                                                                                      [47