如何传递参数以在厨师中执行?

how to pass parameter to execute in chef?

我是厨师新手。最近,我在研究资源,我遇到了一个关于如何在 chef 中执行时将参数传递给命令的问题。这是详细信息—— 我搜索了这个页面 - https://discourse.chef.io/t/pass-parameter-to-bash-script-and-call-bash-scripts-in-chef-cookbook/10431 - 它看起来使用 ruby 变量格式 #{xxx} 可以将配方中的变量传递给配方中“执行”中的脚本 我做了一个测试,首先是我的食谱 --

execf="haha"

file '/tmp/e.sh' do
    content '
#!/bin/bash
cat /tmp/e.log
DT=`date +%F" "%T`
echo " "${DT} >> /tmp/e.log
'
    mode '755'
    execf="e1"
    notifies :run, 'execute[e.sh]', :delayed
end

file '/tmp/e2.sh' do
    content '
#!/bin/bash
cat /tmp/e.log
DT=`date +%F" "%T`
echo " "${DT} >> /tmp/e.log
'
    mode '777'
    execf="e2"
    notifies :run, 'execute[e.sh]', :delayed
end

execute 'e.sh' do
    command '/tmp/e.sh #{execf}'
    action :nothing
end

我认为 -- 这可以将资源“e.sh”或“e2.sh”的运行时间记录到e.log。 运行 "chef-client" 时没有语法错误。但令我惊讶的是——#{execf}——在调用 /tmp/e.sh 时始终是一个“”字符串...所以在 e.log 中,我只能看到 --

 2022-05-13 22:04:48
 2022-05-13 22:17:44
 2022-05-13 22:19:07

只有一个 "" 作为 $1 传递给 /tmp/e.sh...起初我认为可能是因为 execf 是 ruby 中的局部变量所以我尝试了@execf和 $execf ... 但都没有用。也许在食谱中,我不应该使用变量,而应该使用节点属性?但是我找不到如何修改资源中的节点属性... 请善意的帮助。提前感谢任何想法。

主要问题是在 command 中使用单引号 ('')。 Ruby 中的单引号不允许对变量 #{execf} 进行插值。您应该将其重写为:

execute 'e.sh' do
  command "/tmp/e.sh #{execf}"
  action :nothing
end

但是 file 资源中的变量赋值(例如 execf="e1")不会有任何效果。 你会得到类似 haha 2022-05-13 22:04:48 在日志中。

编辑

However variable assignment (such as execf="e1") in the file resources will not have any effect.

原来资源中的变量赋值也被编译,并使用最后赋值。