Class: Inspec::Resources::Crontab

Inherits:
Object
  • Object
show all
Includes:
CommentParser
Defined in:
lib/resources/crontab.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from CommentParser

#parse_comment_line

Constructor Details

#initialize(user = nil) ⇒ Crontab

Returns a new instance of Crontab.



34
35
36
37
38
39
# File 'lib/resources/crontab.rb', line 34

def initialize(user = nil)
  @user   = user
  @params = read_crontab

  return skip_resource 'The `crontab` resource is not supported on your OS.' unless inspec.os.unix?
end

Instance Attribute Details

#paramsObject (readonly)

Returns the value of attribute params.



30
31
32
# File 'lib/resources/crontab.rb', line 30

def params
  @params
end

Instance Method Details

#crontab_cmdObject



75
76
77
# File 'lib/resources/crontab.rb', line 75

def crontab_cmd
  @user.nil? ? 'crontab -l' : "crontab -l -u #{@user}"
end

#parse_crontab_line(l) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/resources/crontab.rb', line 45

def parse_crontab_line(l)
  data, = parse_comment_line(l, comment_char: '#', standalone_comments: false)
  return nil if data.nil? || data.empty?

  case data
  when /@hourly .*/
    { 'minute' => '0', 'hour' => '*', 'day' => '*', 'month' => '*', 'weekday' => '*', 'command' => data.split(/\s+/, 2).at(1) }
  when /@(midnight|daily) .*/
    { 'minute' => '0', 'hour' => '0', 'day' => '*', 'month' => '*', 'weekday' => '*', 'command' => data.split(/\s+/, 2).at(1) }
  when /@weekly .*/
    { 'minute' => '0', 'hour' => '0', 'day' => '*', 'month' => '*', 'weekday' => '0', 'command' => data.split(/\s+/, 2).at(1) }
  when /@monthly ./
    { 'minute' => '0', 'hour' => '0', 'day' => '1', 'month' => '*', 'weekday' => '*', 'command' => data.split(/\s+/, 2).at(1) }
  when /@(annually|yearly) .*/
    { 'minute' => '0', 'hour' => '0', 'day' => '1', 'month' => '1', 'weekday' => '*', 'command' => data.split(/\s+/, 2).at(1) }
  when /@reboot .*/
    { 'minute' => '-1', 'hour' => '-1', 'day' => '-1', 'month' => '-1', 'weekday' => '-1', 'command' => data.split(/\s+/, 2).at(1) }
  else
    elements = data.split(/\s+/, 6)
    {
      'minute'  => elements.at(0),
      'hour'    => elements.at(1),
      'day'     => elements.at(2),
      'month'   => elements.at(3),
      'weekday' => elements.at(4),
      'command' => elements.at(5),
    }
  end
end

#read_crontabObject



41
42
43
# File 'lib/resources/crontab.rb', line 41

def read_crontab
  inspec.command(crontab_cmd).stdout.lines.map { |l| parse_crontab_line(l) }.compact
end

#to_sObject



98
99
100
# File 'lib/resources/crontab.rb', line 98

def to_s
  @user.nil? ? 'crontab for current user' : "crontab for user #{@user}"
end