Skip to content

Instantly share code, notes, and snippets.

@carlessanagustin
Last active February 3, 2023 07:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carlessanagustin/1935d66c53b5c7f09214ca688ef9bcff to your computer and use it in GitHub Desktop.
Save carlessanagustin/1935d66c53b5c7f09214ca688ef9bcff to your computer and use it in GitHub Desktop.
Personal zshrc: alias and sh functions
########## START
RED=$'\e[0;31m'
R=${RED}
BLUE=$'\e[0;34m'
B=${BLUE}
GREEN=$'\e[0;32m'
G=${GREEN}
CYAN=$'\e[0;36m'
C=${CYAN}
YELLOW=$'\e[0;33m'
Y=${YELLOW}
RESET=$'\e[0m'
RC=${RESET}
prompt_k8s(){
k8s_context=$(kubectl config current-context)
k8s_ns=$(kubectl config view --minify --output 'jsonpath={..namespace}')
if [[ "${k8s_context}" == "" ]]; then
echo ""
else
if [[ "${k8s_ns}" == "" ]];then
echo "${k8s_context}"
else
echo "${k8s_context}/${k8s_ns}"
fi
fi
}
PROMPT+='%{$fg_bold[blue]%}k8s:(%{$fg[magenta]%}$(prompt_k8s)%{$fg[blue]%}) %{$reset_color%}'
#alias ls='exa'
#alias my_date="date -u '+%Y-%m-%dT%H:%M:%S,%N%Z'"
alias my_date="date +'%Y-%m-%dT%H:%M:%S'"
alias my_date_az="date -u +'%Y-%m-%dT%H:%M:%sZ'"
# completion
[[ $(command -v kubectl) ]] && source <(kubectl completion zsh)
[[ $(command -v helm) ]] && source <(helm completion zsh)
[[ $(command -v operator-sdk) ]] && source <(operator-sdk completion zsh)
[[ $(command -v flux) ]] && source <(flux completion zsh)
[[ $(command -v fluxctl) ]] && source <(fluxctl completion zsh)
[[ $(command -v argocd) ]] && source <(argocd completion zsh)
[[ $(command -v k9s) ]] && source <(k9s completion zsh)
autoload -U +X bashcompinit && bashcompinit
source /usr/local/etc/bash_completion.d/az
source /usr/local/etc/bash_completion.d/tmux
alias youtube-dl-mp3='youtube-dl -x --audio-format mp3 --audio-quality 1'
alias youtube-dl-video-top="youtube-dl -f 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best'"
alias youtube-dl-video-best="youtube-dl -f 'best[filesize<100M]'"
alias cl='clear && pwd && git status'
alias my_ip_aws='curl --silent https://checkip.amazonaws.com'
alias my_ip='curl ifconfig.co'
my_usage(){
echo "${Y}USAGE: ${1}${RC}"
}
## docker management
alias my_dock_kill_rm='docker kill $(docker ps -aq) ; docker rm $(docker ps -aq)'
alias my_dock_rmi_all='docker rmi -f $(docker images -aq)'
alias my_dock_prune='docker volume prune -f ; docker network prune -f '
my_dock_teardown() { docker kill $(docker ps -aq) ; docker rm $(docker ps -aq) ; docker rmi -f $(docker images -aq) ; docker volume prune -f ; docker network prune -f ; }
my_dock_in() { docker exec -it $1 sh ; }
alias dcu="docker-compose up -d"
alias dcd="docker-compose down"
alias di="docker images"
drmi() { docker rmi $1 ; }
## docker containers
alias my_getme_centos='docker run -it -v "$(pwd)":/shared centos:8'
alias my_getme_debian='docker run -it -v "$(pwd)":/shared debian:10-slim'
alias my_getme_fedora='docker run -it -v "$(pwd)":/shared fedora:36'
alias my_getme_ubuntu='docker run -it -v "$(pwd)":/shared ubuntu:20.04'
alias my_getme_alpine='docker run -it -v "$(pwd)":/shared alpine:latest'
alias my_getme_powershell_root='docker run -it --privileged=true -v $HOME:/root -v "$(pwd)":/shared mcr.microsoft.com/powershell:latest'
alias my_getme_powershell='docker run -it -v "$(pwd)":/shared mcr.microsoft.com/powershell:latest'
alias my_getme_python='docker run -it -v "$(pwd)":/shared python:latest'
alias my_getme_nushell='docker run -it -v "$(pwd)":/shared quay.io/nushell/nu'
alias my_getme_azcli='docker run -it -v "$(pwd)":/shared mcr.microsoft.com/azure-cli:latest'
my_getme_terraform(){ if [ $# -eq 0 ] ; then ; echo "Usage: my_getme_terraform <version>" 1>&2 ; else ; docker run -it -v "$(pwd)":/shared --entrypoint /bin/sh hashicorp/terraform:$1 ; fi ;}
alias my_getme_portainer='docker run -d -p 9000:9000 -v /var/run/docker.sock:/var/run/docker.sock portainer/portainer-ce:latest'
alias my_getme_kubetools='docker run -d --entrypoint sh -p 9000:9000 -v /var/run/docker.sock:/var/run/docker.sock portainer/kube-tools:latest'
alias my_getme_kubectl='docker run -it --entrypoint /bin/bash -v "$(pwd)":/shared bitnami/kubectl:latest'
alias my_getme_pandoc='docker run -it --entrypoint /bin/sh -v "$(pwd)":/shared pandoc/latex:latest'
alias my_getme_opstools='docker run --rm -it -v /var/run/docker.sock:/var/run/docker.sock -v $HOME:/home/axedras registry.gitlab.com/axedras/ops/seed-operator/ax-ops-seed:1.2.0'
my_getme_container() { docker run -it -v "$(pwd)":/shared $1 $2 ; }
## kubernetes
alias kx='kubectx'
alias kn='kubens'
alias explain='kubectl explain'
alias ke='kubectl explain'
alias ketall='kubectl get-all'
alias kt='kubectl logs -f --tail=20 -n'
my_k8s_secret() { echo "$1" | base64 -d ; }
my_k8s_controllers(){ watch kubectl $1 get deploy,rs,ds,sts,cj,jobs,rc ; }
my_k8s_accounts(){ watch kubectl $1 get clusterrolebindings,clusterroles,sa ; }
my_k8s_get(){ watch kubectl $1 get pod,deployments,svc,ingress,pvc,pv ;}
my_k8s_rmpod(){
if [[ $# -eq 0 ]]; then
my_usage "my_k8s_rmpod <namespace> <pod_name>" 1>&2
#echo "Usage: my_k8s_rmpod <namespace> <pod_name>" 1>&2
else
kubectl -n $1 delete pods $2 --wait=false --timeout=0s --grace-period=0 --force
fi
}
my_k8s_troubleshooting(){
[[ "${debug}" == "true" ]] && set -x
local C_NAME=troubleshooting
if [[ "$1" == "create" ]]; then
kubectl -n $2 run ${C_NAME} --image=ubuntu:20.04 -- sleep 99999d
elif [[ "$1" == "delete" ]]; then
kubectl -n $2 --force=true delete pods ${C_NAME}
elif [[ "$1" == "cmd" ]]; then
kubectl -n $2 exec -it ${C_NAME} -- $3
else
my_usage "my_k8s_troubleshooting [create|delete|cmd] <namespace> <command>" 1>&2
fi
}
# from https://marcusnoble.co.uk/2022-07-04-managing-kubernetes-without-losing-your-cool/
alias kshell='kubectl run -it --image ubuntu:20.04 --restart Never --rm shell'
my_k8s_status(){
echo "${Y}>>>>> certificates status (kubectl get certificates --all-namespaces -o wide) <<<<<${RC}"
kubectl get certificates --all-namespaces -o wide
echo
echo "${Y}>>>>> pod status (kubectl get pod --all-namespaces) <<<<<${RC}"
if [[ "${wide}" == "true" ]]; then
kubectl get pod --all-namespaces -o wide | grep -vi "Running"
else
kubectl get pod --all-namespaces | grep -vi "Running"
fi
}
my_k8s_events(){
echo "${Y}>>>>> event type <<<<<${RC}"
kubectl get events --sort-by=".lastTimestamp" --all-namespaces -o wide | grep -vi "Normal"
echo
}
alias kevents='kubectl get events --sort-by=.metadata.creationTimestamp -n'
my_k8s_newline(){
[[ "${debug}" == "true" ]] && set -x
if [[ $# -eq 0 ]]; then
my_usage "my_k8s_newline <namespace> <configmap> <data_id>" 1>&2
else
kubectl -n ${1} get configmaps ${2} -o json | jq '.data."'${3}'"' -r
fi
}
my_k8s_rm_nsPattern(){
if [[ $# -eq 0 ]]; then
my_usage "my_k8s_rm_nsPattern <namespace_pattern>" 1>&2
else
for ns in $(kubectl get ns | grep -i ${1} | awk '{print $1}'); do
kubectl delete ns --force ${ns}
done
kubectl get ns
fi
}
my_k8s_certmanager(){
[[ "${debug}" == "true" ]] && set -x
if [[ $# -eq 0 ]]; then
my_usage "debug=[true|false] my_k8s_certmanager <namespace>" 1>&2
else
kubectl -n ${1} get certificaterequests.cert-manager.io
kubectl -n ${1} get certificates.cert-manager.io
kubectl -n ${1} get clusterissuers.cert-manager.io
kubectl -n ${1} get issuers.cert-manager.io
kubectl -n ${1} get challenges.acme.cert-manager.io
kubectl -n ${1} get orders.acme.cert-manager.io
fi
}
my_helm_stable() {
helm repo add stable https://kubernetes-charts.storage.googleapis.com
helm repo update
}
## ansible
my_encrypt_vault() { ansible-vault encrypt --vault-password-file=~/keys/ansible_vault.key --output=vault_$1 vars_$1 ; }
my_decrypt_vault() { ansible-vault decrypt --vault-password-file=~/keys/ansible_vault.key --output=vars_$1 vault_$1 ; }
my_ansible_facts() { ansible all -i "$1" -m setup ; }
my_build_ansible() { wget -O - https://goo.gl/7yUeDC | bash ; }
alias my_getme_ansible='docker run -it -v "$(pwd)":/shared ansible/ansible bash'
alias ansible-playbook='ansible-playbook -e ansible_python_interpreter=/usr/bin/python3.6'
## pip
my_pip_upgrade() { pip list --outdated --format=freeze | grep -v '^\-e' | cut -d = -f 1 | xargs -n1 pip install --user -U }
## git
my_git_init(){ if [ $# -eq 0 ] ; then ; echo "Usage: my_git_init <email_address>" 1>&2 ; else ; git flow init ; git config --local user.name "Carles San Agustin" ; git config --local user.email $1 ; git config --local http.sslVerify "false" ; git config pull.rebase false; touch README.md .gitignore ; fi ; }
my_gitlab(){ if [ $# -eq 0 ] ; then ; echo "Usage: my_git_init <email_address>" 1>&2 ; else ; git config --local user.name "Carles San Agustin" ; git config --local user.email $1 ; git config --local http.sslVerify "false" ; git config pull.rebase false; git config core.sshCommand "ssh -o IdentitiesOnly=yes -i ~/.ssh/id_ed25519_gitlab_carlessanagustin -F /dev/null"; fi ; }
alias my_git_clean_wt="git clean -d -x -f"
my_git_tag_delete(){
git tag -d $1 || true
git push --delete origin $1
}
my_git_tag_create() { git tag $1 ; git push --tags ; }
my_git_branch_delete() {
git branch -D $1 || true
git push origin --delete $1
}
my_git_branch_rename() {
if [ $# -eq 0 ] ; then
echo "(source https://www.hostinger.com/tutorials/how-to-rename-a-git-branch/#How_to_Rename_a_Local_Git_Branch)"
echo "Usage: my_git_branch_rename <old_name> <new_name> <remote:-origin>" 1>&2
else
old_name=$1
new_name=$2
remote=$3
git checkout ${old_name}
git branch -m ${new_name}
git push ${remote:-origin} --delete ${old_name}
git push ${remote:-origin} -u ${new_name}
fi
}
my_git_changelog() { git log --oneline --no-merges $1 ; }
my_git_clone() { git clone --recursive $1 ;}
alias my_git_push='git push --recurse-submodules=on-demand'
my_git_rebase(){
echo " STEPS...
git checkout master
git pull
git checkout <branch>
git rebase master
"
}
# https://git-scm.com/docs/git-submodule
# Pull a Git Submodule
# $ git submodule update --init --recursive
# Update a Git Submodule
# $ git submodule update --remote --merge
# alias my_git_submodule_update='git submodule update --remote --merge --recursive'
# https://docs.gitlab.com/ee/ci/runners/configure_runners.html#git-submodule-strategy
my_git_submodule_update() {
my_usage "only the top-level submodules are included" 1>&2
git submodule sync
git submodule update --init
}
my_git_submodule_update_recursive() {
my_usage "all submodules (including submodules of submodules) are included" 1>&2
git submodule sync --recursive
git submodule update --init --recursive
}
## ssh
my_tunnel() { ssh -N -L $1\:localhost:$2 $3 ; }
# my_tunnel 8161 8161 user@example.com
my_tunnelr() { ssh -N -R $1\:localhost:$2 $3 ; }
# my_tunnelr 19999 22 user@example.com
export MY_SSH_OPTIONS="-o StrictHostKeyChecking=no -o PreferredAuthentications=password -o PubkeyAuthentication=no -o ServerAliveInterval=60"
alias sshp="ssh -o StrictHostKeyChecking=no -o PreferredAuthentications=password -o PubkeyAuthentication=no -o ServerAliveInterval=60 "
alias sshk="ssh -o StrictHostKeyChecking=no -o PreferredAuthentications=publickey -o PubkeyAuthentication=yes -o ServerAliveInterval=60 "
## system
my_folder_size() { du -hsx $1 | sort -rh | head -10; }
my_chown() { sudo chown -Rf $USER:$USER $1 ; }
alias my_duf='du -sk * | sort -n | while read size fname; do for unit in k M G T P E Z Y; do if [ $size -lt 1024 ]; then echo -e "${size}${unit} - ${fname}"; break; fi; size=$((size/1024)); done; done'
#alias my_duf='du -skh * | sort -n | tac'
alias my_duf_hidden='du -ahd1 | sort -h'
my_zombies(){ ps -eo pid,ppid,state,cmd | awk '$3=="Z"' }
alias my_permits="sudo find * -type d -print0 | sudo xargs -0 chmod 0755 && sudo find . -type f -print0 | sudo xargs -0 chmod 0644"
my_process_count() { ps -ef | awk '{ print $8 }' | sort -n | uniq -c | sort -n ; }
alias my_process_total='ps -A --no-headers | wc -l'
alias my_process_usage='ps aux --sort=%mem,%cpu'
alias my_top5_ps='ps aux | sort -nrk 3,3 | head -n 5'
my_kill_processes() { ps -ef | grep $1 | grep -v grep | awk '{print $2}' | xargs kill -9 ; }
alias my_netstat="netstat -tulpn"
alias my_netstat_a="netstat -tulpna"
my_curl() { curl -s -D - $1 -o /dev/null ; }
svc_logs() { sudo journalctl -f -u $1 ; }
my_newline() {
if [ $# -eq 0 ] ; then
my_usage "my_newline <filepath>" 1>&2
else
awk '{gsub(/\\n/,"\n")}1' $1
fi
}
alias sed_newline="sed -i 's/\\n/\n/g' "
# from: https://goo.gl/EeGNSf
my_topcommands() { fc -l 1 | awk '{CMD[$2]++;count++;}END { for (a in CMD)print CMD[a] " " CMD[a]/count*100 "% " a; }' | grep -v "./" | column -c3 -s " " -t | sort -nr | nl | head -n10 }
#alias my_pwgen="pwgen -s 21 8 -1 -y"
my_pwgen() { pwgen -s $1 8 -1 -y ; }
# azure
alias my_az_locs="az account list-locations --output table"
my_az_sub_envvars() {
export AZ_SUBS_ID=$(az account show | jq '.id')
export AZ_SUBS_NAME=$(az account show | jq '.name')
export AZ_TENANT=$(az account show | jq '.tenantId')
env | grep -i "AZ_"
}
## azure - service principals AKA app registrations
my_az_sp(){
case "$1" in
"list")
az role definition list --output tsv \
--query "[].{name:name, roleType:roleType, roleName:roleName}"
;;
"create")
az ad sp create-for-rbac --name "$2" --years 2
;;
"delete")
az ad app delete --id "$2" --verbose
;;
"assign")
az role assignment create --assignee "$2" \
--role "$3" --scope "$4"
;;
"unassign")
az role assignment delete --assignee "$2" \
--role "$3" --scope "$4"
;;
"list_objectId")
az ad sp list --all --filter "objectId eq '$2'"
;;
"list_displayName")
az ad sp list --all --filter "displayName eq '$2'"
;;
"list_appId")
az ad sp list --all --filter "appId eq '$2'" \
;;
*)
echo 'USAGE:
* list: az role definition list...
* create: az ad sp create-for-rbac --name ${spName} --years 2
* delete: az ad app delete --id "${appId}"
* assign: az role assignment create --assignee "${appId}" --role "${azRole}" --scope "${azScope}"
* unassign: az role assignment delete --assignee "${appId}" --role "${azRole}" --scope "${azScope}"
* list_objectId: az ad sp list --all --filter "objectId eq <objectId>"
* list_displayName: az ad sp list --all --filter "displayName eq <displayName>"
* list_appId: az ad sp list --all --filter "appId eq <appId>"'
;;
esac
}
export BYOBU_PREFIX=/usr/local
my_ssh_key(){
if [ $# -eq 0 ] ; then
#echo "Usage: [DEST_DIR=~/.ssh] [TYPE=ed25519|rsa] my_ssh_key <owner>" 1>&2
my_usage "[DEST_DIR=~/.ssh] [TYPE=ed25519|rsa] my_ssh_key <owner>" 1>&2
else
local NOW=$(date -u '+%Y%m-%dT%H%M%S')
[[ -z ${DEST_DIR} ]] && export DEST_DIR=${HOME}/.ssh
[[ -z ${TYPE} ]] && export TYPE=ed25519
ssh-keygen -t ${TYPE} -b 4096 -P '' -C "$1 on ${NOW}" -f ${DEST_DIR}/${NOW}-id_rsa_$1
chmod 400 ${DEST_DIR}/${NOW}-id_rsa_$1*
fi
}
# virtualbox functions
my_vms_ls(){
vboxmanage list vms
}
my_vms_rm(){
for uuid in $(vboxmanage list vms | awk -F'"' '{print $3}' | tr -d ' ') ; do clean_uuid=${uuid#"{"} && clean_uuid=${clean_uuid%"}"} && vboxmanage unregistervm $clean_uuid --delete ; done
}
#[[ $# == 0 ]] && help
#"$@"
########## END
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment