Created
December 3, 2019 22:47
-
-
Save bdrupieski/f679d1c18cce7b240656a8cd4c7d47c3 to your computer and use it in GitHub Desktop.
delete unbound persistent volume claims
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
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