I am trying to use a heredoc to create a resource in Kubernetes as follows:
cat <<EOF | kubectl apply -f -
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: max-pods
spec:
validationFailureAction: audit
background: false
rules:
- name: restrict-pod-count
match:
resources:
kinds:
- Pod
context:
- name: podcounts
apiCall:
urlPath: "/api/v1/pods"
jmesPath: "items[?spec.nodeName=='minikube'] | length(@)"
preconditions:
any:
- key: "{{ request.operation }}"
operator: Equals
value: "CREATE"
validate:
message: "A maximum of 10 Pods are allowed on the Node `minikube`"
deny:
conditions:
any:
- key: "{{ podcounts }}"
operator: GreaterThan
value: 10
EOF
If I write the YAML in a file and run kubectl apply -f file.yaml
, it works as intended. But when I use it as shown above, it says:
error: error parsing STDIN: error converting YAML to JSON: yaml: line 69: did not find expected '-' indicator
I am not extremely familiar with heredocs, so there should be something I am missing, but the error does not help me (the file does not have 69 lines...)
Your validate.message contains an expression that would be expanded in the heredocs. You need to escape that like this:
[...]
message: "A maximum of 10 Pods are allowed on the Node \`minikube\`"
[...]
You could also use the heredoc delimiter with single quotes to disable the expansion. With that you could use your original version.
cat <<'EOF' | kubectl apply -f -
[...]
EOF