Class: Inspec::Resources::Crontab

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Utils::CommentParser

#parse_comment_line

Constructor Details

#initialize(opts = nil) ⇒ Crontab

Returns a new instance of Crontab.



37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/inspec/resources/crontab.rb', line 37

def initialize(opts = nil)
  if opts.respond_to?(:fetch)
    Hash[opts.map { |k, v| [k.to_sym, v] }]
    @user = opts.fetch(:user, nil)
    @path = opts.fetch(:path, nil)
    raise Inspec::Exceptions::ResourceFailed, "A user or path must be supplied." if @user.nil? && @path.nil?
    raise Inspec::Exceptions::ResourceFailed, "Either user or path must be supplied, not both!" if !@user.nil? && !@path.nil?
  else
    @user = opts
    @path = nil
  end
  @params = read_crontab
end

Instance Attribute Details

#paramsObject (readonly)

Returns the value of attribute params.



33
34
35
# File 'lib/inspec/resources/crontab.rb', line 33

def params
  @params
end

Instance Method Details

#crontab_cmdObject



69
70
71
72
73
74
75
76
77
78
# File 'lib/inspec/resources/crontab.rb', line 69

def crontab_cmd
  if @user.nil?
    "crontab -l"
  elsif inspec.os.aix?
    "crontab -l #{@user}"
  else
    # TODO: the -u scenario needs to be able to do sudo
    "crontab -l -u #{@user}"
  end
end

#parse_crontab_line(l) ⇒ Object



62
63
64
65
66
67
# File 'lib/inspec/resources/crontab.rb', line 62

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

  is_system_crontab? ? parse_system_crontab(data) : parse_user_crontab(data)
end

#read_crontabObject



51
52
53
54
55
56
57
58
59
60
# File 'lib/inspec/resources/crontab.rb', line 51

def read_crontab
  if is_system_crontab?
    raise Inspec::Exceptions::ResourceFailed, "Supplied crontab path '#{@path}' must exist!" unless inspec.file(@path).exist?

    ct = inspec.file(@path).content
  else
    ct = inspec.command(crontab_cmd).stdout
  end
  ct.lines.map { |l| parse_crontab_line(l) }.compact
end

#to_sObject



98
99
100
101
102
103
104
105
106
# File 'lib/inspec/resources/crontab.rb', line 98

def to_s
  if is_system_crontab?
    "crontab for path #{@path}"
  elsif is_user_crontab?
    "crontab for user #{@user}"
  else
    "crontab for current user"
  end
end