Tips and Tricks: Fetch K8S Resources

Monday, Oct 4, 2021 17:00 · 231 words · 2 minutes read

Tips and Tricks

  1. K8S Context Commands
  2. Manually Allocate Elasticsearch Shards
  3. Switch K8S Namespace
  4. Tail Logs in K8S

this blog post will be updated in the future with different scenarios

Overview

In this blog post I will demonstrate how to fetch K8S resources based on different criteria.

Select resources older than X time

Problem: I would like to list all statefulsets created more than 20 days ago

# the time is in seconds 1728000 seconds are 20 days
kubectl get statefulsets -o json | jq -r "[.items[] | {name: .metadata.name, startTime: .metadata.creationTimestamp | fromdate } | select(.startTime < (now | . - 1728000))]" | jq -r ".[].name"
Output:
mongo
redis

Problem: I would like to delete all namespaces older than 48 hours

# the time is in seconds 172800 seconds are 48 hours
kubectl get ns -o json | jq -r "[.items[] | {name: .metadata.name, startTime: .metadata.creationTimestamp | fromdate } | select(.startTime < (now | . - 172800))]" | jq -r ".[].name" | grep "build" | awk '{system("kubectl delete ns --force --grace-period=0 " $1)}'
warning: Immediate deletion does not wait for confirmation that the running resource has been terminated. The resource may continue to run on the cluster indefinitely.
namespace "testable38be9171-6078-4611-8471-96f88e179298" force deleted
warning: Immediate deletion does not wait for confirmation that the running resource has been terminated. The resource may continue to run on the cluster indefinitely.
namespace "testable0d6abfc9-b647-4de5-a2b1-732c343e2dfe" force deleted
comments powered by Disqus

Buy Me A Coffee