Chef infra chef在cron资源上添加一个变量

Chef infra chef在cron资源上添加一个变量,chef-infra,Chef Infra,我正在尝试使用chef中的cron资源配置cron作业 cron "execute_mytask" do action :create hour "0" minute "0" command '/bin/date >> /var/log/mytask.log; /usr/bin/php /var/www/mysite/index.php cli/cron mytask "192.168.XXX.YYY" >> /var/

我正在尝试使用chef中的cron资源配置cron作业

cron "execute_mytask" do
    action :create
    hour "0"
    minute "0"
    command '/bin/date >> /var/log/mytask.log; 
    /usr/bin/php /var/www/mysite/index.php cli/cron mytask "192.168.XXX.YYY" 
    >> /var/log/mytask.log 2>&1'
end
其中192.168.XXX.YYY在开发环境和生产环境之间是不同的 它可以是域名或IP地址

当我试图通过添加变量/属性来更改命令行时,就会出现问题。例如,当我将cron条目修改为

command '/bin/date >> /var/log/mytask.log; 
  /usr/bin/php /var/www/mysite/index.php cli/cron 
  mytask "#{node["MyApp"]["IPAddress"]}" >> /var/log/mytask.log 2>&1'
end
那么我在cron工作中得到的是

0 0 * * * /bin/date >> /var/log/mytask.log; 
/usr/bin/php /var/www/mysite/index.php cli/cron 
mytask "#{node["MyApp"]["IPAddress"]}" >> /var/log/mytask.log 2>&1
所以我能找到的最好方法就是用以下代码硬编码

cron "execute_mytask" do
    action :create
    minute "*/5"
    case node.chef_environment
    when 'develop'
      command '/bin/date >> /var/log/mytask.log; 
      /usr/bin/php /var/www/mysite/index.php cli/cron 
      mytask "192.168.XXX.1" >> /var/log/mytask.log 2>&1'
end
    when 'production'
      command '/bin/date >> /var/log/mytask.log; 
      /usr/bin/php /var/www/mysite/index.php cli/cron 
      mytask "192.168.XXX.2" >> /var/log/mytask.log 2>&1'
    end 
end

有没有办法在cron资源的command部分添加变量/属性?

您需要使用双引号,以便Ruby变量插值工作:

cron "execute_mytask" do
    action :create
    hour "0"
    minute "0"
    command "mytask \"#{node['MyApp']['IPAddress']}\" >> /var/log/mytask.log 2>&1"
end

(仅供参考:我个人更喜欢使用
cron
cookbook及其
cron\u d
资源,该资源将cronjob定义拆分为单独的文件。请参阅-我将呈现涵盖所有任务的shell脚本,如示例中的时间戳功能。它使cron文件更易于理解,并且您可以手动测试/执行cron scripts)

问题似乎在于您引用命令的方式,而不是像现在这样使用单个记号:

command '/bin/date >> /var/log/mytask.log; 
  /usr/bin/php /var/www/mysite/index.php cli/cron 
  mytask "#{node["MyApp"]["IPAddress"]}" >> /var/log/mytask.log 2>&1'
end
在整个过程中使用双引号,并可能更改属性以使用分号,如:

command "/bin/date >> /var/log/mytask.log; 
  /usr/bin/php /var/www/mysite/index.php cli/cron 
  mytask #{node[:MyApp][:IPAddress]} >> /var/log/mytask.log 2>&1"
end

然后您还可以避免使用单引号转义字符,如

,这很有帮助