kubectl常用命令

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<shuangcui@~>$ kubectl
kubectl controls the Kubernetes cluster manager.

Find more information at: https://kubernetes.io/docs/reference/kubectl/overview/

Basic Commands (Beginner):
create Create a resource from a file or from stdin.
expose Take a replication controller, service, deployment or pod and expose it as a new Kubernetes Service
run Run a particular image on the cluster
set Set specific features on objects

Basic Commands (Intermediate):
explain Documentation of resources
get Display one or many resources
edit Edit a resource on the server
delete Delete resources by filenames, stdin, resources and names, or by resources and label selector

Deploy Commands:
rollout Manage the rollout of a resource
scale Set a new size for a Deployment, ReplicaSet, Replication Controller, or Job
autoscale Auto-scale a Deployment, ReplicaSet, or ReplicationController

Cluster Management Commands:
certificate Modify certificate resources.
cluster-info Display cluster info
top Display Resource (CPU/Memory/Storage) usage.
cordon Mark node as unschedulable
uncordon Mark node as schedulable
drain Drain node in preparation for maintenance
taint Update the taints on one or more nodes

Troubleshooting and Debugging Commands:
describe Show details of a specific resource or group of resources
logs Print the logs for a container in a pod
attach Attach to a running container
exec Execute a command in a container
port-forward Forward one or more local ports to a pod
proxy Run a proxy to the Kubernetes API server
cp Copy files and directories to and from containers.
auth Inspect authorization

Advanced Commands:
diff Diff live version against would-be applied version
apply Apply a configuration to a resource by filename or stdin
patch Update field(s) of a resource using strategic merge patch
replace Replace a resource by filename or stdin
wait Experimental: Wait for a specific condition on one or many resources.
convert Convert config files between different API versions
kustomize Build a kustomization target from a directory or a remote url.

Settings Commands:
label Update the labels on a resource
annotate Update the annotations on a resource
completion Output shell completion code for the specified shell (bash or zsh)

Other Commands:
api-resources Print the supported API resources on the server
api-versions Print the supported API versions on the server, in the form of "group/version"
config Modify kubeconfig files
plugin Provides utilities for interacting with plugins.
version Print the client and server version information

Usage:
kubectl [flags] [options]

Use "kubectl <command> --help" for more information about a given command.
Use "kubectl options" for a list of global command-line options (applies to all commands).


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93

<shuangcui@~>$ kubectl get --help
Display one or many resources

Prints a table of the most important information about the specified resources. You can filter the list using a label
selector and the --selector flag. If the desired resource type is namespaced you will only see results in your current
namespace unless you pass --all-namespaces.

Uninitialized objects are not shown unless --include-uninitialized is passed.

By specifying the output as 'template' and providing a Go template as the value of the --template flag, you can filter
the attributes of the fetched resources.

Use "kubectl api-resources" for a complete list of supported resources.

Examples:
# List all pods in ps output format.
kubectl get pods

# List all pods in ps output format with more information (such as node name).
kubectl get pods -o wide

# List a single replication controller with specified NAME in ps output format.
kubectl get replicationcontroller web

# List deployments in JSON output format, in the "v1" version of the "apps" API group:
kubectl get deployments.v1.apps -o json

# List a single pod in JSON output format.
kubectl get -o json pod web-pod-13je7

# List a pod identified by type and name specified in "pod.yaml" in JSON output format.
kubectl get -f pod.yaml -o json

# List resources from a directory with kustomization.yaml - e.g. dir/kustomization.yaml.
kubectl get -k dir/

# Return only the phase value of the specified pod.
kubectl get -o template pod/web-pod-13je7 --template={{.status.phase}}

# List resource information in custom columns.
kubectl get pod test-pod -o custom-columns=CONTAINER:.spec.containers[0].name,IMAGE:.spec.containers[0].image

# List all replication controllers and services together in ps output format.
kubectl get rc,services

# List one or more resources by their type and names.
kubectl get rc/web service/frontend pods/web-pod-13je7

Options:
-A, --all-namespaces=false: If present, list the requested object(s) across all namespaces. Namespace in current
context is ignored even if specified with --namespace.
--allow-missing-template-keys=true: If true, ignore any errors in templates when a field or map key is missing in
the template. Only applies to golang and jsonpath output formats.
--chunk-size=500: Return large lists in chunks rather than all at once. Pass 0 to disable. This flag is beta and
may change in the future.
--field-selector='': Selector (field query) to filter on, supports '=', '==', and '!='.(e.g. --field-selector
key1=value1,key2=value2). The server only supports a limited number of field queries per type.
-f, --filename=[]: Filename, directory, or URL to files identifying the resource to get from a server.
--ignore-not-found=false: If the requested object does not exist the command will return exit code 0.
-k, --kustomize='': Process the kustomization directory. This flag can't be used together with -f or -R.
-L, --label-columns=[]: Accepts a comma separated list of labels that are going to be presented as columns. Names are
case-sensitive. You can also use multiple flag options like -L label1 -L label2...
--no-headers=false: When using the default or custom-column output format, don't print headers (default print
headers).
-o, --output='': Output format. One of:
json|yaml|wide|name|custom-columns=...|custom-columns-file=...|go-template=...|go-template-file=...|jsonpath=...|jsonpath-file=...
See custom columns [http://kubernetes.io/docs/user-guide/kubectl-overview/#custom-columns], golang template
[http://golang.org/pkg/text/template/#pkg-overview] and jsonpath template
[http://kubernetes.io/docs/user-guide/jsonpath].
--raw='': Raw URI to request from the server. Uses the transport specified by the kubeconfig file.
-R, --recursive=false: Process the directory used in -f, --filename recursively. Useful when you want to manage
related manifests organized within the same directory.
-l, --selector='': Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2)
--server-print=true: If true, have the server return the appropriate table output. Supports extension APIs and
CRDs.
--show-kind=false: If present, list the resource type for the requested object(s).
--show-labels=false: When printing, show all labels as the last column (default hide labels column)
--sort-by='': If non-empty, sort list types using this field specification. The field specification is expressed
as a JSONPath expression (e.g. '{.metadata.name}'). The field in the API resource specified by this JSONPath expression
must be an integer or a string.
--template='': Template string or path to template file to use when -o=go-template, -o=go-template-file. The
template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview].
-w, --watch=false: After listing/getting the requested object, watch for changes. Uninitialized objects are excluded
if no object name is provided.
--watch-only=false: Watch for changes to the requested object(s), without listing/getting first.

Usage:
kubectl get
[(-o|--output=)json|yaml|wide|custom-columns=...|custom-columns-file=...|go-template=...|go-template-file=...|jsonpath=...|jsonpath-file=...]
(TYPE[.VERSION][.GROUP] [NAME | -l label] | TYPE[.VERSION][.GROUP]/NAME ...) [flags] [options]

Use "kubectl options" for a list of global command-line options (applies to all commands).

写段脚本,自动进入某个pod中

这段代码什么意思

1
2
3
4
5
6
7
#!/bin/bash


pod=`kubectl -n taskon get pod --selector='app=taskon-backend-golang-withlog' |sed 1d |awk '{print $1}'`


kubectl -n taskon exec -it $pod -- bash

这段代码是一个 Bash 脚本,用于执行一系列的 kubectl 命令来操作 Kubernetes 集群。

首先,这段代码使用 kubectl 命令查询指定命名空间(taskon)中符合特定标签选择器(app=taskon-backend-golang-withlog)的 Pod。kubectl 命令的输出结果会经过一系列的处理操作,包括使用 sed 命令删除第一行(标题行),然后使用 awk 命令提取第一列(Pod 名称),将结果保存到变量 pod 中。

接下来,代码使用 kubectl 命令执行以下操作:

1
kubectl -n taskon exec -it $pod -- bash

该命令的作用是在指定命名空间(taskon)中的特定 Pod 上执行一个交互式的 Bash Shell。-n 参数指定命名空间,exec 命令用于在 Pod 内执行命令,-it 参数表示要创建一个交互式的终端会话,$pod 是之前查询到的 Pod 名称,-- bash 表示要执行的命令是 Bash Shell。

因此,整个代码的目的是在特定命名空间的特定 Pod 上创建一个交互式的 Bash Shell 会话,以便用户可以在该 Pod 内执行 Shell 命令。


pod=$(kubectl -n taskon get pod –selector=”$label” | sed 1d | awk ‘{print $1}’)什么意思


这段代码是一个 Bash 脚本中的命令,用于获取指定标签选择器的 Pod 名称。

让我们逐步解释这段代码:

  1. kubectl -n taskon get pod --selector="$label":这是一个 kubectl 命令,用于查询指定命名空间(taskon)中符合给定标签选择器(存储在 $label 变量中)条件的 Pod。--selector 参数用于指定标签选择器。
  2. sed 1d:这是一个 sed 命令,用于删除命令输出结果的第一行。这通常是标题行,我们在脚本中不需要它。
  3. awk '{print $1}':这是一个 awk 命令,用于提取命令输出结果的第一列。在这种情况下,我们希望提取 Pod 的名称(位于第一列),并将其保存到变量 pod 中。

因此,整个命令的目的是使用 kubectl 命令查询指定命名空间中符合给定标签选择器条件的 Pod,并从输出中提取第一列(Pod 的名称),最后将名称保存到变量 pod 中供后续使用。

请注意,变量 $label 在执行该命令之前应该被正确赋值,以包含所需的标签选择器。


现在我想加一个过滤条件,要求pod的状态必须是Running


要添加一个过滤条件,要求 Pod 的状态必须为 Running,你可以在 kubectl 命令中使用 --field-selector 参数。

以下是修改后的代码示例:

1
pod=$(kubectl -n taskon get pod --selector="$label" --field-selector=status.phase=Running | sed 1d | awk '{print $1}')

在这个示例中,我们添加了 --field-selector=status.phase=Running 参数到 kubectl 命令中。status.phase 字段表示 Pod 的运行状态,通过设置为 “Running”,我们将只获取状态为 Running 的 Pod。

这样,命令将仅返回满足标签选择器和状态为 Running 的 Pod,并将第一列(Pod 的名称)保存到 pod 变量中。

请注意,这里假设你的 Kubernetes 集群使用的是 status.phase 字段来表示 Pod 的运行状态。如果你的集群使用的是其他字段,请相应地修改 --field-selector 参数的值。


现在我有多个服务,假定标签选择器名为server1,server2,server3。 希望扩展这个脚本,当执行时,让我选择输入1,2,3,分别对应server1,server2,server3

要扩展脚本以允许选择输入1、2或3对应于server1、server2或server3,可以使用read命令来获取用户的输入,并根据输入执行相应的操作。以下是修改后的脚本:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#!/bin/bash

echo "请选择要操作的服务:"
echo "1. server1"
echo "2. server2"
echo "3. server3"

read choice

case $choice in
1)
label="server1"
;;
2)
label="server2"
;;
3)
label="server3"
;;
*)
echo "无效的选择"
exit 1
;;
esac

pod=$(kubectl -n taskon get pod --selector="app=$label" | sed 1d | awk '{print $1}')

kubectl -n taskon exec -it $pod -- bash

在修改后的脚本中,首先显示一个选项菜单,要求用户选择要操作的服务。然后使用read命令将用户的选择保存到choice变量中。

使用case语句根据用户的选择设置label变量为相应的标签选择器。如果选择无效,则显示错误消息并退出脚本。

最后,根据label变量的值查询相应的 Pod,并执行kubectl命令以在选择的 Pod 上创建交互式的 Bash Shell 会话。

请注意,这里假设每个服务的标签选择器(server1、server2、server3)与之前提到的标签选择器名称相对应。如果实际情况不同,请相应地修改脚本中的标签选择器和服务名称。

获取某个pod的标签选择器

要获取特定 Pod 的标签选择器,可以使用 kubectl 命令的 get pod 子命令,并通过 --show-labels 参数来显示 Pod 的标签信息。以下是命令的示例:

1
kubectl get pod <pod-name> --show-labels -n <namespace>

请将 <pod-name> 替换为你要获取标签选择器的 Pod 的名称,将 <namespace> 替换为 Pod 所在的命名空间。

执行该命令后,将输出包含有关该 Pod 的信息,其中包括标签选择器。在输出中,您可以查找 LABELS 列,并找到以 app= 开头的标签,该标签的值即为该 Pod 的标签选择器。

请注意,如果您已经执行了 kubectl 命令并通过 --selector 参数筛选了 Pod,那么您可以通过 kubectl 命令的输出来找到 Pod 的标签选择器。在输出的第一行中,您可以找到以 app= 开头的标签,该标签的值即为 Pod 的标签选择器。

如果您希望在脚本中自动获取标签选择器并将其存储到变量中,您可以使用命令输出的文本处理工具(如 awkgrep 等)来提取标签选择器的值,并将其保存到变量中。下面是一个示例脚本:

1
2
3
4
5
6
7
8
9
10
#!/bin/bash

pod_name="<pod-name>"
namespace="<namespace>"

labels=$(kubectl get pod $pod_name --show-labels -n $namespace | awk '/^LABELS/{getline; print}')

label_selector=$(echo $labels | awk -F 'app=' '{print $2}')

echo "Pod的标签选择器为: $label_selector"

在上面的脚本中,将 <pod-name> 替换为您要获取标签选择器的 Pod 的名称,将 <namespace> 替换为 Pod 所在的命名空间。脚本将使用 kubectl 命令获取 Pod 的标签信息,并使用 awk 命令提取以 app= 开头的标签的值,并将其存储在 label_selector 变量中。最后,脚本将打印出 Pod 的标签选择器。


获取全部的

k get pods --show-labels -n taskon


k get pods –show-labels -n taskon 输出结果中,LABELS这一列有个值是app=taskon-backend-golang-withlog,pod-template-hash=678bcbc8f9。后面的pod-template-hash=678bcbc8f9这是什么?

在 Kubernetes 中,pod-template-hash 是由控制器(如 Deployment、ReplicaSet 等)自动生成的标签,用于标识 Pod 模板的特定版本。每当 Pod 模板发生更改时,控制器会创建一个新的副本集(ReplicaSet),并分配一个新的 pod-template-hash 标签值给该副本集中的 Pod。

pod-template-hash 标签的值是根据 Pod 模板的内容计算而来的哈希值,用于确保唯一性。通过将 pod-template-hash 标签添加到 Pod 上,可以确保在 Pod 模板更改时,新的 Pod 副本将被创建,而旧的 Pod 副本将被逐渐停止和删除。

在您提供的输出结果中,LABELS 列包含了两个标签:app=taskon-backend-golang-withlogpod-template-hash=678bcbc8f9。其中,app=taskon-backend-golang-withlog 是您为 Pod 设置的自定义标签,而 pod-template-hash=678bcbc8f9 是由控制器自动生成的用于标识 Pod 模板版本的标签。

通过使用 pod-template-hash 标签,控制器可以跟踪和管理 Pod 模板的变更,并确保在需要更新或回滚时正确地创建、删除和管理 Pod 的副本。

我可以在 Pod 模板中手动更改 pod-template-hash 的值吗?

不建议手动更改 pod-template-hash 的值。pod-template-hash 是由 Kubernetes 控制器自动生成和管理的标签,用于确保唯一性和正确的副本集管理。

手动更改 pod-template-hash 的值可能会导致不一致性和错误的行为。Kubernetes 控制器依赖于 pod-template-hash 标签来识别和管理特定版本的 Pod 模板。如果您手动更改了 pod-template-hash 的值,控制器将无法正确识别和管理与该 Pod 相关的副本集和其他控制器操作。

如果您需要更改 Pod 模板,应该使用 Kubernetes 提供的声明性配置方式,如修改 Deployment、ReplicaSet 等控制器对象的模板部分。这样,Kubernetes 控制器会自动管理 pod-template-hash 的值,并确保正确的版本控制和副本集管理。

总之,应该避免手动更改 pod-template-hash 的值,而是通过适当的声明性配置来管理 Pod 模板的变化。这样可以确保 Kubernetes 控制器正常运行,并保持集群的一致性和可靠性。


所以最终

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

#!/bin/bash

echo "请选择要操作的服务(输入数字并回车):"
echo "1. taskon-server"
echo "2. taskon-reward"
echo "3. taskon-airdrop"

read choice

case $choice in
1)
label="app=taskon-backend-golang-withlog"
;;
2)
label="app=taskon-reward"
;;
3)
label="app=taskon-airdrop-nft-token"
;;
*)
echo "无效的选择"
exit 1
;;
esac


# echo $label;
pod=$(kubectl -n taskon get pod --selector="$label" --field-selector=status.phase=Running | sed 1d | awk '{print $1}')


echo "即将进入pod: $pod";


kubectl -n taskon exec -it $pod -- bash



写一段shell,如果某个变量为空字符串,则输出提示信息,并结束程序

以下是一个示例的 Shell 脚本,用于检查某个变量是否为空字符串并输出提示信息:

1
2
3
4
5
6
7
8
9
10
11
#!/bin/bash

my_variable=""

if [[ -z "$my_variable" ]]; then
echo "变量为空字符串,请提供有效值。"
exit 1
fi

# 继续执行脚本的其他逻辑
echo "变量不为空字符串,可以继续执行脚本。"

在上述脚本中,我们首先将变量 my_variable 设置为空字符串。然后,使用条件语句 if [[ -z "$my_variable" ]]; then 检查该变量是否为空字符串。

如果变量为空字符串,那么将输出提示信息 "变量为空字符串,请提供有效值。"。接着,使用 exit 1 命令退出脚本并返回状态码 1,表示脚本执行出错。

如果变量不为空字符串,那么将输出提示信息 "变量不为空字符串,可以继续执行脚本。"。在这种情况下,你可以在脚本的其他部分继续编写自己的逻辑。

请根据你的实际需求修改变量名和相应的提示信息。


改良一下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43

#!/bin/bash

echo "请选择要操作的服务(输入数字并回车):"
echo "1. taskon-server"
echo "2. taskon-reward"
echo "3. taskon-airdrop"

read choice

case $choice in
1)
label="app=taskon-backend-golang-withlog"
;;
2)
label="app=taskon-reward"
;;
3)
label="app=taskon-airdrop-nft-token"
;;
*)
echo "无效的选择"
exit 1
;;
esac


# echo $label;
pod=$(kubectl -n taskon get pod --selector="$label" --field-selector=status.phase=Running | sed 1d | awk '{print $1}')


if [[ -z "$pod" ]]; then
echo "该标签选择器下,没有处于Running状态的pod,请检查后再试"
echo "脚本将退出"
exit 1
fi


echo "即将进入pod: $pod";


kubectl -n taskon exec -it $pod -- bash


写段脚本,自动cp pod外的某个文件到pod中


k cp ./uploadAddress.xlsx taskon/taskon-backend-golang-withlog-678bcbc8f9-2fg6d:/data/uploadAddress.xlsx

k cp ./taskon-reward taskon/taskon-reward-58d7cffb9f-hzs42:/data/taskon-reward.new

这是一个 kubectl cp 命令的示例,用于将本地文件 ./taskon-reward 复制到运行中的 Kubernetes Pod 中。

让我们逐步解释这个命令:

  • k cp:这是 kubectl cp 命令的简写形式,用于从本地文件系统复制文件到 Pod 或从 Pod 复制文件到本地文件系统。
  • ./taskon-reward:这是要复制的本地文件的路径和名称。./ 表示当前目录,taskon-reward 是文件的名称。
  • taskon/taskon-reward-58d7cffb9f-hzs42:这是目标 Pod 的名称。taskon 是 Pod 所在的命名空间,taskon-reward-58d7cffb9f-hzs42 是 Pod 的名称。
  • :/data/taskon-reward.new:这是目标 Pod 内的路径,指定了复制文件的目标位置。:/data/taskon-reward.new 表示将文件复制到 Pod 内的 /data/taskon-reward.new 路径。

因此,该命令的作用是将本地文件 ./taskon-reward 复制到名为 taskon-reward-58d7cffb9f-hzs42 的 Pod 内的 /data/taskon-reward.new 路径。

请注意,运行此命令需要具有足够的权限,并且保证目标 Pod 的正常运行。

现在我想写一段shell脚本,执行时: 让用户输入要cp到pod中的文件的路径,格式为/a/b/file.txt,我解析拿到file.txt并新定义一个变量newfile,内容为file.txt+当前的年月日时分秒。接着让用户选择要操作的服务,选择输入1、2或3对应于server1、server2或server3,

以下是根据你的要求编写的 Shell 脚本示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#!/bin/bash

# 获取用户输入的文件路径
read -p "请输入要复制到 Pod 中的文件路径(格式为 /a/b/file.txt): " file_path

# 提取文件名
file_name=$(basename "$file_path")

# 定义新文件名
newfile="${file_name}$(date +%Y%m%d%H%M%S)"

# 输出新文件名
echo "新文件名: $newfile"

# 提示用户选择要操作的服务
echo "请选择要操作的服务:"
echo "1. server1"
echo "2. server2"
echo "3. server3"

# 获取用户选择
read -p "请输入选择的服务(1、2 或 3): " choice

# 根据用户选择执行相应的操作
case $choice in
1)
echo "执行 server1 操作"
# 在这里添加 server1 的操作逻辑
;;
2)
echo "执行 server2 操作"
# 在这里添加 server2 的操作逻辑
;;
3)
echo "执行 server3 操作"
# 在这里添加 server3 的操作逻辑
;;
*)
echo "无效的选择"
;;
esac

在这个示例脚本中,首先使用 read 命令获取用户输入的文件路径,并使用 basename 命令提取文件名。然后,使用 date 命令获取当前的年月日时分秒,并将其添加到文件名中,得到新的文件名。

接下来,脚本输出新的文件名,并提示用户选择要操作的服务,然后使用 read 命令获取用户的选择。根据用户的选择,使用 case 语句执行相应的操作逻辑。

你可以在每个选项的操作逻辑部分添加你要执行的实际操作。

请注意,在脚本中可能需要添加错误处理、输入验证等额外的逻辑以增强脚本的健壮性。


加一个判断条件,检测文件是否存在,如果不存在,给出提示并退出


要在脚本中添加检测文件是否存在的条件,并给出相应的提示并退出,可以在用户输入文件路径后加入以下代码:

1
2
3
4
5
# 检测文件是否存在
if [ ! -f "$file_path" ]; then
echo "文件不存在,请检查文件路径。"
exit 1
fi

在这段代码中,我们使用了条件判断语句 if,并结合了文件检测条件 [ -f "$file_path" ]。如果文件不存在(即文件路径不是一个普通文件),则输出提示信息并使用 exit 退出脚本。

完整的代码示例如下:

1
2
3
4
5
6
7
8
9
10
11
12
#!/bin/bash

# 获取用户输入的文件路径
read -p "请输入要复制到 Pod 中的文件路径(格式为 /a/b/file.txt): " file_path

# 检测文件是否存在
if [ ! -f "$file_path" ]; then
echo "文件不存在,请检查文件路径。"
exit 1
fi

echo "要拷贝的文件为:$file_path"

如果用户输入的文件路径不存在或不是一个文件,脚本将会输出提示信息并退出。

在shell脚本中失败时输出执行的命令

要在 Shell 脚本中在执行命令失败时输出执行的命令,你可以将 set -x 命令放置在脚本的开头。这将启用脚本的调试模式,其中每个执行的命令都会被显示出来。

示例代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/bin/bash

# 启用调试模式,输出执行的命令
set -x

# 获取用户输入的文件路径
read -p "请输入要复制到 Pod 中的文件路径(格式为 /a/b/file.txt): " file_path

# 检测文件是否存在
if [ ! -f "$file_path" ]; then
echo "文件不存在,请检查文件路径。"
exit 1
fi

echo "要拷贝的文件为:$file_path"

在这个示例中,set -x 命令启用了调试模式,当脚本执行时,每个命令都会以执行的方式显示在终端。这样,如果执行的命令失败,你就可以看到具体是哪个命令出现了问题。

请注意,在正式运行脚本时,你可以将 set -x 命令注释或删除,以便在不需要调试时禁用调试模式。


完整版:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#!/bin/bash

# 启用调试模式,输出执行的命令
#set -x



# 获取用户输入的文件路径
read -p "请输入要复制到 Pod 中的文件路径(格式为 /a/b/file.txt): " file_path


# 检测文件是否存在
if [ ! -f "$file_path" ]; then
echo "文件不存在,请检查文件路径。"
exit 1
fi



echo "要拷贝的文件为:$file_path";
# 提取文件名
file_name=$(basename "$file_path")

# 定义新文件名
newfile="${file_name}.$(date +%Y%m%d%H%M%S)"

# 输出新文件名
echo "cp到容器中的新文件名为: $newfile (将cp到pod /data/目录下)"

# 提示用户选择要操作的服务
echo "请选择要操作的服务(输入数字并回车):"
echo "1. taskon-server"
echo "2. taskon-reward"
echo "3. taskon-airdrop"

# 获取用户选择
read -p "请输入选择的服务(1、2 或 3): " choice

# 根据用户选择执行相应的操作
case $choice in
1)
label="app=taskon-backend-golang-withlog"
;;
2)
label="app=taskon-reward"
;;
3)
label="app=taskon-airdrop-nft-token"
;;
*)
echo "无效的选择"
exit 1
;;
esac


# echo $label;
pod=$(kubectl -n taskon get pod --selector="$label" --field-selector=status.phase=Running | sed 1d | awk '{print $1}')


if [[ -z "$pod" ]]; then
echo "该标签选择器下,没有处于Running状态的pod,请检查后再试"
echo "脚本将退出"
exit 1
fi


echo "即将cp到pod: $pod 的/data/目录下";
#echo $pod;



kubectl cp $file_path taskon/$pod:/data/$newfile


不要那么灵活,选择1时,就复制 当前目录下的taskon-server到对应pod的/data/目录,同时检测一下修改时间是否在半小时内

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#!/bin/bash

# 启用调试模式,输出执行的命令
#set -x


# 提示用户选择要操作的服务
echo "请选择要操作的服务(输入数字并回车):"
echo "1. taskon-server"
echo "2. taskon-reward"

# 获取用户选择
read -p "请输入选择的服务(1或2): " choice

# 根据用户选择执行相应的操作
case $choice in
1)
label="app=taskon-backend-golang-withlog"
file="taskon-server"
;;
2)
label="app=taskon-reward"
file="taskon-reward"
;;
*)
echo "无效的选择"
exit 1
;;
esac


# 检测文件是否存在
if [ ! -f "$file" ]; then
echo "$file 文件不存在。程序将退出。"
exit 1
fi

# 获取文件最后修改时间的时间戳
last_modified=$(stat -c %Y "$file")

# 获取当前时间的时间戳
current_time=$(date +%s)

# 计算时间差(以分钟为单位)
time_diff=$(( (current_time - last_modified) / 60 ))

echo "$file 文件最后修改时间距离现在已过去 $time_diff 分钟。"



# 检测文件修改时间是否在最近15分钟以内
if [ $time_diff -gt 15 ]; then
echo "$file 文件存在,但修改时间不在最近15分钟以内。程序将退出。"
exit 1
fi



# 执行 SHA1 校验操作
sha1sum_result=$(sha1sum "$file")
# 输出校验结果
echo "文件的 SHA1 校验值为:"
echo "$sha1sum_result"




# # echo $label;
pod=$(kubectl -n taskon get pod --selector="$label" --field-selector=status.phase=Running | sed 1d | awk '{print $1}')


if [[ -z "$pod" ]]; then
echo "该标签选择器下,没有处于Running状态的pod,请检查后再试"
echo "脚本将退出"
exit 1
fi


echo "要拷贝的文件为:$file";

# 定义新文件名
newfile="${file}.new.$(date +%Y%m%d%H%M%S)"

# 输出新文件名

echo "即将cp到pod: $pod 的/data/目录下,新文件名为: $newfile ";



kubectl cp $file taskon/$pod:/data/$newfile



如何检索一个k8s集群用到的全部yaml

要检索一个 Kubernetes(k8s)集群中使用的所有 YAML 文件,可以使用以下方法:

  1. 使用 kubectl 命令行工具获取所有资源的 YAML 表示:
    kubectl get all --all-namespaces -o yaml > all_resources.yaml
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
       这个命令会获取集群中的所有资源(包括 Pod、Deployment、Service 等)的 YAML 表示,并将结果保存到 `all_resources.yaml` 文件中。

    2. 使用 `kubectl` 命令行工具逐个获取每个命名空间中的 YAML 表示:
    ````
    kubectl get all -o yaml --namespace=NAMESPACE > namespace_resources.yaml
    ````
    将 `NAMESPACE` 替换为实际的命名空间名称,这个命令会获取指定命名空间中的所有资源的 YAML 表示,并将结果保存到 `namespace_resources.yaml` 文件中。

    可以根据具体需求选择上述方法之一来获取 YAML 表示。这些命令将使用当前配置的上下文连接到 Kubernetes 集群并执行相应的操作。

    请注意,这些命令将返回每个资源的 YAML 表示,并将其保存到文件中,因此可能会生成较大的文件,具体取决于集群中的资源数量和配置。


    ### 能不能分门别类地存放?比如svc的在一起,configmap的在一起



    当获取到所有资源的 YAML 表示后,你可以通过对 YAML 文件进行筛选和分类来将它们分门别类地存放。这可以使用脚本或命令行工具来完成。以下是一个示例脚本,它使用 `kubectl` 命令行工具和 `grep` 命令来将资源分类并存放到不同的目录中:

    ```bash
    #!/bin/bash

    # 创建目录用于存放不同类型的资源
    mkdir -p svc
    mkdir -p configmap

    # 获取所有资源的 YAML 表示
    kubectl get all --all-namespaces -o yaml > all_resources.yaml

    # 根据资源类型将 YAML 文件移动到对应的目录中
    grep -e "kind: Service" -e "kind: Endpoints" all_resources.yaml > svc/services.yaml
    grep "kind: ConfigMap" all_resources.yaml > configmap/configmaps.yaml

    # 删除生成的临时文件
    rm all_resources.yaml

    echo "资源已按类型分类并存放到对应的目录中。"

在上述示例脚本中,我们通过 mkdir 命令创建了用于存放不同类型资源的目录,比如 svc 目录用于存放服务相关的资源,configmap 目录用于存放配置映射相关的资源。

然后,我们使用 kubectl get all --all-namespaces -o yaml 命令获取所有资源的 YAML 表示,并将结果保存到 all_resources.yaml 文件中。

接下来,我们使用 grep 命令根据资源类型筛选 YAML 文件,并将筛选结果分别保存到对应的目录中的文件中。在示例中,我们使用 -e 选项来指定多个匹配模式,确保我们捕获到每个资源类型的所有变体。

最后,我们删除生成的临时文件,并输出一条提示消息。

请注意,示例脚本仅演示了如何对一些资源类型进行分类,并将其存放到不同的目录中。你可以根据自己的需求和资源类型进行适当的调整和扩展。

整理当前k8s集群用到的全部yaml,分门别类整理好,如何做

要整理当前 Kubernetes(k8s)集群中使用的全部 YAML,并按照资源类型进行分门别类,可以按照以下步骤进行操作:

  1. 获取集群中所有资源的 YAML 表示:

    1
    kubectl get all --all-namespaces -o yaml > all_resources.yaml

    这个命令将获取集群中所有资源(包括 Pod、Deployment、Service、ConfigMap 等)的 YAML 表示,并将结果保存到名为 all_resources.yaml 的文件中。

  2. 创建用于存放分类文件的目录:

    1
    mkdir -p categorized
  3. 使用脚本或命令行工具对 all_resources.yaml 文件进行处理,将不同类型的资源分门别类存放到对应的目录中。以下是一个示例脚本,用于将资源分类并存放到不同的目录中:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    #!/bin/bash

    # 创建目录用于存放不同类型的资源
    mkdir -p categorized/deployments
    mkdir -p categorized/services
    mkdir -p categorized/configmaps

    # 将 Deployment 相关的资源移动到 deployments 目录
    awk '/^---$/{x="";next}{print > ("categorized/deployments/deployment" (x?x:++i) ".yaml")}' all_resources.yaml

    # 将 Service 相关的资源移动到 services 目录
    awk '/^---$/{x="";next}{print > ("categorized/services/service" (x?x:++i) ".yaml")}' all_resources.yaml

    # 将 ConfigMap 相关的资源移动到 configmaps 目录
    awk '/^---$/{x="";next}{print > ("categorized/configmaps/configmap" (x?x:++i) ".yaml")}' all_resources.yaml

    echo "资源已按类型分类并存放到对应的目录中。"

    在上述示例脚本中,我们使用 awk 命令根据资源类型将 YAML 文件中的内容分割成多个文件,并将它们存放到对应的目录中。示例中创建了 deploymentsservicesconfigmaps 目录用于存放对应类型的资源。

    脚本中的 awk 命令使用 /^---$/ 作为分隔符,将 YAML 文件拆分成多个部分。然后,根据每个部分的内容,使用递增的索引将其写入到对应的文件中。

    你可以根据需要调整脚本来适应其他资源类型或目录结构的需求。

  4. 运行脚本并等待执行完成。之后,你将在 categorized 目录下找到根据资源类型分门别类整理好的 YAML 文件。

请注意,这个示例脚本仅提供了一个简单的分类方法,并假设你只关注 Deployment、Service 和 ConfigMap 这几种资源类型。你可以根据实际情况进行扩展和调整,以满足你的具体需求。

k8s集群如何查看kubectl apply -f的文件都在哪里?

在 Kubernetes 集群中,kubectl apply -f 命令会将 YAML 文件中定义的资源对象应用到集群中。Kubernetes 并没有默认的机制来跟踪和记录已应用的 YAML 文件的位置。因此,Kubernetes 本身不提供直接的方法来查看 kubectl apply -f 命令所使用的文件的位置。

然而,你可以通过一些方法来查找已经应用到集群中的 YAML 文件的位置:

  1. 版本控制系统:如果你的 YAML 文件存储在版本控制系统(如 Git)中,你可以通过检查版本控制仓库来确定文件的位置。查看 Git 提交历史记录,你可以找到执行 kubectl apply -f 命令的相关提交记录,从而找到应用的 YAML 文件。

  2. 查找资源:你可以使用 kubectl 命令来查找已经应用到集群的资源对象,然后根据资源对象的定义来确定 YAML 文件的位置。例如,你可以运行以下命令来列出所有的 Deployment 资源,并查看其 YAML 定义:

    1
    2
    kubectl get deployments --all-namespaces -o wide
    kubectl get deployment <deployment-name> -n <namespace> -o yaml

    通过查看资源对象的 YAML 定义,你可以确定使用的 YAML 文件的位置。

  3. 配置管理工具:如果你使用了配置管理工具(例如 Helm、Kustomize 等),它们通常会有自己的目录结构来存放应用的配置文件。你可以查看配置管理工具的文档或项目配置文件,以确定已应用文件的位置。

总结来说,Kubernetes 本身并没有提供直接的方法来查看 kubectl apply -f 命令所使用的文件的位置。你可以通过版本控制系统、资源对象的定义和配置管理工具等途径来确定已应用文件的位置。

k8s中deployment,svc,pod都有什么区别?想创建一个可以对外提供接口访问的后端服务,都需要哪些组件?

在 Kubernetes 中,Deployment、Service 和 Pod 是三个不同的概念,用于实现应用程序的部署、服务暴露和运行。

  1. Deployment(部署)是一种 Kubernetes 资源对象,用于定义应用程序的副本集和部署策略。Deployment 管理着一个或多个 Pod 的创建、更新和删除过程,确保应用程序的副本数量符合期望,并提供滚动更新和回滚等功能。Deployment 是常用的部署应用程序的方式。

  2. Service(服务)是一种 Kubernetes 资源对象,用于公开集群内部的应用程序或 Pod。Service 提供了一个稳定的网络终点,使得其他服务或外部用户能够通过 Service 的 IP 地址和端口访问应用程序。Service 可以根据标签选择器将请求负载均衡到后端的一组 Pod 上。

  3. Pod(容器组)是 Kubernetes 中最小的可部署单元。Pod 包含一个或多个容器(例如 Docker 容器),这些容器共享网络和存储资源,并作为一个单元进行调度和部署。Pod 是运行应用程序的实际实例,可以包含应用程序、依赖的库和其他资源。

对于创建一个可以对外提供接口访问的后端服务,你需要以下组件:

  1. Deployment:创建一个 Deployment 对象,用于定义后端服务的 Pod 模板和部署策略。Deployment 确保指定数量的 Pod 实例在集群中运行,并可以自动进行水平扩展和滚动更新。

  2. Service:创建一个 Service 对象,用于公开后端服务。Service 提供一个稳定的网络终点,其他服务或外部用户可以使用该终点通过 Service 的 IP 地址和端口与后端服务进行通信。

  3. 后端应用程序:创建一个或多个 Pod 对象,其中包含实际的后端应用程序容器。Pod 可以通过 Deployment 进行管理,确保应用程序的副本数量符合预期。

需要注意的是,Pod 是直接运行应用程序的实例,而 Deployment 和 Service 是 Kubernetes 对象,用于管理和公开应用程序。Deployment 确保 Pod 的副本正常运行,Service 提供网络访问的入口。

综上所述,要创建一个可以对外提供接口访问的后端服务,你需要创建一个 Deployment 对象来管理后端应用程序的 Pod,然后创建一个 Service 对象来公开该后端服务。这样,其他服务或外部用户就可以通过 Service 的 IP 地址和端口与后端服务进行通信。

k8s获取当前命名空间下的全部deployment

要获取当前命名空间下所有的 Deployment 对象,可以使用 kubectl 命令或 Kubernetes API 客户端库。

使用 kubectl 命令行工具:

1
kubectl get deployments

该命令会列出当前命名空间下的所有 Deployment 对象,并显示它们的名称、副本数、可用副本数、所用镜像以及创建时间等信息。

如果要获取特定命名空间下的 Deployment 对象,可以使用 --namespace 参数指定命名空间:

1
kubectl get deployments --namespace <namespace>

请将 <namespace> 替换为你希望查询的命名空间名称。

使用 Kubernetes API 客户端库:
如果你使用的是编程语言,如 Python、Go、Java 等,可以使用相应的 Kubernetes API 客户端库来编写代码获取 Deployment 对象。以下是一个使用 Python 客户端库 kubernetes 的示例代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from kubernetes import client, config

# 加载 Kubernetes 配置文件
config.load_kube_config()

# 创建 API 客户端对象
api_instance = client.AppsV1Api()

# 获取当前命名空间下的所有 Deployment
namespace = 'default' # 替换为你的命名空间名称
deployments = api_instance.list_namespaced_deployment(namespace)

# 遍历输出 Deployment 的名称
for deployment in deployments.items:
print(deployment.metadata.name)

请确保你已经安装了 kubernetes Python 客户端库,并按照相应语言的方式配置了 Kubernetes 集群访问。

使用上述方法,你就可以获取当前命名空间下的全部 Deployment 对象。

k8s获取当前命名空间下的全部ReplicaSet

在 Kubernetes 中,ReplicaSet 是用于管理 Pod 副本数量的对象,而 Deployment 则是 ReplicaSet 的高级抽象。因此,要获取当前命名空间下的全部 ReplicaSet 对象,可以使用 kubectl 命令或 Kubernetes API 客户端库。

使用 kubectl 命令行工具:

1
kubectl get replicasets

该命令会列出当前命名空间下的所有 ReplicaSet 对象,并显示它们的名称、所属 Deployment、所需副本数、可用副本数、所属镜像以及创建时间等信息。

如果要获取特定命名空间下的 ReplicaSet 对象,可以使用 --namespace 参数指定命名空间:

1
kubectl get replicasets --namespace <namespace>

请将 <namespace> 替换为你希望查询的命名空间名称。

使用 Kubernetes API 客户端库:
如果你使用的是编程语言,如 Python、Go、Java 等,可以使用相应的 Kubernetes API 客户端库来编写代码获取 ReplicaSet 对象。以下是一个使用 Python 客户端库 kubernetes 的示例代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from kubernetes import client, config

# 加载 Kubernetes 配置文件
config.load_kube_config()

# 创建 API 客户端对象
api_instance = client.AppsV1Api()

# 获取当前命名空间下的所有 ReplicaSet
namespace = 'default' # 替换为你的命名空间名称
replica_sets = api_instance.list_namespaced_replica_set(namespace)

# 遍历输出 ReplicaSet 的名称
for replica_set in replica_sets.items:
print(replica_set.metadata.name)

请确保你已经安装了 kubernetes Python 客户端库,并按照相应语言的方式配置了 Kubernetes 集群访问。

使用上述方法,你就可以获取当前命名空间下的全部 ReplicaSet 对象。

文章目录

  1. 写段脚本,自动进入某个pod中
    1. 这段代码什么意思
    2. pod=$(kubectl -n taskon get pod –selector=”$label” | sed 1d | awk ‘{print $1}’)什么意思
    3. 现在我想加一个过滤条件,要求pod的状态必须是Running
    4. 现在我有多个服务,假定标签选择器名为server1,server2,server3。 希望扩展这个脚本,当执行时,让我选择输入1,2,3,分别对应server1,server2,server3
    5. 获取某个pod的标签选择器
    6. k get pods –show-labels -n taskon 输出结果中,LABELS这一列有个值是app=taskon-backend-golang-withlog,pod-template-hash=678bcbc8f9。后面的pod-template-hash=678bcbc8f9这是什么?
      1. 我可以在 Pod 模板中手动更改 pod-template-hash 的值吗?
    7. 写一段shell,如果某个变量为空字符串,则输出提示信息,并结束程序
  2. 写段脚本,自动cp pod外的某个文件到pod中
    1. 现在我想写一段shell脚本,执行时: 让用户输入要cp到pod中的文件的路径,格式为/a/b/file.txt,我解析拿到file.txt并新定义一个变量newfile,内容为file.txt+当前的年月日时分秒。接着让用户选择要操作的服务,选择输入1、2或3对应于server1、server2或server3,
    2. 加一个判断条件,检测文件是否存在,如果不存在,给出提示并退出
    3. 在shell脚本中失败时输出执行的命令
  3. 如何检索一个k8s集群用到的全部yaml
    1. 整理当前k8s集群用到的全部yaml,分门别类整理好,如何做
    2. k8s集群如何查看kubectl apply -f的文件都在哪里?
    3. k8s中deployment,svc,pod都有什么区别?想创建一个可以对外提供接口访问的后端服务,都需要哪些组件?
    4. k8s获取当前命名空间下的全部deployment
    5. k8s获取当前命名空间下的全部ReplicaSet