Method: Chef::Provider::Cron#action_create

Defined in:
lib/chef/provider/cron.rb

#action_createObject


91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
# File 'lib/chef/provider/cron.rb', line 91

def action_create
  crontab = String.new
  newcron = String.new
  cron_found = false

  newcron << "# Chef Name: #{new_resource.name}\n"
  [ :mailto, :path, :shell, :home ].each do |v|
    newcron << "#{v.to_s.upcase}=#{@new_resource.send(v)}\n" if @new_resource.send(v)
  end
  @new_resource.environment.each do |name, value|
    newcron << "#{name}=#{value}\n"
  end
  newcron << "#{@new_resource.minute} #{@new_resource.hour} #{@new_resource.day} #{@new_resource.month} #{@new_resource.weekday} #{@new_resource.command}\n"

  if @cron_exists
    unless cron_different?
      Chef::Log.debug("Skipping existing cron entry '#{@new_resource.name}'")
      return
    end
    read_crontab.each_line do |line|
      case line.chomp
      when "# Chef Name: #{@new_resource.name}"
        cron_found = true
        next
      when ENV_PATTERN
        crontab << line unless cron_found
        next
      when CRON_PATTERN
        if cron_found
          cron_found = false
          crontab << newcron
          next
        end
      else
        if cron_found # We've got a Chef comment with no following crontab line
          crontab << newcron
          cron_found = false
        end
      end
      crontab << line
    end

    # Handle edge case where the Chef comment is the last line in the current crontab
    crontab << newcron if cron_found

    converge_by("update crontab entry for #{@new_resource}") do
      write_crontab crontab
      Chef::Log.info("#{@new_resource} updated crontab entry")
    end

  else
    crontab = read_crontab unless @cron_empty
    crontab << newcron

    converge_by("add crontab entry for #{@new_resource}") do
      write_crontab crontab
      Chef::Log.info("#{@new_resource} added crontab entry")
    end
  end
end