Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save quangnhut123/4dcee968be0febf95bfb61ed0c969432 to your computer and use it in GitHub Desktop.
Save quangnhut123/4dcee968be0febf95bfb61ed0c969432 to your computer and use it in GitHub Desktop.
Get kubeconfig for custom cluster in Rancher 2.0
#!/bin/bash
# Usage: ./get_kubeconfig_custom_cluster_rancher2.sh cluster_name
# Needs to be run on the server running `rancher/rancher` container
# Check if jq exists
command -v jq >/dev/null 2>&1 || { echo "jq is not installed. Exiting." >&2; exit 1; }
# Check if clustername is given
if [ -z "$1" ]; then
echo "Usage: $0 [clustername]"
exit 1
fi
# Provide clustername as first argument
CLUSTERNAME=$1
# Retrieve Docker container ID of container running `rancher/rancher` image
CONTID=`docker ps | grep -E "rancher/rancher:|rancher/rancher@" | awk '{ print $1 }'`
# Get cluster ID from name
CLUSTERID=`docker exec $CONTID kubectl get cluster -o json | jq -r '.items[] | select(.spec.displayName == "'$CLUSTERNAME'") | .metadata.name'`
# Get kubeconfig for cluster ID and save it to `kubeconfig`
docker exec $CONTID kubectl get secret c-$CLUSTERID -n cattle-system -o json | jq -r .data.cluster | base64 -d | jq -r .metadata.state > kubeconfig
# Show kubeconfig
cat kubeconfig
if command -v kubectl >/dev/null 2>&1; then
# Run kubectl against kubeconfig
kubectl --kubeconfig kubeconfig get nodes
fi
#!/bin/bash
# Needs to be run in embedded kubectl of Imported cluster called local, or using the RKE generated kubeconfig
if [ -z "$1" ]; then
echo "Usage: $0 [clustername]"
exit 1
fi
# Provide clustername as first argument
CLUSTERNAME=$1
kubectl get secret c-$(kubectl get cluster -o json | jq -r '.items[] | select(.spec.displayName == "'$CLUSTERNAME'") | .metadata.name') -n cattle-system -o json | jq -r .data.cluster | base64 -d | jq -r .metadata.state
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment