0 | 是什么
envsubst 的名称源自 environment variable substitution(environment variable substitution),意为环境变量替换,是一款专门用于执行 Shell 环境变量替换的工具程序。
其核心功能在于读取输入数据,识别其中包含的环境变量引用,并将这些引用替换为实际的值,最终输出处理后的结果。在 Linux 和 Unix 操作系统中,该工具通常作为默认组件预装。
借助此命令,用户可以预先配置模板文件,并通过定义环境变量将参数注入模板,从而动态生成最终的配置文件。在 Linux 运维实践中,这是一项既具高阶技巧又极为实用的操作手段。
1 | 怎么用
Usage: envsubst [OPTION] [SHELL-FORMAT]
Substitutes the values of environment variables.
Operation mode:
-v, --variables output the variables occurring in SHELL-FORMAT
Informative output:
-h, --help display this help and exit
-V, --version output version information and exit
In normal operation mode, standard input is copied to standard output,
with references to environment variables of the form $VARIABLE or ${VARIABLE}
being replaced with the corresponding values. If a SHELL-FORMAT is given,
only those environment variables that are referenced in SHELL-FORMAT are
substituted; otherwise all environment variables references occurring in
standard input are substituted.
When --variables is used, standard input is ignored, and the output consists
of the environment variables that are referenced in SHELL-FORMAT, one per line.
以下是对命令行为模式的简要翻译说明:
在常规操作模式下,标准输入内容会被复制到标准输出,同时文中出现的 $VARIABLE 或 ${VARIABLE} 格式的环境变量引用会被替换为相应的值。若提供了 SHELL-FORMAT 参数,则仅替换该格式中引用的环境变量;否则,输入中出现的所有环境变量引用均会被替换。
当使用 --variables 选项时,标准输入将被忽略,输出内容仅由 SHELL-FORMAT 中引用的环境变量组成,每个变量名占一行。
2 | 举例说明
首先,假设存在如下一个模板文件:
$ cat envsubst-template.yaml
apiVersion: v1
kind: Deploy
metadata:
name: $name
namespace: $ns
接下来,通过几种不同的案例来演示 envsubst 的使用,以便更深入地理解其工作机制。
- 案例 1 | envsubst-template 从当前环境中获取变量 name 和 ns 的值,将替换后的 YAML 内容重定向保存至 envsubst-1.yaml 文件中。
$ name='hello' ns='world' envsubst < envsubst-template.yaml > envsubst-1.yaml
$ cat envsubst-1.yaml
apiVersion: v1
kind: Deploy
metadata:
name: hello
namespace: world
需要注意的是,$ name='hello' ns='world' envsubst < envsubst-template.yaml > envsubst-1.yaml 中的变量也可以通过 export 命令预先定义:
$ export name='hello'
$ export ns='world'
$ envsubst < envsubst-template.yaml > envsubst-1.yaml
- 案例 2 | 与案例 1 的区别在于指定了 SHELL-FORMAT 为
$name,这意味着仅将模板 YAML 中的$name变量用 envsubst 传入的值进行替换,而其他变量(如$ns)保持原样不变。
$ name='hello' ns='world' envsubst '$name'< envsubst-template.yaml > envsubst-2.yaml
$ cat envsubst-2.yaml
apiVersion: v1
kind: Deploy
metadata:
name: hello
namespace: $ns
- 案例 3 | 主要展示 --variables 选项的作用:可以看到,启用该选项后,标准输入被忽略,输出结果仅包含 SHELL-FORMAT 中引用的环境变量名称。
$ name='hello' ns='world' envsubst --variables '$name'< envsubst-template.yaml > envsubst-3.yaml
$ cat envsubst-3.yaml
name
- 案例 4 | 同样展示 --variables 选项的作用:启用后,标准输入被忽略,输出由 SHELL-FORMAT 中引用的环境变量组成,每行一个变量名。
$ name='hello' ns='world' envsubst --variables '$name,$ns'< envsubst-template.yaml > envsubst-4.yaml
$ cat envsubst-4.yaml
name
ns
以上就是高级开发运维测试必须掌握的envsubst命令使用详解的详细内容,更多关于开发运维测试envsubst命令的资料请关注本站其它相关文章!