Skip to content

Commit

Permalink
v0.0.11 add merge option
Browse files Browse the repository at this point in the history
Signed-off-by: PixelRobots <[email protected]>
  • Loading branch information
PixelRobots committed Sep 26, 2024
1 parent fcf0e55 commit 98cff8d
Show file tree
Hide file tree
Showing 4 changed files with 195 additions and 25 deletions.
19 changes: 9 additions & 10 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,19 @@ All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [0.0.10] - 2024-09-27
## [0.0.11] - 2024-09-30

### Added
- **Clickable Backup Path**: Backup path is now clickable if the terminal supports it, making it easier to navigate to backup files.
- **Manual YAML Handling for Single Entries**: Ensured proper YAML structure when only one cluster, context, or user remains in the kubeconfig file.
- **Merge Kubeconfig Files:** Introduced the ability to merge multiple kubeconfig files into one using the `-MergeConfigs` parameter. Users can specify multiple kubeconfig file paths to be merged into the destination kubeconfig file.
- **DestinationConfig Parameter:** Added the `-DestinationConfig` parameter for specifying the output path of the merged kubeconfig file. If not specified, it defaults to `"$HOME/.kube/config"`.
- **Cluster Count Output:** The `-ListClusters` parameter now also outputs the total number of clusters present in the kubeconfig file after listing them.

### Changed
- **Environment Detection**: Enhanced WSL detection and config path handling for both native Linux/macOS and WSL environments.
- **KubeConfig Path Handling**: Improved logic for determining the kubeconfig path in different environments (Windows, WSL, Linux/macOS).

### Fixed
- **Cluster Removal Formatting**: Fixed an issue where the kubeconfig format would break when cleaning up to a single cluster, context, or user.
- **Cluster Kept Count**: fixed so the number is correct. It was 1 out before.
## [0.0.10] - 2024-09-28

### Added
- Initial support for listing clusters with `-ListClusters` to display all clusters in the kubeconfig file without performing any cleanup.
- Added functionality to retain users and contexts during the cleanup process when clusters are marked for removal.

## [0.0.9] - 2024-09-26

Expand Down Expand Up @@ -45,4 +44,4 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
## [0.0.6] - 2024-09-25

### Added
- Initial release of **KubeTidy**, featuring Kubernetes cluster reachability checks and cleanup of unreachable clusters, contexts, and users.
- Initial release of **KubeTidy**, featuring Kubernetes cluster reachability checks and cleanup of unreachable clusters, contexts, and users.
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.10'
ModuleVersion = '0.0.11'

# Supported PSEditions
# CompatiblePSEditions = @()
Expand Down
154 changes: 146 additions & 8 deletions KubeTidy.psm1
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
<#
.SYNOPSIS
KubeTidy: A script to clean up your Kubernetes config file by removing unreachable clusters and associated users and contexts.
KubeTidy: A script to clean up your Kubernetes config file by removing unreachable clusters and associated users and contexts, or merge multiple config files.
.DESCRIPTION
This script removes unreachable clusters from the kubeconfig file and ensures that associated
users and contexts that reference the removed clusters are also removed.
users and contexts that reference the removed clusters are also removed. It can also merge multiple kubeconfig files.
.PARAMETER KubeConfigPath
Path to your kubeconfig file. Defaults to the default Kubernetes location if not specified.
Expand All @@ -21,6 +21,12 @@
.PARAMETER ListClusters
Displays a list of all clusters in the kubeconfig file without performing cleanup.
.PARAMETER MergeConfigs
An array of kubeconfig files to merge into the destination kubeconfig file.
.PARAMETER DestinationConfig
The path to save the merged kubeconfig file. Defaults to the default location if not specified.
.PARAMETER Verbose
Enables verbose logging for detailed output.
#>
Expand All @@ -31,7 +37,9 @@ param (
[string]$ExclusionList = "",
[bool]$Backup = $true,
[switch]$Force,
[switch]$ListClusters
[switch]$ListClusters,
[string[]]$MergeConfigs,
[string]$DestinationConfig = ""
)

# Split the ExclusionList by commas to create an array of clusters
Expand Down Expand Up @@ -97,23 +105,141 @@ function Get-AllClusters {

Write-Host "Listing all clusters in KubeConfig file:" -ForegroundColor Yellow
Write-Host ""

# Read the kubeconfig content
$kubeConfigContent = Get-Content -Raw -Path $KubeConfigPath
$kubeConfig = $kubeConfigContent | ConvertFrom-Yaml

foreach ($cluster in $kubeConfig.clusters) {
$clusterName = $cluster.name
Write-Host "Cluster: $clusterName" -ForegroundColor Cyan
# Get the total number of clusters
$clusterCount = $kubeConfig.clusters.Count

# Check if there are clusters in the file
if ($clusterCount -gt 0) {
# List the clusters
foreach ($cluster in $kubeConfig.clusters) {
$clusterName = $cluster.name
Write-Host "Cluster: $clusterName" -ForegroundColor Cyan
}

# Output the total number of clusters
Write-Host ""
Write-Host "Total Clusters: $clusterCount" -ForegroundColor Green
} else {
Write-Host "No clusters found in the kubeconfig file." -ForegroundColor Red
}
}

# Main Cleanup Function

# Function to merge kubeconfig files
# Function to merge kubeconfig files
function Merge-KubeConfigs {
[CmdletBinding()]
param (
[string[]]$MergeConfigs,
[string]$DestinationConfig
)

# Initialize empty hash tables to hold the merged clusters, contexts, and users
$mergedClusters = @{}
$mergedContexts = @{}
$mergedUsers = @{}

foreach ($configPath in $MergeConfigs) {
Write-Verbose "Merging config from $configPath"
$configContent = Get-Content -Raw -Path $configPath
$config = $configContent | ConvertFrom-Yaml

# Merge clusters
foreach ($cluster in $config.clusters) {
if (-not $mergedClusters.ContainsKey($cluster.name)) {
$mergedClusters[$cluster.name] = $cluster
}
}

# Merge contexts
foreach ($context in $config.contexts) {
if (-not $mergedContexts.ContainsKey($context.name)) {
$mergedContexts[$context.name] = $context
}
}

# Merge users
foreach ($user in $config.users) {
if (-not $mergedUsers.ContainsKey($user.name)) {
$mergedUsers[$user.name] = $user
}
}
}

# Create the merged kubeconfig with the correct structure
$mergedKubeConfig = @"
apiVersion: v1
kind: Config
preferences: {} `n
"@

# Convert clusters, contexts, and users to YAML
$clustersYaml = @"
clusters: `n
"@
foreach ($cluster in $mergedClusters.Values) {
$clustersYaml += " - cluster:`n"
$clustersYaml += " certificate-authority-data: $($cluster.cluster.'certificate-authority-data')`n"
$clustersYaml += " server: $($cluster.cluster.server)`n"
$clustersYaml += " name: $($cluster.name)`n"
}

$contextsYaml = @"
contexts: `n
"@
foreach ($context in $mergedContexts.Values) {
$contextsYaml += " - context:`n"
$contextsYaml += " cluster: $($context.context.cluster)`n"
$contextsYaml += " user: $($context.context.user)`n"
$contextsYaml += " name: $($context.name)`n"
}

$usersYaml = @"
users: `n
"@
foreach ($user in $mergedUsers.Values) {
$usersYaml += " - name: $($user.name)`n"
$usersYaml += " user:`n"
$usersYaml += " client-certificate-data: $($user.user.'client-certificate-data')`n"
$usersYaml += " client-key-data: $($user.user.'client-key-data')`n"
}

# Combine everything into one YAML structure
$fullKubeConfigYaml = $mergedKubeConfig + $clustersYaml + $contextsYaml + $usersYaml

# Save the merged config to the destination file
$fullKubeConfigYaml | Set-Content -Path $DestinationConfig
Write-Host "Merged kubeconfig saved to $DestinationConfig" -ForegroundColor Green

# Display summary of merged entities
Write-Host ""
Write-Host "╔════════════════════════════════════════════════╗" -ForegroundColor Magenta
Write-Host "║ KubeTidy Merge Summary ║" -ForegroundColor Magenta
Write-Host "╠════════════════════════════════════════════════╣" -ForegroundColor Magenta
Write-Host "║ Files Merged: $($MergeConfigs.Count)" -ForegroundColor Yellow
Write-Host "║ Clusters Merged: $($mergedClusters.Count)" -ForegroundColor Cyan
Write-Host "║ Contexts Merged: $($mergedContexts.Count)" -ForegroundColor Cyan
Write-Host "║ Users Merged: $($mergedUsers.Count)" -ForegroundColor Cyan
Write-Host "╚════════════════════════════════════════════════╝" -ForegroundColor Magenta
Write-Host ""
}


# Main Cleanup or Merge Function
function Invoke-KubeTidy {
[CmdletBinding()]
param (
[string]$KubeConfigPath,
[array]$ExclusionList,
[switch]$Force,
[switch]$ListClusters
[switch]$ListClusters,
[string[]]$MergeConfigs,
[string]$DestinationConfig
)

# Ensure that the $KubeConfigPath is valid
Expand Down Expand Up @@ -161,6 +287,17 @@ function Invoke-KubeTidy {
Import-Module powershell-yaml -ErrorAction Stop
Write-Verbose "powershell-yaml module loaded successfully."

# If MergeConfigs is provided, perform merging
if ($MergeConfigs) {
if (-not $DestinationConfig) {
$DestinationConfig = "$env:USERPROFILE\.kube\config"
}
Show-KubeTidyBanner
Write-Host "Merging kubeconfig files..." -ForegroundColor Yellow
Merge-KubeConfigs -MergeConfigs $MergeConfigs -DestinationConfig $DestinationConfig
return
}

# If ListClusters flag is provided, list clusters and exit
if ($ListClusters) {
Show-KubeTidyBanner
Expand Down Expand Up @@ -280,6 +417,7 @@ preferences: {} `n
$fullKubeConfigYaml | Set-Content -Path $KubeConfigPath

Write-Host "Kubeconfig cleaned and saved." -ForegroundColor Green

# Display the summary with consistent padding
$removedCount = $removedClusters.Count
$checkedClustersText = "{0,5}" -f $checkedClusters
Expand Down
45 changes: 39 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

</br>

**KubeTidy** is a PowerShell tool designed to clean up your Kubernetes configuration file by removing unreachable clusters, along with associated users and contexts. It simplifies the management of your `kubeconfig` by ensuring that only reachable and valid clusters remain, making it easier to work with multiple Kubernetes environments.
**KubeTidy** is a PowerShell tool designed to clean up your Kubernetes configuration file by removing unreachable clusters, along with associated users and contexts. It simplifies the management of your `kubeconfig` by ensuring that only reachable and valid clusters remain, making it easier to work with multiple Kubernetes environments. **KubeTidy** also supports merging multiple `kubeconfig` files into one.

## Features

Expand All @@ -17,7 +17,8 @@
- **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.
- **List Clusters Option**: Use the `-ListClusters` parameter to simply list all clusters in your kubeconfig without performing any cleanup.
- **List Clusters Option**: Use the `-ListClusters` parameter to list all clusters in your kubeconfig without performing any cleanup, with a count of total clusters displayed.
- **Merge Kubeconfig Files**: Easily merge multiple `kubeconfig` files into a single config file using the `-MergeConfigs` parameter.
- **Verbose Output**: Provides detailed logging about cluster reachability and other operations using the `-Verbose` flag.

## Requirements
Expand Down Expand Up @@ -55,9 +56,13 @@ Invoke-KubeTidy -KubeConfigPath "$HOME\.kube\config" -ExclusionList "cluster1,cl
- **`-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.
- **`-ListClusters`**: Lists all clusters in the kubeconfig file without performing any cleanup.
- **`-ListClusters`**: Lists all clusters in the kubeconfig file without performing any cleanup, and displays the total number of clusters.
- **`-MergeConfigs`**: Merges multiple `kubeconfig` files into one. Takes an array of file paths as input.
- **`-DestinationConfig`**: Path to save the merged `kubeconfig` file. If not specified, the default `"$HOME\.kube\config"` will be used.

### Example
### Examples

#### Cleaning up your kubeconfig

To exclude specific clusters from removal and clean up your kubeconfig:

Expand All @@ -72,12 +77,26 @@ If no clusters are reachable and you still want to proceed:
Invoke-KubeTidy -KubeConfigPath "$HOME\.kube\config" -ExclusionList "aks-prod-cluster,aks-staging-cluster" -Force
```

To list all clusters without performing any cleanup:
#### Merging multiple `kubeconfig` files

To merge multiple `kubeconfig` files into a single config file:

```powershell
Invoke-KubeTidy -MergeConfigs "config1.yaml","config2.yaml","config3.yaml" -DestinationConfig "$HOME\.kube\config"
```

This will merge the `config1.yaml`, `config2.yaml`, and `config3.yaml` into the destination config file (`$HOME\.kube\config` by default).

#### Listing clusters

To list all clusters without performing any cleanup, along with the count of clusters:

```powershell
Invoke-KubeTidy -KubeConfigPath "$HOME\.kube\config" -ListClusters
```

#### Verbose logging for detailed output

For detailed logging during the execution:

```powershell
Expand All @@ -97,7 +116,21 @@ VERBOSE: Cluster aks-prod-cluster is reachable via HTTPS.
VERBOSE: Removed the following clusters: aks-old-cluster
```

## Output
### List Clusters Output Example

When using the `-ListClusters` parameter, you will receive output like this:

```
Listing all clusters in KubeConfig file:
Cluster: cluster1
Cluster: cluster2
Cluster: cluster3
Total Clusters: 3
```

## Output Example

After execution, you will receive a summary like the following:

Expand Down

0 comments on commit 98cff8d

Please sign in to comment.