我如何设置一个流浪者箱,使其始终有一个cron工作?

我如何设置一个流浪者箱,使其始终有一个cron工作?,cron,vagrant,vagrantfile,Cron,Vagrant,Vagrantfile,如何配置Vagrant配置,以便在配置机器时自动配置其crontab?(根据厨师(?)文件提供流浪汉) 例如,我希望设置以下cron: 5 * * * * curl http://www.google.com 这样的基本资源调配可以很容易地完成,而无需Chef/Puppet/Ansible,而是使用shell 在让box从boostrap.sh下载Apache的示例中,本文很好地介绍了这一基本配置 类似地,您可以按照相同的步骤编辑Vagrant文件,以便在设置时调用bootstrap.sh文件

如何配置Vagrant配置,以便在配置机器时自动配置其crontab?(根据厨师(?)文件提供流浪汉)

例如,我希望设置以下cron:

5 * * * * curl http://www.google.com

这样的基本资源调配可以很容易地完成,而无需Chef/Puppet/Ansible,而是使用shell

在让box从boostrap.sh下载Apache的示例中,本文很好地介绍了这一基本配置

类似地,您可以按照相同的步骤编辑Vagrant文件,以便在设置时调用bootstrap.sh文件:

Vagrant.configure("2") do |config|
  ...
  config.vm.provision :shell, path: "bootstrap.sh"
  ...
end
然后,您可以在与Vagrant文件相同的目录中创建bootstrap.sh文件,该文件将包含以下内容:

#!/bin/bash
# Adds a crontab entry to curl google.com every hour on the 5th minute

# Cron expression
cron="5 * * * * curl http://www.google.com"
    # │ │ │ │ │
    # │ │ │ │ │
    # │ │ │ │ └───── day of week (0 - 6) (0 to 6 are Sunday to Saturday, or use names; 7 is Sunday, the same as 0)
    # │ │ │ └────────── month (1 - 12)
    # │ │ └─────────────── day of month (1 - 31)
    # │ └──────────────────── hour (0 - 23)
    # └───────────────────────── min (0 - 59)

# Escape all the asterisks so we can grep for it
cron_escaped=$(echo "$cron" | sed s/\*/\\\\*/g)

# Check if cron job already in crontab
crontab -l | grep "${cron_escaped}"
if [[ $? -eq 0 ]] ;
  then
    echo "Crontab already exists. Exiting..."
    exit
  else
    # Write out current crontab into temp file
    crontab -l > mycron
    # Append new cron into cron file
    echo "$cron" >> mycron
    # Install new cron file
    crontab mycron
    # Remove temp file
    rm mycron
fi
默认情况下,Vagrant Provisioniers以root用户身份运行,因此这将向root用户的crontab追加一个cron作业,假设它不存在。如果要将其添加到流浪用户的crontab中,则需要运行provisioner,并将
privileged
标志设置为
false

config.vm.provision :shell, path: "bootstrap.sh", privileged: false

实际上,我认为这将把它作为root的cron,因为除非特权标志设置为false,否则配置脚本将作为root运行。感谢@BrianMorton good spot,我已经用它更新了答案,var名称是cron_-escape是正确的,但是在grep中,我们用${cronescape}检查,所以没有下划线?非常感谢。