I would like to create a cron job which selects the name kubernetes secrets from a given type (e.g kubernetes.io/tls) older than 29 days.
I tried these 2 ways:
1 - Using grep:
kubectl get secrets --all-namespaces| grep kubernetes.io/tls
cicd devkins.infra.mydomain.ninja.tls kubernetes.io/tls 2 14d
cust-ao-xmas cust-ao-xmas.infra.mydomain.ninja.tls kubernetes.io/tls 2 1h
dev dev.mydomain.com.tls kubernetes.io/tls 2 4h
logging graylog.infra.mydomain.ninja.tls kubernetes.io/tls 2 10d
2 Using jsonpath
kubectl get secrets --all-namespaces -o jsonpath='{range .items[?(@.type=="kubernetes.io/tls")]}[{.metadata.namespace},{.metadata.name},{.metadata.creationTimestamp}]{"\n"}{end}'
[cicd,devkins.infra.mydomain.ninja.tls,2017-12-13T22:57:02Z]
[cust-ao-xmas,cust-ao-xmas.infra.mydomain.ninja.tls,2017-12-28T03:13:32Z]
[dev,dev.mydomain.com.tls,2017-12-28T00:59:10Z]
[logging,graylog.infra.mydomain.ninja.tls,2017-12-17T22:23:38Z]
Both of them return the answers but make it extremely hard to parse
Is there a better way to achieve this?
Both of them return the answers but make it extremely hard to parse
If you mean parsing the output, then kubectl --output=json
or --output=yaml
will likely get you much further toward your goal. I see that you already discovered jsonpath
, but I find its syntax crazy hard to remember or work with, versus --output=json
can go into jq
or python
or a thousand other fun tools that work with a standard text format
If you absolutely have to stay within kubectl
, then using golang text/template is almost certainly more powerful, and arguably easier to read, but at the expense of verbosity
This is what I use... There is probably better way of doing it, but works for my case (secrets older than 24hrs).
kubectl get secrets -o json | jq -r "[.items[] | {name: .metadata.name, startTime: .metadata.creationTimestamp | fromdate } | select(.startTime < (now | . - 86400))]" | jq -r ".[].name"