0

I'm trying to set up a cronjob to run a command (in this example ls) once every day. For this I am using the cron resource.

The problem is that I don't know how to test it with Inspect. I tried using crontab but it's not working.

Here's the code:

// code
cron 'my-ls' do
  minute '1'
  hour '0'
  command 'ls'
end

// test
describe crontab.commands('ls') do
  its('minutes') { should cmp '1' }
  its('hours') { should cmp '0' }
end

It's failing saying that:

×  hours should cmp == "0"

     expected: "0"
          got: []

     (compared using `cmp` matcher)

     ×  minutes should cmp == "1"

     expected: "1"
          got: []

     (compared using `cmp` matcher)

PS: I also tried with cron_d using the cron cookbook

Christopher Francisco
  • 15,672
  • 28
  • 94
  • 206

1 Answers1

1

Here's the simplest way I could get these tests working:

Step 1: Create a text file named cronls.txt with this data:

1 0 * * * ls -al

Step 2: Turn it into a cron job with this command:

crontab -a cronls.txt

Step 3: In your Chef cookbook, add these controls to your default_test.rb:

control 'cron-1' do
  describe crontab do
    its('commands') { should include 'ls -al' }
  end
end

control 'cron-2' do
  describe crontab.commands('ls -al') do
    its('minutes') { should cmp '1' }
    its('hours') { should cmp '0' }
  end
end

Step 4: Execute your InSpec tests:

inspec exec test/integration/default/default_test.rb

The results are what you would expect:

  ✔  cron-1: crontab for current user
     ✔  crontab for current user commands should include "ls -al"
  ✔  cron-2: crontab for current user with command == "ls -al"
     ✔  crontab for current user with command == "ls -al" minutes should cmp == "1"
     ✔  crontab for current user with command == "ls -al" hours should cmp == "0"

This isn't the only way to do this (or even the best way), but it should get you going. For more options on the crontab resource, read the InSpec documentation:

https://docs.chef.io/resource_cron.html

james.garriss
  • 12,959
  • 7
  • 83
  • 96