Skip to content

Instantly share code, notes, and snippets.

@babarot
Last active February 28, 2022 07:32
Show Gist options
  • Save babarot/bb820b99fdba605ea4bd4fb29046ce58 to your computer and use it in GitHub Desktop.
Save babarot/bb820b99fdba605ea4bd4fb29046ce58 to your computer and use it in GitHub Desktop.
Get current GCP project name / Kubernetes context which you are on.
#!/bin/bash
if ! type jq &>/dev/null; then
echo "jq: not found" >&2
exit 1
fi
if ! type gcloud &>/dev/null; then
echo "gcloud: not found" >&2
exit 1
fi
gcloud config configurations list --format='json' \
| jq -r '.[] | select(.is_active==true) | .properties.core.project'
#!/bin/bash
while (( ${#} > 0 ))
do
case "${1}" in
--context)
context="${2}"
shift
shift
;;
--context=*)
context="${1#*=}"
shift
;;
esac
done
if ! type kubectl &>/dev/null; then
echo "kubectl command not found" >&2
exit 1
fi
if ! context="$(kubectl config current-context 2>/dev/null)"; then
echo "NaN"
exit 0
fi
namespace="$(kubectl config view -o "jsonpath={.contexts[?(@.name==\"${context}\")].context.namespace}")"
if [[ -z "${namespace}" ]]; then
namespace="default"
fi
regions=(
asia-northeast1-a
asia-northeast1-b
asia-northeast1-c
asia-east1-a
asia-east1-b
asia-east1-c
)
for region in "${regions[@]}"
do
context=${context%_${region}*}
done
echo "${context}/${namespace}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment