Skip to content

Instantly share code, notes, and snippets.

@shiryel
Last active March 15, 2022 21:39
Show Gist options
  • Save shiryel/5b6fb0106d499ded91b623e930797ee9 to your computer and use it in GitHub Desktop.
Save shiryel/5b6fb0106d499ded91b623e930797ee9 to your computer and use it in GitHub Desktop.
Get all envs from kubernetes container (curated environment vars as export)
if [[ $# -lt 1 ]]; then
echo "Error: Needs at least the name of the pod"
echo "Example: ./kubenv.sh pod-name output-file.env"
exit 1
fi
pod_name=$1
output=${2:-"$1.env"}
# create the envrc from the pod envs
pod=(echo $(kubectl get pods --all-namespaces | grep "${pod_name}" | head -1 | awk '{print $1}{print $2}'))
echo -ne "$(kubectl -n "${pod[1]}" exec -it "${pod[2]}" -- sh -c 'export')" > "${output}"
# revomes returns (^M)
sed -i "s/\r//" "${output}"
# removes useless envs
useless_envs=("HOME" "TERM" "PATH" "HOSTNAME" "LANG" "LANGUAGE" "LC_ALL" "MIX_ENV" "APP_REVISION" "APP_NAME")
for env in ${useless_envs[*]}; {
sed -i "/\(^export ${env}='.*\$\)/d" "${output}"
}
sed -i "/='10.0/d" "${output}"
sed -i "/='tcp/d" "${output}"
sed -i "/='udp/d" "${output}"
# removes envs that are added automatically by kubernetes
services=($(kubectl get svc --all-namespaces -o=custom-columns=NAME:.metadata.name --no-headers))
for service in ${services[*]}; {
to_rm=$(echo ${service} | tr "[a-z]" "[A-Z]" | tr "-" "_")
sed -i "/\(^export ${to_rm}_SERVICE_PORT.*\$\)/d" "${output}"
sed -i "/\(^export ${to_rm}_SERVICE_HOST.*\$\)/d" "${output}"
sed -i "/\(^export ${to_rm}_PORT.*\$\)/d" "${output}"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment