Created
May 31, 2026 13:40
-
-
Save Aref-Riant/71a137a06808e2993ab46bf53f195d74 to your computer and use it in GitHub Desktop.
get all k8 secrets decoded in csv
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
| #!/bin/bash | |
| set -euo pipefail | |
| ## You need to have jq installed ## | |
| # Default values | |
| OUTPUT_FILE="" | |
| NAMESPACE="" | |
| SKIP_EMPTY=true | |
| # Function to display usage | |
| usage() { | |
| cat << EOF | |
| Usage: $0 [OPTIONS] | |
| Options: | |
| -n, --namespace NAMESPACE Only get secrets from specific namespace | |
| -o, --output FILE Output to file instead of stdout | |
| -a, --all Include empty secrets | |
| -h, --help Display this help message | |
| Example: | |
| $0 -n default -o secrets.csv | |
| EOF | |
| exit 1 | |
| } | |
| # Parse command line arguments | |
| while [[ $# -gt 0 ]]; do | |
| case $1 in | |
| -n|--namespace) | |
| NAMESPACE="$2" | |
| shift 2 | |
| ;; | |
| -o|--output) | |
| OUTPUT_FILE="$2" | |
| shift 2 | |
| ;; | |
| -a|--all) | |
| SKIP_EMPTY=false | |
| shift | |
| ;; | |
| -h|--help) | |
| usage | |
| ;; | |
| *) | |
| echo "Unknown option: $1" | |
| usage | |
| ;; | |
| esac | |
| done | |
| # Check prerequisites | |
| for cmd in kubectl jq; do | |
| if ! command -v $cmd &> /dev/null; then | |
| echo "Error: $cmd is not installed" >&2 | |
| exit 1 | |
| fi | |
| done | |
| # Check cluster connectivity | |
| if ! kubectl cluster-info &> /dev/null; then | |
| echo "Error: Cannot connect to Kubernetes cluster" >&2 | |
| exit 1 | |
| fi | |
| # Build kubectl command | |
| KUBECTL_CMD="kubectl get secrets" | |
| if [ -n "$NAMESPACE" ]; then | |
| KUBECTL_CMD="$KUBECTL_CMD -n $NAMESPACE" | |
| else | |
| KUBECTL_CMD="$KUBECTL_CMD --all-namespaces" | |
| fi | |
| # Function to process secrets | |
| process_secrets() { | |
| echo "namespace,secret_name,key,decoded_value" | |
| $KUBECTL_CMD -o json | \ | |
| jq -r --arg skip_empty "$SKIP_EMPTY" ' | |
| .items[] | | |
| .metadata.namespace as $namespace | | |
| .metadata.name as $secret_name | | |
| if .data then | |
| .data | to_entries[] | | |
| select($skip_empty != "true" or (.value | @base64d) != "") | | |
| [ | |
| $namespace, | |
| $secret_name, | |
| .key, | |
| (.value | @base64d) | |
| ] | @csv | |
| else | |
| empty | |
| end | |
| ' | |
| } | |
| # Output to file or stdout | |
| if [ -n "$OUTPUT_FILE" ]; then | |
| process_secrets > "$OUTPUT_FILE" | |
| echo "Secrets exported to $OUTPUT_FILE" | |
| else | |
| process_secrets | |
| fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment