Last active
June 2, 2023 16:45
-
-
Save moio/2c9a58cba986a5c771a08de0343d8ced to your computer and use it in GitHub Desktop.
Script to trim Helm's history
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
# encoding: UTF-8 | |
# Prints kubectl commands to trim Helm history in excess of the parameter below | |
# Assumes the default Helm history storage (Secrets) | |
HISTORY_ENTRIES_TO_RETAIN = 2 | |
namespaces = `kubectl get ns -o name` | |
.split | |
.map do |namespace| | |
namespace.delete_prefix("namespace/") | |
end | |
secrets = namespaces.map do |namespace| | |
`kubectl get secret --namespace #{namespace} -o name` | |
.split | |
.map do |name| | |
if name =~ /^secret\/(sh\.helm\.release\.v1\..+)\.v([0-9]+)$/ | |
{ namespace: namespace, base_name: $1, name: $1 + ".v" + $2, version: $2.to_i } | |
else | |
nil | |
end | |
end.compact | |
end.flatten | |
secrets_to_drop = secrets.group_by do |secret| | |
secret[:namespace] + "/" + secret[:base_name] | |
end.map do |group_key, group_values| | |
sorted = group_values.sort_by do |secret| | |
secret[:version] | |
end.reverse | |
sorted[HISTORY_ENTRIES_TO_RETAIN..-1] | |
end.compact.flatten | |
secrets_to_drop.each do |secret| | |
puts "kubectl delete secret --namespace #{secret[:namespace]} #{secret[:name]}" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment