You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Puppet中使用exec命令设置Bash变量报错的解决方法

Puppet Exec命令存储bash结果到变量的错误解决方法

错误原因

Puppet的Exec资源默认不会启动shell解析命令中的变量替换语法(比如$(pwd)),而是直接把整个字符串当作可执行文件去系统路径中查找,因此会出现"Could not find command 'test=$(pwd)'"的错误。

解决办法

有两种方式可以让Exec正确解析bash的变量替换:

方式1:直接调用bash并通过-c参数传递命令

将命令包裹在bash的-c参数中,明确让bash来执行解析:

exec { 'test':
    command => '/bin/bash -c "test=$(pwd)"',
    path    => ['/bin/', '/sbin/', '/usr/bin/', '/usr/sbin/'],
    logoutput => true,
}

方式2:给Exec指定shell参数

通过shell参数指定使用bash作为执行命令的shell,Puppet会自动用bash解析命令中的变量:

exec { 'test':
    command => 'test=$(pwd)',
    path    => ['/bin/', '/sbin/', '/usr/bin/', '/usr/sbin/'],
    shell   => '/bin/bash',
    logoutput => true,
}

额外说明

如果需要将命令结果存入Puppet变量供后续配置使用,上述方法仅在shell环境中定义变量是不够的(shell环境和Puppet主环境隔离),可以使用generate函数直接获取命令输出:

$current_dir = generate('/bin/pwd')
# 后续可以直接使用$current_dir变量

内容的提问来源于stack exchange,提问作者Christian Michael Tan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 02:10:01