Skip to content

Commit

Permalink
added verbose option
Browse files Browse the repository at this point in the history
Signed-off-by: PixelRobots <22979170+PixelRobots@users.noreply.github.com>
  • Loading branch information
PixelRobots committed Sep 25, 2024
1 parent 5f6a2bc commit 5d7deff
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 19 deletions.
2 changes: 1 addition & 1 deletion KubeTidy.psd1
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
RootModule = 'KubeTidy.psm1'

# Version number of this module.
ModuleVersion = '0.0.6'
ModuleVersion = '0.0.7'

# Supported PSEditions
# CompatiblePSEditions = @()
Expand Down
44 changes: 27 additions & 17 deletions KubeTidy.psm1
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,8 @@
.PARAMETER Force
Forces cleanup even if no clusters are reachable. Defaults to false.
.NOTES
Script Name: KubeTidy
Author: Richard Hooper
Version: 0.6
.EXAMPLE
Invoke-KubeTidyCleanup -KubeConfigPath "$HOME\.kube\config" -ExclusionList "aks-prod-cluster,aks-staging-cluster""
.PARAMETER Verbose
Enables verbose logging for detailed output.
#>

[CmdletBinding()]
Expand All @@ -40,36 +35,43 @@ $ExclusionArray = $ExclusionList -split ',' | ForEach-Object { $_.Trim() }

# Function to create a backup of the kubeconfig file
function New-Backup {
[CmdletBinding()]
param (
[string]$KubeConfigPath
)
$backupPath = "$KubeConfigPath.bak_$(Get-Date -Format 'yyyyMMdd_HHmmss')"
Copy-Item -Path $KubeConfigPath -Destination $backupPath
Write-Host "Backup created at $backupPath" -ForegroundColor Green
Write-Verbose "Backup of KubeConfig created at path: $backupPath"
}

# Function to check if a cluster is reachable using HTTPS request
function Test-ClusterReachability {
[CmdletBinding()]
param (
[string]$ClusterServer
)
try {
Write-Verbose "Testing reachability for cluster server: $ClusterServer"
$response = Invoke-WebRequest -Uri $ClusterServer -UseBasicParsing -TimeoutSec 5 -SkipCertificateCheck -ErrorAction Stop
Write-Verbose "Cluster $ClusterServer is reachable."
return $true
}
catch {
if ($_.Exception.Response) {
Write-Verbose "Cluster $ClusterServer is reachable but returned an error (e.g., 401 Unauthorized)."
return $true # Server is reachable but returned an error like 401
}
else {
Write-Host "Cluster $ClusterServer is unreachable."
Write-Verbose "Cluster $ClusterServer is unreachable due to error: $($_.Exception.Message)"
return $false
}
}
}

# Main Cleanup Function
function Invoke-KubeTidyCleanup {
[CmdletBinding()]
param (
[string]$KubeConfigPath,
[array]$ExclusionArray,
Expand All @@ -79,20 +81,19 @@ function Invoke-KubeTidyCleanup {
# Ensure that the $KubeConfigPath is valid
if (-not $KubeConfigPath) {
$homePath = [System.Environment]::GetFolderPath("UserProfile")
Write-Host "No KubeConfig path provided. Using default: $homePath\.kube\config" -ForegroundColor Yellow
Write-Verbose "No KubeConfig path provided. Using default: $homePath\.kube\config"
$KubeConfigPath = "$homePath\.kube\config"
}

# Check if the powershell-yaml module is installed; if not, install it
if (-not (Get-Module -ListAvailable -Name powershell-yaml)) {
Write-Host "powershell-yaml module not found. Installing powershell-yaml..."
Write-Verbose "powershell-yaml module not found. Installing powershell-yaml..."
Install-Module -Name powershell-yaml -Force -Scope CurrentUser
}

# Import the powershell-yaml module to ensure it's loaded
Import-Module powershell-yaml -ErrorAction Stop
Write-Host "powershell-yaml module loaded successfully."

Write-Verbose "powershell-yaml module loaded successfully."

# Display ASCII art and start message
Write-Host ""
Expand All @@ -107,42 +108,48 @@ function Invoke-KubeTidyCleanup {
Write-Host ""

# Read kubeconfig file
Write-Verbose "Reading KubeConfig from $KubeConfigPath"
$kubeConfigContent = Get-Content -Raw -Path $KubeConfigPath
$kubeConfig = $kubeConfigContent | ConvertFrom-Yaml

# Backup original file before cleanup
if ($Backup) {
Write-Verbose "Creating a backup of the KubeConfig file."
New-Backup -KubeConfigPath $KubeConfigPath
}

$removedClusters = @()
$checkedClusters = 0
$reachableClusters = 0
$totalClusters = $kubeConfig.clusters.Count

foreach ($cluster in $kubeConfig.clusters) {
$clusterName = $cluster.name
$clusterServer = $cluster.cluster.server
$checkedClusters++

Write-Progress -Activity "Checking Cluster:" -Status " $clusterName" -PercentComplete (($checkedClusters / $totalClusters) * 100)

if ($ExclusionArray -contains $clusterName) {
Write-Host "Skipping $clusterName (in exclusion list)" -ForegroundColor Cyan
Write-Verbose "Skipping cluster $clusterName as it is in the exclusion list."
continue
}

Write-Host "Checking reachability for cluster: $clusterName at $clusterServer..." -ForegroundColor Gray
Write-Verbose "Checking reachability for cluster: $clusterName at $clusterServer"
if (-not (Test-ClusterReachability -ClusterServer $clusterServer)) {
Write-Host "$clusterName is NOT reachable via HTTPS. Marking for removal..." -ForegroundColor Red
Write-Verbose "$clusterName is NOT reachable via HTTPS. Marking for removal."
$removedClusters += $clusterName
}
else {
Write-Host "$clusterName is reachable via HTTPS." -ForegroundColor Green
Write-Verbose "$clusterName is reachable via HTTPS."
$reachableClusters++
}
}

# Check if all clusters are unreachable
if ($reachableClusters -eq 0 -and -not $Force) {
Write-Host "No clusters are reachable. Perhaps the internet is down? Use `-Force` to proceed with cleanup." -ForegroundColor Yellow
Write-Verbose "No clusters are reachable. Aborting cleanup unless `-Force` is used."
return
}

Expand All @@ -157,12 +164,15 @@ function Invoke-KubeTidyCleanup {
$kubeConfig.users = $retainedUsers

Write-Host "Removed clusters, users, and contexts related to unreachable clusters." -ForegroundColor Green
Write-Verbose "Removed the following clusters: $($removedClusters -join ', ')"
}
else {
Write-Host "No clusters were removed." -ForegroundColor Yellow
Write-Verbose "No clusters were marked for removal."
}

# Save updated kubeconfig back to the file
Write-Verbose "Saving the updated KubeConfig to $KubeConfigPath"
$kubeConfig | ConvertTo-Yaml | Set-Content -Path $KubeConfigPath
Write-Host "Kubeconfig cleaned and saved." -ForegroundColor Green

Expand All @@ -181,4 +191,4 @@ function Invoke-KubeTidyCleanup {
Write-Host "║ Clusters Removed: $removedCountText" -ForegroundColor Red
Write-Host "║ Clusters Kept: $retainedCountText" -ForegroundColor Green
Write-Host "╚════════════════════════════════════════════════╝" -ForegroundColor Magenta
}
}
23 changes: 22 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
- **Backup Creation:** Automatically creates a backup of the original kubeconfig before performing any cleanup.
- **Summary Report:** Provides a neat summary of how many clusters were checked, removed, and retained.
- **Force Cleanup Option:** If all clusters are unreachable, KubeTidy can force a cleanup using the `-Force` parameter.
- **Verbose Output**: Provides detailed logging about cluster reachability and other operations using the `-Verbose` flag.

## Requirements

Expand Down Expand Up @@ -52,6 +53,7 @@ Invoke-KubeTidyCleanup -KubeConfigPath "$HOME\.kube\config" -ExclusionList "clus
- **`-ExclusionList`**: A comma-separated list of clusters to exclude from removal. (Useful for clusters requiring VPN or temporary networks.)
- **`-Backup`**: Set to `false` if you don't want a backup to be created. Defaults to `true`.
- **`-Force`**: Forces cleanup even if no clusters are reachable. Use this when you want to proceed with cleanup despite network issues.
- **`-Verbose`**: Enables detailed logging during the cleanup process, including information about cluster reachability, backup creation, and module imports.

### Example

Expand All @@ -67,6 +69,25 @@ If no clusters are reachable and you still want to proceed:
Invoke-KubeTidyCleanup -KubeConfigPath "$HOME\.kube\config" -ExclusionList "aks-prod-cluster,aks-staging-cluster" -Force
```

For detailed logging during the execution:

```powershell
Invoke-KubeTidyCleanup -KubeConfigPath "$HOME\.kube\config" -ExclusionList "aks-prod-cluster,aks-staging-cluster" -Verbose
```

### Verbose Output Example

When using the `-Verbose` flag, you will receive detailed information like:

```
VERBOSE: No KubeConfig path provided. Using default: C:\Users\username\.kube\config
VERBOSE: powershell-yaml module loaded successfully.
VERBOSE: Creating a backup of the KubeConfig file.
VERBOSE: Checking reachability for cluster: aks-prod-cluster at https://example-cluster-url
VERBOSE: Cluster aks-prod-cluster is reachable via HTTPS.
VERBOSE: Removed the following clusters: aks-old-cluster
```

## Output

After execution, you will receive a summary like the following:
Expand All @@ -83,4 +104,4 @@ After execution, you will receive a summary like the following:

## License

This project is licensed under the MIT License. See the [LICENSE](./LICENSE) file for more details.
This project is licensed under the MIT License. See the [LICENSE](./LICENSE) file for more details.

0 comments on commit 5d7deff

Please sign in to comment.