如何让Puppet执行Bash脚本时显示echo及调试输出?
问题
我编写了一个内嵌Bash代码的Puppet脚本,想要让Bash中的echo命令输出以及set -x的调试信息显示在Puppet的执行输出里,以此查看Bash脚本的执行顺序。脚本内容如下:
# Add an XFRM interface $xfrm_config = @("xfrm-config") #!/usr/bin/env bash set -x # Only configure `xfrm0` on the event that `eth0` has been configured if [ "${IFACE}" = "eth0" ] && [ "${STATE}" = "routable" ] && [ "${AdministrativeState}" = "configured" ] && [ "${OperationalState}" = "routable" ]; then # Remove the adapter if it already exists if ip link show xfrm0 > /dev/null 2>&1; then ip link delete xfrm0 echo "step 1" fi # Add and activate the adapter, IP, and route ip link add xfrm0 type xfrm dev eth0 if_id 0xabcd echo "step 2" ip address add ${host_server_net_mesh_vpn_ipv4_address}/32 dev xfrm0 echo "step 3" ip link set xfrm0 up echo "step 4" ip route add ${peer_server_net_mesh_vpn_ipv4_address}/32 dev xfrm0 echo "step 5" fi | xfrm-config file { $xfrm_config_path: ensure => file, owner => 'root', group => 'root', mode => '0755', content => $xfrm_config, } ~> exec { 'add-xfrm-interface': command => $xfrm_config_path, path => '/usr/bin', provider => 'shell', environment => ['IFACE=eth0', 'STATE=routable', 'AdministrativeState=configured', 'OperationalState=routable'], logoutput => true, }
解决方案
要让Bash的echo输出和set -x调试信息显示在Puppet执行输出中,按以下步骤调整:
重定向stderr到stdout:
set -x的调试信息默认输出到stderr,而Puppet的logoutput => true默认仅捕获stdout。在Bash脚本开头添加exec 2>&1,将stderr合并到stdout,这样所有输出都会被Puppet捕获:#!/usr/bin/env bash exec 2>&1 set -x或者使用
BASH_XTRACEFD=1让set -x直接输出到stdout:#!/usr/bin/env bash BASH_XTRACEFD=1 set -x修正脚本语法错误:原脚本中
echo "step 1"的缩进层级错误,会导致逻辑异常,调整为与同块命令同级:if ip link show xfrm0 > /dev/null 2>&1; then ip link delete xfrm0 echo "step 1" fi其余
echo语句的缩进也统一对齐,避免后续维护问题。确认变量解析逻辑:如果
${host_server_net_mesh_vpn_ipv4_address}是Puppet变量,当前写法没问题;如果是要在Bash中使用的环境变量,需要转义为\${host_server_net_mesh_vpn_ipv4_address},防止被Puppet提前解析替换。验证
exec资源配置:已设置的logoutput => true是正确的,它会将命令的输出记录到Puppet日志中;如果需要强制显示所有输出(包括无变更时),可以将logoutput设为'always'。
内容的提问来源于stack exchange,提问作者Callum McCrorie
相关产品推荐
相关产品推荐

