Skip to content

Instantly share code, notes, and snippets.

@bdrupieski
Created December 3, 2019 22:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bdrupieski/f679d1c18cce7b240656a8cd4c7d47c3 to your computer and use it in GitHub Desktop.
Save bdrupieski/f679d1c18cce7b240656a8cd4c7d47c3 to your computer and use it in GitHub Desktop.
delete unbound persistent volume claims
using System;
using System.Linq;
using System.Threading.Tasks;
using k8s;
namespace KubeStuff
{
class Program
{
static async Task Main(string[] args)
{
var config = new KubernetesClientConfiguration { Host = "http://127.0.0.1:8001" };
var client = new Kubernetes(config);
await DeleteUnboundPersistentVolumeClaimsForNamespace(client);
}
private static async Task DeleteUnboundPersistentVolumeClaimsForNamespace(Kubernetes client)
{
var namespaces = await client.ListNamespaceAsync();
foreach (var ns in namespaces.Items)
{
await DeleteUnboundPersistentVolumeClaimsForNamespace(client, ns.Metadata.Name);
}
}
private static async Task DeleteUnboundPersistentVolumeClaimsForNamespace(Kubernetes client, string targetNamespace)
{
var pods = await client.ListNamespacedPodAsync(targetNamespace);
var pvcs = await client.ListNamespacedPersistentVolumeClaimAsync(targetNamespace);
var allPvcs = pvcs.Items
.Select(x => x.Metadata.Name)
.ToHashSet();
var boundPvcs = pods.Items
.Where(x => x.Spec?.Volumes != null)
.SelectMany(x => x.Spec.Volumes)
.Select(x => x.PersistentVolumeClaim?.ClaimName)
.Where(x => !String.IsNullOrWhiteSpace(x))
.ToHashSet();
var unboundPvcs = allPvcs.Except(boundPvcs).ToList();
foreach (var unboundPvc in unboundPvcs)
{
await client.DeleteNamespacedPersistentVolumeClaimAsync(unboundPvc, targetNamespace);
Console.WriteLine(unboundPvc);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment