首页 > 解决方案 > 如何从节点获取文件的内容并将其保存在 pod 内的变量中?

问题描述

我正在编写一个要从 pod 运行的自动化脚本。我想获取 pod 内文件的内容并将其保存在变量中。

该文件是:

$ cat ip_addr.txt
10.120.2.21

我的代码是:

kubectl exec -it --namespace=<namespace name> <pod name> -- bash -c "elastisearch=$(cat ipaddr.txt)"

当我运行 ls 或 cd 等其他命令时,它运行良好

当我elastisearch=$(cat ipaddr.txt)在吊舱内运行时,它运行良好。

提前致谢。

标签: bashkubernetes

解决方案


当您使用

kubectl exec -it --namespace=<namespace name> <pod name> -- bash -c "elastisearch=$(cat ipaddr.txt)"

你为这个会话设置它,并且只为这个会话。命令结束时会话结束。
你的情况会发生什么

  1. 开始一个会话bash
  2. 将命令传递给它elastisearch=$(cat ipaddr.txt)
  3. 变量elastisearch已设置
  4. 命令成功结束
  5. 会话结束,shell 被破坏并elastisearch随之变化

您有三种可能的解决方案:

  • elastisearch在同一会话中运行需要变量的命令,例如:
kubectl exec -it --namespace=<namespace name> <pod name> -- bash -c "elastisearch=$(cat ipaddr.txt); some_other_command_that_need_this_variable"
...
spec:
  containers:
  - name: <app-name>
    image: <app-image>
    env:
    - name: elastisearch
      value: "10.120.2.21"
...
ENV elastisearch="10.120.2.21"

推荐阅读