为k8s集群操作命令设置别名(Alias),大大提高简化操作,提高效率

背景:

越来越多的企业投入K8S集群并使用,但相对复杂的集群操作命令又不熟悉。到了需要操作的时候,却记不住命令,百度?或者问AI?不用!今天教你一招,为K8S集群常见命令设置别名(你愿意让它叫什么就叫什么,当然linux环境下,需要是英文的,哈哈哈)。下次,用你自己设置的别名来运行命令,总不会记不住了吧?

 

一、这里先解释一下别名设置规则格式: alias(设置别名的命令) k(你要设置成的名称)="kubectl"(K8S集群中操作命令)

类如如下:

alias k="kubectl"  #  将kubectl 命令设置成别名K

alias kgp="kubectl get pods"           将kubectl get pods 命令设置成别名kgp

alias kgd="kubectl get deployment"     将kubectl get deployment 命令设置成别名kgd

alias kdp="kubectl describe pod"       将kubectl describe pod 命令设置成别名kdp

alias klf="kubectl logs -f --tail=100" 将kubectl logs -f --tail=100命令设置成别名klf

 

二、理解了之后,我们就可以将这些文件复制到 Shell 的配置文件下。

不同终端对应的配置文件不同:

Bash:默认配置文件为用户目录下的 ~/.bashrc(临时用户)或 /etc/bashrc(全局所有用户,需 root 权限)。

Zsh:默认配置文件为 ~/.zshrc(临时用户)或 /etc/zshrc(全局用户)

 

三、如何确认自己的默认终端呢?使用 echo $SHELL 命令即可。

结果说明:

输出 /bin/bash 或 /usr/bin/bash → Bash

输出 /bin/zsh 或 /usr/bin/zsh → Zsh

 

root@master1:~# echo $SHELL

/bin/bash

可以看到我使用的bash.

 

四、接下来就进入etc目录,看到有一个bash.bashrc 文件,查看一下。

 

root@master1:/etc# cat bash.bashrc

# System-wide .bashrc file for interactive bash(1) shells.

 

# To enable the settings / commands in this file for login shells as well,

# this file has to be sourced in /etc/profile.

 

# If not running interactively, don't do anything

[ -z "$PS1" ] && return

 

# check the window size after each command and, if necessary,

# update the values of LINES and COLUMNS.

shopt -s checkwinsize

 

# set variable identifying the chroot you work in (used in the prompt below)

if [ -z "${debian_chroot:-}" ] && [ -r /etc/debian_chroot ]; then

    debian_chroot=$(cat /etc/debian_chroot)

fi

 

# set a fancy prompt (non-color, overwrite the one in /etc/profile)

# but only if not SUDOing and have SUDO_PS1 set; then assume smart user.

if ! [ -n "${SUDO_USER}" -a -n "${SUDO_PS1}" ]; then

  PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '

fi

 

# Commented out, don't overwrite xterm -T "title" -n "icontitle" by default.

# If this is an xterm set the title to user@host:dir

#case "$TERM" in

#xterm*|rxvt*)

#    PROMPT_COMMAND='echo -ne "\033]0;${USER}@${HOSTNAME}: ${PWD}\007"'

#    ;;

#*)

#    ;;

#esac

 

# enable bash completion in interactive shells

#if ! shopt -oq posix; then

#  if [ -f /usr/share/bash-completion/bash_completion ]; then

#    . /usr/share/bash-completion/bash_completion

#  elif [ -f /etc/bash_completion ]; then

#    . /etc/bash_completion

#  fi

#fi

 

# sudo hint

if [ ! -e "$HOME/.sudo_as_admin_successful" ] && [ ! -e "$HOME/.hushlogin" ] ; then

    case " $(groups) " in *\ admin\ *|*\ sudo\ *)

    if [ -x /usr/bin/sudo ]; then

        cat <<-EOF

        To run a command as administrator (user "root"), use "sudo <command>".

        See "man sudo_root" for details.

 

        EOF

    fi

    esac

fi

 

# if the command-not-found package is installed, use it

if [ -x /usr/lib/command-not-found -o -x /usr/share/command-not-found/command-not-found ]; then

        function command_not_found_handle {

                # check because c-n-f could've been removed in the meantime

                if [ -x /usr/lib/command-not-found ]; then

                   /usr/lib/command-not-found -- "$1"

                   return $?

                elif [ -x /usr/share/command-not-found/command-not-found ]; then

                   /usr/share/command-not-found/command-not-found -- "$1"

                   return $?

                else

                   printf "%s: command not found\n" "$1" >&2

                   return 127

                fi

        }

fi

export PROMPT_COMMAND="history -a; $PROMPT_COMMAND"

 

五、确定就是它了。直接在末尾添加以上设置好的别名,其余不用修改。

root@master1:~# vi /etc/bash.bashrc

 

六、wq保存退出

 

七、查看确定保存成功。

root@master1:~# cat  /etc/bash.bashrc

# System-wide .bashrc file for interactive bash(1) shells.

 

# To enable the settings / commands in this file for login shells as well,

# this file has to be sourced in /etc/profile.

 

# If not running interactively, don't do anything

[ -z "$PS1" ] && return

 

# check the window size after each command and, if necessary,

# update the values of LINES and COLUMNS.

shopt -s checkwinsize

 

# set variable identifying the chroot you work in (used in the prompt below)

if [ -z "${debian_chroot:-}" ] && [ -r /etc/debian_chroot ]; then

    debian_chroot=$(cat /etc/debian_chroot)

fi

 

# set a fancy prompt (non-color, overwrite the one in /etc/profile)

# but only if not SUDOing and have SUDO_PS1 set; then assume smart user.

if ! [ -n "${SUDO_USER}" -a -n "${SUDO_PS1}" ]; then

  PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '

fi

 

# Commented out, don't overwrite xterm -T "title" -n "icontitle" by default.

# If this is an xterm set the title to user@host:dir

#case "$TERM" in

#xterm*|rxvt*)

#    PROMPT_COMMAND='echo -ne "\033]0;${USER}@${HOSTNAME}: ${PWD}\007"'

#    ;;

#*)

#    ;;

#esac

 

# enable bash completion in interactive shells

#if ! shopt -oq posix; then

#  if [ -f /usr/share/bash-completion/bash_completion ]; then

#    . /usr/share/bash-completion/bash_completion

#  elif [ -f /etc/bash_completion ]; then

#    . /etc/bash_completion

#  fi

#fi

 

# sudo hint

if [ ! -e "$HOME/.sudo_as_admin_successful" ] && [ ! -e "$HOME/.hushlogin" ] ; then

    case " $(groups) " in *\ admin\ *|*\ sudo\ *)

    if [ -x /usr/bin/sudo ]; then

        cat <<-EOF

        To run a command as administrator (user "root"), use "sudo <command>".

        See "man sudo_root" for details.

 

        EOF

    fi

    esac

fi

 

# if the command-not-found package is installed, use it

if [ -x /usr/lib/command-not-found -o -x /usr/share/command-not-found/command-not-found ]; then

        function command_not_found_handle {

                # check because c-n-f could've been removed in the meantime

                if [ -x /usr/lib/command-not-found ]; then

                   /usr/lib/command-not-found -- "$1"

                   return $?

                elif [ -x /usr/share/command-not-found/command-not-found ]; then

                   /usr/share/command-not-found/command-not-found -- "$1"

                   return $?

                else

                   printf "%s: command not found\n" "$1" >&2

                   return 127

                fi

        }

fi

export PROMPT_COMMAND="history -a; $PROMPT_COMMAND"

 

alias k="kubectl"

alias kgp="kubectl get pods"

alias kgd="kubectl get deployment"

alias kdp="kubectl describe pod"

alias klf="kubectl logs -f --tail=100"

 

 

九、刷新使得命令生效(这一步非常关键) source /etc/bash.bashrc

 

十、验证

 

root@master1:~# kgp -A  

NAMESPACE           NAME                                      READY   STATUS              RESTARTS        AGE

alertmanager        alertmanager-8488977f69-5dvgx             1/1     Running             15 (24h ago)    26d

grafana             grafata-d85c5cd6d-sxqdm                   1/1     Running             16 (24h ago)    28d

kube-system         calico-kube-controllers-97d84d657-xmdws   1/1     Running             55 (24h ago)    90d

kube-system         calico-node-4qrzw                         1/1     Init:ErrImagePull   30 (24h ago)    85d

kube-system         coredns-56f48d697c-4j6zn                  1/1     Running             0               24h

kube-system         coredns-56f48d697c-pvgf8                  1/1     Running             23 (24h ago)    20d

kube-system         etcd-master1                              1/1     Running             33 (24h ago)    90d

kube-system         kube-apiserver-master1                    1/1     Running             100 (24h ago)   90d

kube-system         kube-controller-manager-master1           1/1     Running             688             39d

kube-system         kube-proxy-tpj77                          1/1     Running             32 (24h ago)    90d

kube-system         kube-scheduler-master1                    1/1     Running             653 (24h ago)   90d

kubesphere-system   extensions-museum-6579984bcb-lmz7j        1/1     Running             32 (24h ago)    90d

kubesphere-system   ks-apiserver-68c485447d-22pqp             1/1     Running             32 (24h ago)    90d

kubesphere-system   ks-console-85964f7cff-9tl47               1/1     Running             0               24h

kubesphere-system   ks-controller-manager-7b9c699cd5-8j7kd    1/1     Running             132 (24h ago)   26d

prometheus          prometheus-785b95f9b-kmx9m                1/1     Running             8 (24h ago)     20d

 

解释:因为之前设置了别名 alias kgp="kubectl get pods" ,所以kgp -A  就等同于 kubectl get pods -A 命令

 

 

root@master1:~# kdp grafata-d85c5cd6d-sxqdm -n grafana

Name:             grafata-d85c5cd6d-sxqdm

Namespace:        grafana

Priority:         0

Service Account:  default

Node:             master1/10.0.12.11

Start Time:       Wed, 06 Aug 2025 12:24:59 +0800

Labels:           app=grafata

                  pod-template-hash=d85c5cd6d

Annotations:      cni.projectcalico.org/containerID: eed22f2109933c053c910e8b33665c44b6fd34440e73c1df7da2773b37710947

                  cni.projectcalico.org/podIP: 10.244.137.90/32

                  cni.projectcalico.org/podIPs: 10.244.137.90/32

                  kubesphere.io/creator: admin

                  kubesphere.io/imagepullsecrets: {}

                  logging.kubesphere.io/logsidecar-config: {}

Status:           Running

IP:               10.244.137.90

IPs:

  IP:           10.244.137.90

Controlled By:  ReplicaSet/grafata-d85c5cd6d

Containers:

  container-1b2ci1:

    Container ID:   containerd://361702fda8bb4f1511c316dab02df06898710ef78054084eacd8b6fb36d88632

    Image:          crpi-.cn-shanghai.personal.cr.aliyuncs.com//grafana:9.5.7-ubuntu

    Image ID:       sha256:65e9e577f20d091ad3a4300f3ec72ec37eecb3bb13915265de3738996536e63d

    Port:           3000/TCP

    Host Port:      0/TCP

    State:          Running

      Started:      Tue, 02 Sep 2025 14:51:45 +0800

    Last State:     Terminated

      Reason:       Unknown

      Exit Code:    255

      Started:      Fri, 15 Aug 2025 09:16:16 +0800

      Finished:     Tue, 02 Sep 2025 14:51:14 +0800

    Ready:          True

    Restart Count:  16

    Environment:    <none>

    Mounts:

      /etc/grafana/grafana.ini from grafana-config-volume (rw,path="grafana.ini")

      /var/lib/grafana from volume-k91lh1 (rw)

      /var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-nqjjl (ro)

Conditions:

  Type               Status

  DisruptionTarget   False

  Initialized        True

  Ready              True

  ContainersReady    True

  PodScheduled       True

Volumes:

  volume-k91lh1:

    Type:       PersistentVolumeClaim (a reference to a PersistentVolumeClaim in the same namespace)

    ClaimName:  grafana-pvc

    ReadOnly:   false

  grafana-config-volume:

    Type:      ConfigMap (a volume populated by a ConfigMap)

    Name:      grafana-config

    Optional:  false

  kube-api-access-nqjjl:

    Type:                    Projected (a volume that contains injected data from multiple sources)

    TokenExpirationSeconds:  3607

    ConfigMapName:           kube-root-ca.crt

    ConfigMapOptional:       <nil>

    DownwardAPI:             true

QoS Class:                   BestEffort

Node-Selectors:              <none>

Tolerations:                 node.kubernetes.io/not-ready:NoExecute op=Exists for 300s

                             node.kubernetes.io/unreachable:NoExecute op=Exists for 300s

Events:                      <none>

root@master1:~#

 

解释:

因为之前设定了alias kdp="kubectl describe pod",所以kdp grafata-d85c5cd6d-sxqdm -n grafana  等同于 kubectl describe pod grafata-d85c5cd6d-sxqdm -n grafana 命令。

 

 

 

root@master1:~# kgd -A

NAMESPACE           NAME                      READY   UP-TO-DATE   AVAILABLE   AGE

alertmanager        alertmanager              1/1     1            1           28d

grafana             grafata                   1/1     1            1           39d

kube-system         calico-kube-controllers   1/1     1            1           90d

kube-system         coredns                   2/2     2            2           90d

kubesphere-system   extensions-museum         1/1     1            1           90d

kubesphere-system   ks-apiserver              1/1     1            1           90d

kubesphere-system   ks-console                1/1     1            1           90d

kubesphere-system   ks-controller-manager     1/1     1            1           90d

prometheus          prometheus                1/1     1            1           39d

 

解释:因为之前设置了别名alias kgd="kubectl get deployment",所以 kgd -A 等同于 kubectl get deployment -A命令。

 

怎么样?是不是学会了。是不是大大提高了运维效率?

至少我觉得是,O(∩_∩)O哈哈~

 

posted @ 2025-09-03 15:09  华哥来也  阅读(43)  评论(0)    收藏  举报
回到顶部
回到顶部