| 1 |
# -*- coding: utf-8 -*- |
| 2 |
|
| 3 |
# Copyright: (c) 2012, Dane Summers <[email protected]> |
| 4 |
# Copyright: (c) 2013, Mike Grozak <[email protected]> |
| 5 |
# Copyright: (c) 2013, Patrick Callahan <[email protected]> |
| 6 |
# Copyright: (c) 2015, Evan Kaufman <[email protected]> |
| 7 |
# Copyright: (c) 2015, Luca Berruti <[email protected]> |
| 8 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 9 |
|
| 10 |
from __future__ import annotations |
| 11 |
|
| 12 |
|
| 13 |
DOCUMENTATION = r""" |
| 14 |
--- |
| 15 |
module: cron |
| 16 |
short_description: Manage cron.d and crontab entries |
| 17 |
description: |
| 18 |
- Use this module to manage crontab and environment variables entries. This module allows |
| 19 |
you to create environment variables and named crontab entries, update, or delete them. |
| 20 |
- 'When crontab jobs are managed: the module includes one line with the description of the |
| 21 |
crontab entry C("#Ansible: <name>") corresponding to the O(name) passed to the module, |
| 22 |
which is used by future ansible/module calls to find/check the state. The O(name) |
| 23 |
parameter should be unique, and changing the O(name) value will result in a new cron |
| 24 |
task being created (or a different one being removed).' |
| 25 |
- When environment variables are managed, no comment line is added, but, when the module |
| 26 |
needs to find/check the state, it uses the O(name) parameter to find the environment |
| 27 |
variable definition line. |
| 28 |
- When using symbols such as C(%), they must be properly escaped. |
| 29 |
version_added: "0.9" |
| 30 |
options: |
| 31 |
name: |
| 32 |
description: |
| 33 |
- Description of a crontab entry or, if O(env) is set, the name of environment variable. |
| 34 |
- This parameter is always required as of ansible-core 2.12. |
| 35 |
type: str |
| 36 |
required: yes |
| 37 |
user: |
| 38 |
description: |
| 39 |
- The specific user whose crontab should be modified. |
| 40 |
- When unset, this parameter defaults to the current user. |
| 41 |
type: str |
| 42 |
job: |
| 43 |
description: |
| 44 |
- The command to execute or, if O(env) is set, the value of environment variable. |
| 45 |
- The command should not contain line breaks. |
| 46 |
- Required if O(state=present). |
| 47 |
type: str |
| 48 |
aliases: [ value ] |
| 49 |
state: |
| 50 |
description: |
| 51 |
- Whether to ensure the job or environment variable is present or absent. |
| 52 |
type: str |
| 53 |
choices: [ absent, present ] |
| 54 |
default: present |
| 55 |
cron_file: |
| 56 |
description: |
| 57 |
- If specified, uses this file instead of an individual user's crontab. |
| 58 |
The assumption is that this file is exclusively managed by the module, |
| 59 |
do not use if the file contains multiple entries, NEVER use for /etc/crontab. |
| 60 |
- If this is a relative path, it is interpreted with respect to C(/etc/cron.d). |
| 61 |
- Many Linux distros expect (and some require) the filename portion to consist solely |
| 62 |
of upper- and lower-case letters, digits, underscores, and hyphens. |
| 63 |
- Using this parameter requires you to specify the O(user) as well, unless O(state=absent). |
| 64 |
- Either this parameter or O(name) is required. |
| 65 |
type: path |
| 66 |
backup: |
| 67 |
description: |
| 68 |
- If set, create a backup of the crontab before it is modified. |
| 69 |
The location of the backup is returned in the RV(ignore:backup_file) variable by this module. |
| 70 |
type: bool |
| 71 |
default: no |
| 72 |
minute: |
| 73 |
description: |
| 74 |
- Minute when the job should run (V(0-59), V(*), V(*/2), and so on). |
| 75 |
- Cannot be combined with O(special_time). |
| 76 |
type: str |
| 77 |
default: "*" |
| 78 |
hour: |
| 79 |
description: |
| 80 |
- Hour when the job should run (V(0-23), V(*), V(*/2), and so on). |
| 81 |
- Cannot be combined with O(special_time). |
| 82 |
type: str |
| 83 |
default: "*" |
| 84 |
day: |
| 85 |
description: |
| 86 |
- Day of the month the job should run (V(1-31), V(*), V(*/2), and so on). |
| 87 |
- Cannot be combined with O(special_time). |
| 88 |
type: str |
| 89 |
default: "*" |
| 90 |
aliases: [ dom ] |
| 91 |
month: |
| 92 |
description: |
| 93 |
- Month of the year the job should run (V(JAN-DEC) or V(1-12), V(*), V(*/2), and so on). |
| 94 |
- Cannot be combined with O(special_time). |
| 95 |
type: str |
| 96 |
default: "*" |
| 97 |
weekday: |
| 98 |
description: |
| 99 |
- Day of the week that the job should run (V(SUN-SAT) or V(0-6), V(*), and so on). |
| 100 |
- Cannot be combined with O(special_time). |
| 101 |
type: str |
| 102 |
default: "*" |
| 103 |
aliases: [ dow ] |
| 104 |
special_time: |
| 105 |
description: |
| 106 |
- Special time specification nickname. |
| 107 |
- Cannot be combined with O(minute), O(hour), O(day), O(month) or O(weekday). |
| 108 |
type: str |
| 109 |
choices: [ annually, daily, hourly, monthly, reboot, weekly, yearly ] |
| 110 |
version_added: "1.3" |
| 111 |
disabled: |
| 112 |
description: |
| 113 |
- If the job should be disabled (commented out) in the crontab. |
| 114 |
- Only has effect if O(state=present). |
| 115 |
type: bool |
| 116 |
default: no |
| 117 |
version_added: "2.0" |
| 118 |
env: |
| 119 |
description: |
| 120 |
- If set, manages a crontab's environment variable. |
| 121 |
- New variables are added on top of crontab. |
| 122 |
- O(name) and O(value) parameters are the name and the value of environment variable. |
| 123 |
type: bool |
| 124 |
default: false |
| 125 |
version_added: "2.1" |
| 126 |
insertafter: |
| 127 |
description: |
| 128 |
- Used with O(state=present) and O(env). |
| 129 |
- If specified, the environment variable will be inserted after the declaration of specified environment variable. |
| 130 |
type: str |
| 131 |
version_added: "2.1" |
| 132 |
insertbefore: |
| 133 |
description: |
| 134 |
- Used with O(state=present) and O(env). |
| 135 |
- If specified, the environment variable will be inserted before the declaration of specified environment variable. |
| 136 |
type: str |
| 137 |
version_added: "2.1" |
| 138 |
requirements: |
| 139 |
- cron (any 'vixie cron' conformant variant, like cronie) |
| 140 |
notes: |
| 141 |
- If you are experiencing permissions issues with cron and MacOS, |
| 142 |
you should see the official MacOS documentation for further information. |
| 143 |
author: |
| 144 |
- Dane Summers (@dsummersl) |
| 145 |
- Mike Grozak (@rhaido) |
| 146 |
- Patrick Callahan (@dirtyharrycallahan) |
| 147 |
- Evan Kaufman (@EvanK) |
| 148 |
- Luca Berruti (@lberruti) |
| 149 |
extends_documentation_fragment: |
| 150 |
- action_common_attributes |
| 151 |
attributes: |
| 152 |
check_mode: |
| 153 |
support: full |
| 154 |
diff_mode: |
| 155 |
support: full |
| 156 |
platform: |
| 157 |
support: full |
| 158 |
platforms: posix |
| 159 |
""" |
| 160 |
|
| 161 |
EXAMPLES = r""" |
| 162 |
- name: Ensure a job that runs at 2 and 5 exists. Creates an entry like "0 5,2 * * ls -alh > /dev/null" |
| 163 |
ansible.builtin.cron: |
| 164 |
name: "check dirs" |
| 165 |
minute: "0" |
| 166 |
hour: "5,2" |
| 167 |
job: "ls -alh > /dev/null" |
| 168 |
|
| 169 |
- name: 'Ensure an old job is no longer present. Removes any job that is prefixed by "#Ansible: an old job" from the crontab' |
| 170 |
ansible.builtin.cron: |
| 171 |
name: "an old job" |
| 172 |
state: absent |
| 173 |
|
| 174 |
- name: Creates an entry like "@reboot /some/job.sh" |
| 175 |
ansible.builtin.cron: |
| 176 |
name: "a job for reboot" |
| 177 |
special_time: reboot |
| 178 |
job: "/some/job.sh" |
| 179 |
|
| 180 |
- name: Creates an entry like "PATH=/opt/bin" on top of crontab |
| 181 |
ansible.builtin.cron: |
| 182 |
name: PATH |
| 183 |
env: yes |
| 184 |
job: /opt/bin |
| 185 |
|
| 186 |
- name: Creates an entry like "APP_HOME=/srv/app" and insert it after PATH declaration |
| 187 |
ansible.builtin.cron: |
| 188 |
name: APP_HOME |
| 189 |
env: yes |
| 190 |
job: /srv/app |
| 191 |
insertafter: PATH |
| 192 |
|
| 193 |
- name: Creates a cron file under /etc/cron.d |
| 194 |
ansible.builtin.cron: |
| 195 |
name: yum autoupdate |
| 196 |
weekday: "2" |
| 197 |
minute: "0" |
| 198 |
hour: "12" |
| 199 |
user: root |
| 200 |
job: "YUMINTERACTIVE=0 /usr/sbin/yum-autoupdate" |
| 201 |
cron_file: ansible_yum-autoupdate |
| 202 |
|
| 203 |
- name: Removes a cron file from under /etc/cron.d |
| 204 |
ansible.builtin.cron: |
| 205 |
name: "yum autoupdate" |
| 206 |
cron_file: ansible_yum-autoupdate |
| 207 |
state: absent |
| 208 |
|
| 209 |
- name: Removes "APP_HOME" environment variable from crontab |
| 210 |
ansible.builtin.cron: |
| 211 |
name: APP_HOME |
| 212 |
env: yes |
| 213 |
state: absent |
| 214 |
""" |
| 215 |
|
| 216 |
RETURN = r"""#""" |
| 217 |
|
| 218 |
import os |
| 219 |
import platform |
| 220 |
import pwd |
| 221 |
import re |
| 222 |
import shlex |
| 223 |
import sys |
| 224 |
import tempfile |
| 225 |
|
| 226 |
from ansible.module_utils.basic import AnsibleModule |
| 227 |
from ansible.module_utils.common.file import S_IRWU_RWG_RWO |
| 228 |
from ansible.module_utils.common.text.converters import to_bytes, to_native |
| 229 |
|
| 230 |
|
| 231 |
class CronTabError(Exception): |
| 232 |
pass |
| 233 |
|
| 234 |
|
| 235 |
class CronTab: |
| 236 |
""" |
| 237 |
CronTab object to write time based crontab file |
| 238 |
|
| 239 |
user - the user of the crontab (defaults to current user) |
| 240 |
cron_file - a cron file under /etc/cron.d, or an absolute path |
| 241 |
""" |
| 242 |
|
| 243 |
def __init__(self, module, user=None, cron_file=None): |
| 244 |
self.module = module |
| 245 |
self.user = user |
| 246 |
self.root = os.getuid() == 0 |
| 247 |
self.lines = [] |
| 248 |
self.ansible = "#Ansible: " |
| 249 |
self.n_existing = '' |
| 250 |
self.cron_cmd = self.module.get_bin_path('crontab', required=True) |
| 251 |
|
| 252 |
if cron_file: |
| 253 |
|
| 254 |
if os.path.isabs(cron_file): |
| 255 |
self.cron_file = cron_file |
| 256 |
self.b_cron_file = to_bytes(cron_file, errors='surrogate_or_strict') |
| 257 |
else: |
| 258 |
self.cron_file = os.path.join('/etc/cron.d', cron_file) |
| 259 |
self.b_cron_file = os.path.join(b'/etc/cron.d', to_bytes(cron_file, errors='surrogate_or_strict')) |
| 260 |
else: |
| 261 |
self.cron_file = None |
| 262 |
|
| 263 |
self.read() |
| 264 |
|
| 265 |
def read(self): |
| 266 |
# Read in the crontab from the system |
| 267 |
if self.cron_file: |
| 268 |
# read the cronfile |
| 269 |
try: |
| 270 |
with open(self.b_cron_file, 'rb') as f: |
| 271 |
self.n_existing = to_native(f.read(), errors='surrogate_or_strict') |
| 272 |
self.lines = self.n_existing.splitlines() |
| 273 |
except OSError: |
| 274 |
# cron file does not exist |
| 275 |
return |
| 276 |
except Exception: |
| 277 |
raise CronTabError("Unexpected error:", sys.exc_info()[0]) |
| 278 |
else: |
| 279 |
# FIXME: using safely quoted shell for now, but this really should be two non-shell calls instead. |
| 280 |
(rc, out, err) = self.module.run_command(self._read_user_execute(), use_unsafe_shell=True) |
| 281 |
|
| 282 |
if rc not in (0, 1): # 1 can mean that there are no jobs. |
| 283 |
raise CronTabError("Unable to read crontab") |
| 284 |
|
| 285 |
self.n_existing = out |
| 286 |
|
| 287 |
lines = out.splitlines() |
| 288 |
count = 0 |
| 289 |
for l in lines: |
| 290 |
if count > 2 or (not re.match(r'# DO NOT EDIT THIS FILE - edit the master and reinstall.', l) and |
| 291 |
not re.match(r'# \(/tmp/.*installed on.*\)', l) and |
| 292 |
not re.match(r'# \(.*version.*\)', l)): |
| 293 |
self.lines.append(l) |
| 294 |
else: |
| 295 |
pattern = re.escape(l) + '[\r\n]?' |
| 296 |
self.n_existing = re.sub(pattern, '', self.n_existing, 1) |
| 297 |
count += 1 |
| 298 |
|
| 299 |
def is_empty(self): |
| 300 |
if len(self.lines) == 0: |
| 301 |
return True |
| 302 |
for line in self.lines: |
| 303 |
if line.strip(): |
| 304 |
return False |
| 305 |
return True |
| 306 |
|
| 307 |
def write(self, backup_file=None): |
| 308 |
""" |
| 309 |
Write the crontab to the system. Saves all information. |
| 310 |
""" |
| 311 |
if backup_file: |
| 312 |
fileh = open(backup_file, 'wb') |
| 313 |
elif self.cron_file: |
| 314 |
fileh = open(self.b_cron_file, 'wb') |
| 315 |
else: |
| 316 |
filed, path = tempfile.mkstemp(prefix='crontab') |
| 317 |
os.chmod(path, S_IRWU_RWG_RWO) |
| 318 |
fileh = os.fdopen(filed, 'wb') |
| 319 |
|
| 320 |
fileh.write(to_bytes(self.render())) |
| 321 |
fileh.close() |
| 322 |
|
| 323 |
# return if making a backup |
| 324 |
if backup_file: |
| 325 |
return |
| 326 |
|
| 327 |
# Add the entire crontab back to the user crontab |
| 328 |
if not self.cron_file: |
| 329 |
# FIXME: quoting shell args for now but really this should be two non-shell calls. |
| 330 |
(rc, out, err) = self.module.run_command(self._write_execute(path), use_unsafe_shell=True) |
| 331 |
os.unlink(path) |
| 332 |
|
| 333 |
if rc != 0: |
| 334 |
self.module.fail_json(msg=f"Failed to install new cronfile: {path}", stderr=err, stdout=out, rc=rc) |
| 335 |
|
| 336 |
# set SELinux permissions |
| 337 |
if self.module.selinux_enabled() and self.cron_file: |
| 338 |
self.module.set_default_selinux_context(self.cron_file, False) |
| 339 |
|
| 340 |
def do_comment(self, name): |
| 341 |
return "%s%s" % (self.ansible, name) |
| 342 |
|
| 343 |
def add_job(self, name, job): |
| 344 |
# Add the comment |
| 345 |
self.lines.append(self.do_comment(name)) |
| 346 |
|
| 347 |
# Add the job |
| 348 |
self.lines.append("%s" % (job)) |
| 349 |
|
| 350 |
def update_job(self, name, job): |
| 351 |
return self._update_job(name, job, self.do_add_job) |
| 352 |
|
| 353 |
def do_add_job(self, lines, comment, job): |
| 354 |
lines.append(comment) |
| 355 |
|
| 356 |
lines.append("%s" % (job)) |
| 357 |
|
| 358 |
def remove_job(self, name): |
| 359 |
return self._update_job(name, "", self.do_remove_job) |
| 360 |
|
| 361 |
def do_remove_job(self, lines, comment, job): |
| 362 |
return None |
| 363 |
|
| 364 |
def add_env(self, decl, insertafter=None, insertbefore=None): |
| 365 |
if not (insertafter or insertbefore): |
| 366 |
self.lines.insert(0, decl) |
| 367 |
return |
| 368 |
|
| 369 |
if insertafter: |
| 370 |
other_name = insertafter |
| 371 |
elif insertbefore: |
| 372 |
other_name = insertbefore |
| 373 |
other_decl = self.find_env(other_name) |
| 374 |
if len(other_decl) > 0: |
| 375 |
if insertafter: |
| 376 |
index = other_decl[0] + 1 |
| 377 |
elif insertbefore: |
| 378 |
index = other_decl[0] |
| 379 |
self.lines.insert(index, decl) |
| 380 |
return |
| 381 |
|
| 382 |
self.module.fail_json(msg="Variable named '%s' not found." % other_name) |
| 383 |
|
| 384 |
def update_env(self, name, decl): |
| 385 |
return self._update_env(name, decl, self.do_add_env) |
| 386 |
|
| 387 |
def do_add_env(self, lines, decl): |
| 388 |
lines.append(decl) |
| 389 |
|
| 390 |
def remove_env(self, name): |
| 391 |
return self._update_env(name, '', self.do_remove_env) |
| 392 |
|
| 393 |
def do_remove_env(self, lines, decl): |
| 394 |
return None |
| 395 |
|
| 396 |
def remove_job_file(self): |
| 397 |
try: |
| 398 |
os.unlink(self.cron_file) |
| 399 |
return True |
| 400 |
except OSError: |
| 401 |
# cron file does not exist |
| 402 |
return False |
| 403 |
except Exception: |
| 404 |
raise CronTabError("Unexpected error:", sys.exc_info()[0]) |
| 405 |
|
| 406 |
def find_job(self, name, job=None): |
| 407 |
# attempt to find job by 'Ansible:' header comment |
| 408 |
comment = None |
| 409 |
for l in self.lines: |
| 410 |
if comment is not None: |
| 411 |
if comment == name: |
| 412 |
return [comment, l] |
| 413 |
else: |
| 414 |
comment = None |
| 415 |
elif re.match(r'%s' % self.ansible, l): |
| 416 |
comment = re.sub(r'%s' % self.ansible, '', l) |
| 417 |
|
| 418 |
# failing that, attempt to find job by exact match |
| 419 |
if job: |
| 420 |
for i, l in enumerate(self.lines): |
| 421 |
if l == job: |
| 422 |
# if no leading ansible header, insert one |
| 423 |
if not re.match(r'%s' % self.ansible, self.lines[i - 1]): |
| 424 |
self.lines.insert(i, self.do_comment(name)) |
| 425 |
return [self.lines[i], l, True] |
| 426 |
# if a leading blank ansible header AND job has a name, update header |
| 427 |
elif name and self.lines[i - 1] == self.do_comment(None): |
| 428 |
self.lines[i - 1] = self.do_comment(name) |
| 429 |
return [self.lines[i - 1], l, True] |
| 430 |
|
| 431 |
return [] |
| 432 |
|
| 433 |
def find_env(self, name): |
| 434 |
for index, l in enumerate(self.lines): |
| 435 |
if re.match(r'^%s=' % name, l): |
| 436 |
return [index, l] |
| 437 |
|
| 438 |
return [] |
| 439 |
|
| 440 |
def get_cron_job(self, minute, hour, day, month, weekday, job, special, disabled): |
| 441 |
# normalize any leading/trailing newlines (ansible/ansible-modules-core#3791) |
| 442 |
job = job.strip('\r\n') |
| 443 |
|
| 444 |
if disabled: |
| 445 |
disable_prefix = '#' |
| 446 |
else: |
| 447 |
disable_prefix = '' |
| 448 |
|
| 449 |
if special: |
| 450 |
if self.cron_file: |
| 451 |
return "%s@%s %s %s" % (disable_prefix, special, self.user, job) |
| 452 |
return "%s@%s %s" % (disable_prefix, special, job) |
| 453 |
if self.cron_file: |
| 454 |
return "%s%s %s %s %s %s %s %s" % (disable_prefix, minute, hour, day, month, weekday, self.user, job) |
| 455 |
return "%s%s %s %s %s %s %s" % (disable_prefix, minute, hour, day, month, weekday, job) |
| 456 |
|
| 457 |
def get_jobnames(self): |
| 458 |
jobnames = [] |
| 459 |
|
| 460 |
for l in self.lines: |
| 461 |
if re.match(r'%s' % self.ansible, l): |
| 462 |
jobnames.append(re.sub(r'%s' % self.ansible, '', l)) |
| 463 |
|
| 464 |
return jobnames |
| 465 |
|
| 466 |
def get_envnames(self): |
| 467 |
envnames = [] |
| 468 |
|
| 469 |
for l in self.lines: |
| 470 |
if re.match(r'^\S+=', l): |
| 471 |
envnames.append(l.split('=')[0]) |
| 472 |
|
| 473 |
return envnames |
| 474 |
|
| 475 |
def _update_job(self, name, job, addlinesfunction): |
| 476 |
ansiblename = self.do_comment(name) |
| 477 |
newlines = [] |
| 478 |
comment = None |
| 479 |
|
| 480 |
for l in self.lines: |
| 481 |
if comment is not None: |
| 482 |
addlinesfunction(newlines, comment, job) |
| 483 |
comment = None |
| 484 |
elif l == ansiblename: |
| 485 |
comment = l |
| 486 |
else: |
| 487 |
newlines.append(l) |
| 488 |
|
| 489 |
self.lines = newlines |
| 490 |
|
| 491 |
if len(newlines) == 0: |
| 492 |
return True |
| 493 |
return False # TODO add some more error testing |
| 494 |
|
| 495 |
def _update_env(self, name, decl, addenvfunction): |
| 496 |
newlines = [] |
| 497 |
|
| 498 |
for l in self.lines: |
| 499 |
if re.match(r'^%s=' % name, l): |
| 500 |
addenvfunction(newlines, decl) |
| 501 |
else: |
| 502 |
newlines.append(l) |
| 503 |
|
| 504 |
self.lines = newlines |
| 505 |
|
| 506 |
def render(self): |
| 507 |
""" |
| 508 |
Render this crontab as it would be in the crontab. |
| 509 |
""" |
| 510 |
crons = [] |
| 511 |
for cron in self.lines: |
| 512 |
crons.append(cron) |
| 513 |
|
| 514 |
result = '\n'.join(crons) |
| 515 |
if result: |
| 516 |
result = result.rstrip('\r\n') + '\n' |
| 517 |
return result |
| 518 |
|
| 519 |
def _read_user_execute(self): |
| 520 |
""" |
| 521 |
Returns the command line for reading a crontab |
| 522 |
""" |
| 523 |
user = '' |
| 524 |
if self.user: |
| 525 |
if platform.system() == 'SunOS': |
| 526 |
return "su %s -c '%s -l'" % (shlex.quote(self.user), shlex.quote(self.cron_cmd)) |
| 527 |
if platform.system() == 'AIX': |
| 528 |
return "%s -l %s" % (shlex.quote(self.cron_cmd), shlex.quote(self.user)) |
| 529 |
if platform.system() == 'HP-UX': |
| 530 |
return "%s %s %s" % (self.cron_cmd, '-l', shlex.quote(self.user)) |
| 531 |
if pwd.getpwuid(os.getuid())[0] != self.user: |
| 532 |
user = '-u %s' % shlex.quote(self.user) |
| 533 |
return "%s %s %s" % (self.cron_cmd, user, '-l') |
| 534 |
|
| 535 |
def _write_execute(self, path): |
| 536 |
""" |
| 537 |
Return the command line for writing a crontab |
| 538 |
""" |
| 539 |
user = '' |
| 540 |
if self.user: |
| 541 |
if platform.system() in ['SunOS', 'HP-UX', 'AIX']: |
| 542 |
return "chown %s %s ; su '%s' -c '%s %s'" % ( |
| 543 |
shlex.quote(self.user), shlex.quote(path), shlex.quote(self.user), self.cron_cmd, shlex.quote(path)) |
| 544 |
if pwd.getpwuid(os.getuid())[0] != self.user: |
| 545 |
user = '-u %s' % shlex.quote(self.user) |
| 546 |
return "%s %s %s" % (self.cron_cmd, user, shlex.quote(path)) |
| 547 |
|
| 548 |
|
| 549 |
def main(): |
| 550 |
# The following example playbooks: |
| 551 |
# |
| 552 |
# - cron: name="check dirs" hour="5,2" job="ls -alh > /dev/null" |
| 553 |
# |
| 554 |
# - name: do the job |
| 555 |
# cron: name="do the job" hour="5,2" job="/some/dir/job.sh" |
| 556 |
# |
| 557 |
# - name: no job |
| 558 |
# cron: name="an old job" state=absent |
| 559 |
# |
| 560 |
# - name: sets env |
| 561 |
# cron: name="PATH" env=yes value="/bin:/usr/bin" |
| 562 |
# |
| 563 |
# Would produce: |
| 564 |
# PATH=/bin:/usr/bin |
| 565 |
# # Ansible: check dirs |
| 566 |
# * * 5,2 * * ls -alh > /dev/null |
| 567 |
# # Ansible: do the job |
| 568 |
# * * 5,2 * * /some/dir/job.sh |
| 569 |
|
| 570 |
module = AnsibleModule( |
| 571 |
argument_spec=dict( |
| 572 |
name=dict(type='str', required=True), |
| 573 |
user=dict(type='str'), |
| 574 |
job=dict(type='str', aliases=['value']), |
| 575 |
cron_file=dict(type='path'), |
| 576 |
state=dict(type='str', default='present', choices=['present', 'absent']), |
| 577 |
backup=dict(type='bool', default=False), |
| 578 |
minute=dict(type='str', default='*'), |
| 579 |
hour=dict(type='str', default='*'), |
| 580 |
day=dict(type='str', default='*', aliases=['dom']), |
| 581 |
month=dict(type='str', default='*'), |
| 582 |
weekday=dict(type='str', default='*', aliases=['dow']), |
| 583 |
special_time=dict(type='str', choices=["reboot", "yearly", "annually", "monthly", "weekly", "daily", "hourly"]), |
| 584 |
disabled=dict(type='bool', default=False), |
| 585 |
env=dict(type='bool', default=False), |
| 586 |
insertafter=dict(type='str'), |
| 587 |
insertbefore=dict(type='str'), |
| 588 |
), |
| 589 |
supports_check_mode=True, |
| 590 |
mutually_exclusive=[ |
| 591 |
['insertafter', 'insertbefore'], |
| 592 |
], |
| 593 |
) |
| 594 |
|
| 595 |
name = module.params['name'] |
| 596 |
user = module.params['user'] |
| 597 |
job = module.params['job'] |
| 598 |
cron_file = module.params['cron_file'] |
| 599 |
state = module.params['state'] |
| 600 |
backup = module.params['backup'] |
| 601 |
minute = module.params['minute'] |
| 602 |
hour = module.params['hour'] |
| 603 |
day = module.params['day'] |
| 604 |
month = module.params['month'] |
| 605 |
weekday = module.params['weekday'] |
| 606 |
special_time = module.params['special_time'] |
| 607 |
disabled = module.params['disabled'] |
| 608 |
env = module.params['env'] |
| 609 |
insertafter = module.params['insertafter'] |
| 610 |
insertbefore = module.params['insertbefore'] |
| 611 |
do_install = state == 'present' |
| 612 |
|
| 613 |
changed = False |
| 614 |
res_args = dict() |
| 615 |
|
| 616 |
if cron_file: |
| 617 |
|
| 618 |
if cron_file == '/etc/crontab': |
| 619 |
module.fail_json(msg="Will not manage /etc/crontab via cron_file, see documentation.") |
| 620 |
|
| 621 |
cron_file_basename = os.path.basename(cron_file) |
| 622 |
if not re.search(r'^[A-Z0-9_-]+$', cron_file_basename, re.I): |
| 623 |
module.warn('Filename portion of cron_file ("%s") should consist' % cron_file_basename + |
| 624 |
' solely of upper- and lower-case letters, digits, underscores, and hyphens') |
| 625 |
|
| 626 |
# Ensure all files generated are only writable by the owning user. Primarily relevant for the cron_file option. |
| 627 |
os.umask(int('022', 8)) |
| 628 |
crontab = CronTab(module, user, cron_file) |
| 629 |
|
| 630 |
module.debug('cron instantiated - name: "%s"' % name) |
| 631 |
|
| 632 |
if module._diff: |
| 633 |
diff = dict() |
| 634 |
diff['before'] = crontab.n_existing |
| 635 |
if crontab.cron_file: |
| 636 |
diff['before_header'] = crontab.cron_file |
| 637 |
else: |
| 638 |
if crontab.user: |
| 639 |
diff['before_header'] = 'crontab for user "%s"' % crontab.user |
| 640 |
else: |
| 641 |
diff['before_header'] = 'crontab' |
| 642 |
|
| 643 |
# --- user input validation --- |
| 644 |
|
| 645 |
if special_time and \ |
| 646 |
(True in [(x != '*') for x in [minute, hour, day, month, weekday]]): |
| 647 |
module.fail_json(msg="You cannot combine special_time with any of the time or day/date parameters.") |
| 648 |
|
| 649 |
# cannot support special_time on solaris |
| 650 |
if special_time and platform.system() == 'SunOS': |
| 651 |
module.fail_json(msg="Solaris does not support special_time=... or @reboot") |
| 652 |
|
| 653 |
if do_install: |
| 654 |
if cron_file and not user: |
| 655 |
module.fail_json(msg="To use cron_file=... parameter you must specify user=... as well") |
| 656 |
|
| 657 |
if job is None: |
| 658 |
module.fail_json(msg="You must specify 'job' to install a new cron job or variable") |
| 659 |
|
| 660 |
if (insertafter or insertbefore) and not env: |
| 661 |
module.fail_json(msg="Insertafter and insertbefore parameters are valid only with env=yes") |
| 662 |
|
| 663 |
# if requested make a backup before making a change |
| 664 |
if backup and not module.check_mode: |
| 665 |
(dummy, backup_file) = tempfile.mkstemp(prefix='crontab') |
| 666 |
crontab.write(backup_file) |
| 667 |
|
| 668 |
if env: |
| 669 |
if ' ' in name: |
| 670 |
module.fail_json(msg="Invalid name for environment variable") |
| 671 |
decl = '%s="%s"' % (name, job) |
| 672 |
old_decl = crontab.find_env(name) |
| 673 |
|
| 674 |
if do_install: |
| 675 |
if len(old_decl) == 0: |
| 676 |
crontab.add_env(decl, insertafter, insertbefore) |
| 677 |
changed = True |
| 678 |
if len(old_decl) > 0 and old_decl[1] != decl: |
| 679 |
crontab.update_env(name, decl) |
| 680 |
changed = True |
| 681 |
else: |
| 682 |
if len(old_decl) > 0: |
| 683 |
crontab.remove_env(name) |
| 684 |
changed = True |
| 685 |
else: |
| 686 |
if do_install: |
| 687 |
for char in ['\r', '\n']: |
| 688 |
if char in job.strip('\r\n'): |
| 689 |
module.warn('Job should not contain line breaks') |
| 690 |
break |
| 691 |
|
| 692 |
job = crontab.get_cron_job(minute, hour, day, month, weekday, job, special_time, disabled) |
| 693 |
old_job = crontab.find_job(name, job) |
| 694 |
|
| 695 |
if len(old_job) == 0: |
| 696 |
crontab.add_job(name, job) |
| 697 |
changed = True |
| 698 |
if len(old_job) > 0 and old_job[1] != job: |
| 699 |
crontab.update_job(name, job) |
| 700 |
changed = True |
| 701 |
if len(old_job) > 2: |
| 702 |
crontab.update_job(name, job) |
| 703 |
changed = True |
| 704 |
else: |
| 705 |
old_job = crontab.find_job(name) |
| 706 |
|
| 707 |
if len(old_job) > 0: |
| 708 |
crontab.remove_job(name) |
| 709 |
changed = True |
| 710 |
if crontab.cron_file and crontab.is_empty(): |
| 711 |
if module._diff: |
| 712 |
diff['after'] = '' |
| 713 |
diff['after_header'] = '/dev/null' |
| 714 |
else: |
| 715 |
diff = dict() |
| 716 |
if module.check_mode: |
| 717 |
changed = os.path.isfile(crontab.cron_file) |
| 718 |
else: |
| 719 |
changed = crontab.remove_job_file() |
| 720 |
module.exit_json(changed=changed, cron_file=cron_file, state=state, diff=diff) |
| 721 |
|
| 722 |
# no changes to env/job, but existing crontab needs a terminating newline |
| 723 |
if not changed and crontab.n_existing != '': |
| 724 |
if not (crontab.n_existing.endswith('\r') or crontab.n_existing.endswith('\n')): |
| 725 |
changed = True |
| 726 |
|
| 727 |
res_args = dict( |
| 728 |
jobs=crontab.get_jobnames(), |
| 729 |
envs=crontab.get_envnames(), |
| 730 |
changed=changed |
| 731 |
) |
| 732 |
|
| 733 |
if changed: |
| 734 |
if not module.check_mode: |
| 735 |
crontab.write() |
| 736 |
if module._diff: |
| 737 |
diff['after'] = crontab.render() |
| 738 |
if crontab.cron_file: |
| 739 |
diff['after_header'] = crontab.cron_file |
| 740 |
else: |
| 741 |
if crontab.user: |
| 742 |
diff['after_header'] = 'crontab for user "%s"' % crontab.user |
| 743 |
else: |
| 744 |
diff['after_header'] = 'crontab' |
| 745 |
|
| 746 |
res_args['diff'] = diff |
| 747 |
|
| 748 |
# retain the backup only if crontab or cron file have changed |
| 749 |
if backup and not module.check_mode: |
| 750 |
if changed: |
| 751 |
res_args['backup_file'] = backup_file |
| 752 |
else: |
| 753 |
os.unlink(backup_file) |
| 754 |
|
| 755 |
if cron_file: |
| 756 |
res_args['cron_file'] = cron_file |
| 757 |
|
| 758 |
module.exit_json(**res_args) |
| 759 |
|
| 760 |
|
| 761 |
if __name__ == '__main__': |
| 762 |
main() |