|
| 1 | +#!/bin/bash |
| 2 | + |
| 3 | +# kubectl test allows for testing resources in your cluster using Open Policy Agent |
| 4 | +# It uses the conftest utility and expects to find associated policy files in |
| 5 | +# a directory called policy |
| 6 | + |
| 7 | + |
| 8 | +# Check if a specified command exists on the path and is executable |
| 9 | +function check_command () { |
| 10 | + if ! [[ -x $(command -v $1) ]] ; then |
| 11 | + echo "$1 not installed" |
| 12 | + exit 1 |
| 13 | + fi |
| 14 | +} |
| 15 | + |
| 16 | +function usage () { |
| 17 | + echo "A Kubectl plugin for using Conftest to test objects in Kubernetes using Open Policy Agent" |
| 18 | + echo |
| 19 | + echo "See https://github.com/instrumenta/conftest for more information" |
| 20 | + echo |
| 21 | + echo "Usage:" |
| 22 | + echo " kubectl test (TYPE[.VERSION][.GROUP] [NAME] | TYPE[.VERSION][.GROUP]/NAME)" |
| 23 | +} |
| 24 | + |
| 25 | +# Check the required commands are available on the PATH |
| 26 | +check_command "conftest" |
| 27 | +check_command "kubectl" |
| 28 | + |
| 29 | + |
| 30 | +if [[ ($# -eq 0) || ($1 == "--help") ]]; then |
| 31 | + # No commands or the --help flag passed and we'll show the usage instructions |
| 32 | + usage |
| 33 | +elif [[ ($# -eq 1) && $1 =~ ^[a-z\.]+$ ]]; then |
| 34 | + # If we have one argument we get the list of objects from kubectl |
| 35 | + # parse our the individual items and then pass those one by one into conftest |
| 36 | + check_command "jq" |
| 37 | + if output=$(kubectl get $1 $2 -o json); then |
| 38 | + echo $output | jq -cj '.items[] | tostring+"\u0000"' | xargs -n1 -0 -I@ bash -c "echo '@' | conftest test -" |
| 39 | + fi |
| 40 | +elif [[ ($# -eq 1 ) ]]; then |
| 41 | + # Support the / variant for getting an individual resource |
| 42 | + if output=$(kubectl get $1 -o json); then |
| 43 | + echo $output | conftest test - |
| 44 | + fi |
| 45 | +elif [[ ($# -eq 2 ) && $1 =~ ^[a-z]+$ ]]; then |
| 46 | + # if we have two arguments then we assume the first is the type and the second the resource name |
| 47 | + if output=$(kubectl get $1 $2 -o json); then |
| 48 | + echo $output | conftest test - |
| 49 | + fi |
| 50 | +else |
| 51 | + echo "Please check the arguments to kubectl test" |
| 52 | + echo |
| 53 | + usage |
| 54 | + exit 1 |
| 55 | +fi |
0 commit comments