| 1 |
#!/usr/bin/python |
| 2 |
|
| 3 |
# Copyright (c) 2017, Ansible Project |
| 4 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 5 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 6 |
|
| 7 |
# Cronvar Plugin: The goal of this plugin is to provide an idempotent |
| 8 |
# method for set cron variable values. It should play well with the |
| 9 |
# existing cron module as well as allow for manually added variables. |
| 10 |
# Each variable entered will be preceded with a comment describing the |
| 11 |
# variable so that it can be found later. This is required to be |
| 12 |
# present in order for this plugin to find/modify the variable |
| 13 |
|
| 14 |
# This module is based on the crontab module. |
| 15 |
|
| 16 |
from __future__ import annotations |
| 17 |
|
| 18 |
DOCUMENTATION = r""" |
| 19 |
module: cronvar |
| 20 |
short_description: Manage variables in crontabs |
| 21 |
description: |
| 22 |
- Use this module to manage crontab variables. |
| 23 |
- This module allows you to create, update, or delete cron variable definitions. |
| 24 |
extends_documentation_fragment: |
| 25 |
- community.general._attributes |
| 26 |
attributes: |
| 27 |
check_mode: |
| 28 |
support: none |
| 29 |
diff_mode: |
| 30 |
support: none |
| 31 |
options: |
| 32 |
name: |
| 33 |
description: |
| 34 |
- Name of the crontab variable. |
| 35 |
type: str |
| 36 |
required: true |
| 37 |
value: |
| 38 |
description: |
| 39 |
- The value to set this variable to. |
| 40 |
- Required if O(state=present). |
| 41 |
type: str |
| 42 |
insertafter: |
| 43 |
description: |
| 44 |
- If specified, the variable is inserted after the variable specified. |
| 45 |
- Used with O(state=present). |
| 46 |
type: str |
| 47 |
insertbefore: |
| 48 |
description: |
| 49 |
- Used with O(state=present). If specified, the variable is inserted just before the variable specified. |
| 50 |
type: str |
| 51 |
state: |
| 52 |
description: |
| 53 |
- Whether to ensure that the variable is present or absent. |
| 54 |
type: str |
| 55 |
choices: [absent, present] |
| 56 |
default: present |
| 57 |
user: |
| 58 |
description: |
| 59 |
- The specific user whose crontab should be modified. |
| 60 |
- This parameter defaults to V(root) when unset. |
| 61 |
type: str |
| 62 |
cron_file: |
| 63 |
description: |
| 64 |
- If specified, uses this file instead of an individual user's crontab. |
| 65 |
- Without a leading V(/), this is assumed to be in C(/etc/cron.d). |
| 66 |
- With a leading V(/), this is taken as absolute. |
| 67 |
type: str |
| 68 |
backup: |
| 69 |
description: |
| 70 |
- If set, create a backup of the crontab before it is modified. The location of the backup is returned in the C(backup) |
| 71 |
variable by this module. |
| 72 |
type: bool |
| 73 |
default: false |
| 74 |
requirements: |
| 75 |
- cron |
| 76 |
author: |
| 77 |
- Doug Luce (@dougluce) |
| 78 |
""" |
| 79 |
|
| 80 |
EXAMPLES = r""" |
| 81 |
- name: Ensure entry like "[email protected]" exists |
| 82 |
community.general.cronvar: |
| 83 |
name: EMAIL |
| 84 |
value: [email protected] |
| 85 |
|
| 86 |
- name: Ensure a variable does not exist. This may remove any variable named "LEGACY" |
| 87 |
community.general.cronvar: |
| 88 |
name: LEGACY |
| 89 |
state: absent |
| 90 |
|
| 91 |
- name: Add a variable to a file under /etc/cron.d |
| 92 |
community.general.cronvar: |
| 93 |
name: LOGFILE |
| 94 |
value: /var/log/yum-autoupdate.log |
| 95 |
user: root |
| 96 |
cron_file: ansible_yum-autoupdate |
| 97 |
""" |
| 98 |
|
| 99 |
import os |
| 100 |
import platform |
| 101 |
import pwd |
| 102 |
import re |
| 103 |
import shlex |
| 104 |
import tempfile |
| 105 |
from shlex import quote as shlex_quote |
| 106 |
|
| 107 |
from ansible.module_utils.basic import AnsibleModule |
| 108 |
|
| 109 |
|
| 110 |
class CronVarError(Exception): |
| 111 |
pass |
| 112 |
|
| 113 |
|
| 114 |
class CronVar: |
| 115 |
""" |
| 116 |
CronVar object to write variables to crontabs. |
| 117 |
|
| 118 |
user - the user of the crontab (defaults to root) |
| 119 |
cron_file - a cron file under /etc/cron.d |
| 120 |
""" |
| 121 |
|
| 122 |
def __init__(self, module, user=None, cron_file=None): |
| 123 |
self.module = module |
| 124 |
self.user = user |
| 125 |
self.lines = None |
| 126 |
self.wordchars = "".join( |
| 127 |
chr(x) |
| 128 |
for x in range(128) |
| 129 |
if chr(x) |
| 130 |
not in ( |
| 131 |
"=", |
| 132 |
"'", |
| 133 |
'"', |
| 134 |
) |
| 135 |
) |
| 136 |
self.cron_cmd = self.module.get_bin_path("crontab", required=True) |
| 137 |
|
| 138 |
if cron_file: |
| 139 |
self.cron_file = "" |
| 140 |
if os.path.isabs(cron_file): |
| 141 |
self.cron_file = cron_file |
| 142 |
else: |
| 143 |
self.cron_file = os.path.join("/etc/cron.d", cron_file) |
| 144 |
parent_dir = os.path.dirname(self.cron_file) |
| 145 |
if parent_dir and not os.path.isdir(parent_dir): |
| 146 |
module.fail_json(msg=f"Parent directory '{parent_dir}' does not exist for cron_file: '{cron_file}'") |
| 147 |
else: |
| 148 |
self.cron_file = None |
| 149 |
|
| 150 |
self.read() |
| 151 |
|
| 152 |
def read(self): |
| 153 |
# Read in the crontab from the system |
| 154 |
self.lines = [] |
| 155 |
if self.cron_file: |
| 156 |
# read the cronfile |
| 157 |
try: |
| 158 |
with open(self.cron_file) as f: |
| 159 |
self.lines = f.read().splitlines() |
| 160 |
except OSError: |
| 161 |
# cron file does not exist |
| 162 |
return |
| 163 |
except Exception as e: |
| 164 |
raise CronVarError(f"Unexpected error: {e}", type(e)) from e |
| 165 |
else: |
| 166 |
# using safely quoted shell for now, but this really should be two non-shell calls instead. FIXME |
| 167 |
(rc, out, err) = self.module.run_command(self._read_user_execute(), use_unsafe_shell=True) |
| 168 |
|
| 169 |
if rc != 0 and rc != 1: # 1 can mean that there are no jobs. |
| 170 |
raise CronVarError("Unable to read crontab") |
| 171 |
|
| 172 |
lines = out.splitlines() |
| 173 |
for count, l in enumerate(lines): |
| 174 |
if count > 2 or ( |
| 175 |
not re.match(r"# DO NOT EDIT THIS FILE - edit the master and reinstall.", l) |
| 176 |
and not re.match(r"# \(/tmp/.*installed on.*\)", l) |
| 177 |
and not re.match(r"# \(.*version.*\)", l) |
| 178 |
): |
| 179 |
self.lines.append(l) |
| 180 |
|
| 181 |
def log_message(self, message): |
| 182 |
self.module.debug(f'ansible: "{message}"') |
| 183 |
|
| 184 |
def write(self, backup_file=None): |
| 185 |
""" |
| 186 |
Write the crontab to the system. Saves all information. |
| 187 |
""" |
| 188 |
if backup_file: |
| 189 |
fileh = open(backup_file, "w") |
| 190 |
elif self.cron_file: |
| 191 |
fileh = open(self.cron_file, "w") |
| 192 |
path = None |
| 193 |
else: |
| 194 |
filed, path = tempfile.mkstemp(prefix="crontab") |
| 195 |
fileh = os.fdopen(filed, "w") |
| 196 |
|
| 197 |
fileh.write(self.render()) |
| 198 |
fileh.close() |
| 199 |
|
| 200 |
# return if making a backup |
| 201 |
if backup_file: |
| 202 |
return |
| 203 |
|
| 204 |
# Add the entire crontab back to the user crontab |
| 205 |
if not self.cron_file: |
| 206 |
# quoting shell args for now but really this should be two non-shell calls. FIXME |
| 207 |
(rc, out, err) = self.module.run_command(self._write_execute(path), use_unsafe_shell=True) |
| 208 |
os.unlink(path) |
| 209 |
|
| 210 |
if rc != 0: |
| 211 |
self.module.fail_json(msg=err) |
| 212 |
|
| 213 |
def remove_variable_file(self): |
| 214 |
try: |
| 215 |
os.unlink(self.cron_file) |
| 216 |
return True |
| 217 |
except OSError: |
| 218 |
# cron file does not exist |
| 219 |
return False |
| 220 |
except Exception as e: |
| 221 |
raise CronVarError(f"Unexpected error: {e}", type(e)) from e |
| 222 |
|
| 223 |
def parse_for_var(self, line): |
| 224 |
lexer = shlex.shlex(line) |
| 225 |
lexer.wordchars = self.wordchars |
| 226 |
varname = lexer.get_token() |
| 227 |
is_env_var = lexer.get_token() == "=" |
| 228 |
value = "".join(lexer) |
| 229 |
if is_env_var: |
| 230 |
return (varname, value) |
| 231 |
raise CronVarError("Not a variable.") |
| 232 |
|
| 233 |
def find_variable(self, name): |
| 234 |
for l in self.lines: |
| 235 |
try: |
| 236 |
(varname, value) = self.parse_for_var(l) |
| 237 |
if varname == name: |
| 238 |
return value |
| 239 |
except CronVarError: |
| 240 |
pass |
| 241 |
return None |
| 242 |
|
| 243 |
def get_var_names(self): |
| 244 |
var_names = [] |
| 245 |
for l in self.lines: |
| 246 |
try: |
| 247 |
var_name, dummy = self.parse_for_var(l) |
| 248 |
var_names.append(var_name) |
| 249 |
except CronVarError: |
| 250 |
pass |
| 251 |
return var_names |
| 252 |
|
| 253 |
def add_variable(self, name, value, insertbefore, insertafter): |
| 254 |
if insertbefore is None and insertafter is None: |
| 255 |
# Add the variable to the top of the file. |
| 256 |
self.lines.insert(0, f"{name}={value}") |
| 257 |
else: |
| 258 |
newlines = [] |
| 259 |
for l in self.lines: |
| 260 |
try: |
| 261 |
varname, dummy = self.parse_for_var(l) # Throws if not a var line |
| 262 |
if varname == insertbefore: |
| 263 |
newlines.append(f"{name}={value}") |
| 264 |
newlines.append(l) |
| 265 |
elif varname == insertafter: |
| 266 |
newlines.append(l) |
| 267 |
newlines.append(f"{name}={value}") |
| 268 |
else: |
| 269 |
raise CronVarError # Append. |
| 270 |
except CronVarError: |
| 271 |
newlines.append(l) |
| 272 |
|
| 273 |
self.lines = newlines |
| 274 |
|
| 275 |
def remove_variable(self, name): |
| 276 |
self.update_variable(name, None, remove=True) |
| 277 |
|
| 278 |
def update_variable(self, name, value, remove=False): |
| 279 |
newlines = [] |
| 280 |
for l in self.lines: |
| 281 |
try: |
| 282 |
varname, dummy = self.parse_for_var(l) # Throws if not a var line |
| 283 |
if varname != name: |
| 284 |
raise CronVarError # Append. |
| 285 |
if not remove: |
| 286 |
newlines.append(f"{name}={value}") |
| 287 |
except CronVarError: |
| 288 |
newlines.append(l) |
| 289 |
|
| 290 |
self.lines = newlines |
| 291 |
|
| 292 |
def render(self): |
| 293 |
""" |
| 294 |
Render a proper crontab |
| 295 |
""" |
| 296 |
result = "\n".join(self.lines) |
| 297 |
if result and result[-1] not in ["\n", "\r"]: |
| 298 |
result += "\n" |
| 299 |
return result |
| 300 |
|
| 301 |
def _read_user_execute(self): |
| 302 |
""" |
| 303 |
Returns the command line for reading a crontab |
| 304 |
""" |
| 305 |
user = "" |
| 306 |
|
| 307 |
if self.user: |
| 308 |
if platform.system() == "SunOS": |
| 309 |
return f"su {shlex_quote(self.user)} -c '{shlex_quote(self.cron_cmd)} -l'" |
| 310 |
elif platform.system() == "AIX": |
| 311 |
return f"{shlex_quote(self.cron_cmd)} -l {shlex_quote(self.user)}" |
| 312 |
elif platform.system() == "HP-UX": |
| 313 |
return f"{self.cron_cmd} -l {shlex_quote(self.user)}" |
| 314 |
elif pwd.getpwuid(os.getuid())[0] != self.user: |
| 315 |
user = f"-u {shlex_quote(self.user)}" |
| 316 |
return f"{self.cron_cmd} {user} -l" |
| 317 |
|
| 318 |
def _write_execute(self, path): |
| 319 |
""" |
| 320 |
Return the command line for writing a crontab |
| 321 |
""" |
| 322 |
user = "" |
| 323 |
if self.user: |
| 324 |
if platform.system() in ["SunOS", "HP-UX", "AIX"]: |
| 325 |
return f"chown {shlex_quote(self.user)} {shlex_quote(path)} ; su '{shlex_quote(self.user)}' -c '{self.cron_cmd} {shlex_quote(path)}'" |
| 326 |
elif pwd.getpwuid(os.getuid())[0] != self.user: |
| 327 |
user = f"-u {shlex_quote(self.user)}" |
| 328 |
return f"{self.cron_cmd} {user} {shlex_quote(path)}" |
| 329 |
|
| 330 |
|
| 331 |
# ================================================== |
| 332 |
|
| 333 |
|
| 334 |
def main(): |
| 335 |
# The following example playbooks: |
| 336 |
# |
| 337 |
# - community.general.cronvar: name="SHELL" value="/bin/bash" |
| 338 |
# |
| 339 |
# - name: Set the email |
| 340 |
# community.general.cronvar: name="EMAILTO" value="[email protected]" |
| 341 |
# |
| 342 |
# - name: Get rid of the old new host variable |
| 343 |
# community.general.cronvar: name="NEW_HOST" state=absent |
| 344 |
# |
| 345 |
# Would produce: |
| 346 |
# SHELL = /bin/bash |
| 347 |
# EMAILTO = [email protected] |
| 348 |
|
| 349 |
module = AnsibleModule( |
| 350 |
argument_spec=dict( |
| 351 |
name=dict(type="str", required=True), |
| 352 |
value=dict(type="str"), |
| 353 |
user=dict(type="str"), |
| 354 |
cron_file=dict(type="str"), |
| 355 |
insertafter=dict(type="str"), |
| 356 |
insertbefore=dict(type="str"), |
| 357 |
state=dict(type="str", default="present", choices=["absent", "present"]), |
| 358 |
backup=dict(type="bool", default=False), |
| 359 |
), |
| 360 |
mutually_exclusive=[["insertbefore", "insertafter"]], |
| 361 |
supports_check_mode=False, |
| 362 |
) |
| 363 |
module.run_command_environ_update = {"LANGUAGE": "C", "LC_ALL": "C"} |
| 364 |
|
| 365 |
name = module.params["name"] |
| 366 |
value = module.params["value"] |
| 367 |
user = module.params["user"] |
| 368 |
cron_file = module.params["cron_file"] |
| 369 |
insertafter = module.params["insertafter"] |
| 370 |
insertbefore = module.params["insertbefore"] |
| 371 |
state = module.params["state"] |
| 372 |
backup = module.params["backup"] |
| 373 |
ensure_present = state == "present" |
| 374 |
|
| 375 |
changed = False |
| 376 |
res_args = dict() |
| 377 |
|
| 378 |
# Ensure all files generated are only writable by the owning user. Primarily relevant for the cron_file option. |
| 379 |
os.umask(int("022", 8)) |
| 380 |
cronvar = CronVar(module, user, cron_file) |
| 381 |
|
| 382 |
module.debug(f'cronvar instantiated - name: "{name}"') |
| 383 |
|
| 384 |
# --- user input validation --- |
| 385 |
|
| 386 |
if name is None and ensure_present: |
| 387 |
module.fail_json(msg="You must specify 'name' to insert a new cron variable") |
| 388 |
|
| 389 |
if value is None and ensure_present: |
| 390 |
module.fail_json(msg="You must specify 'value' to insert a new cron variable") |
| 391 |
|
| 392 |
if name is None and not ensure_present: |
| 393 |
module.fail_json(msg="You must specify 'name' to remove a cron variable") |
| 394 |
|
| 395 |
# if requested make a backup before making a change |
| 396 |
if backup: |
| 397 |
dummy, backup_file = tempfile.mkstemp(prefix="cronvar") |
| 398 |
cronvar.write(backup_file) |
| 399 |
|
| 400 |
if cronvar.cron_file and not name and not ensure_present: |
| 401 |
changed = cronvar.remove_job_file() |
| 402 |
module.exit_json(changed=changed, cron_file=cron_file, state=state) |
| 403 |
|
| 404 |
old_value = cronvar.find_variable(name) |
| 405 |
|
| 406 |
if ensure_present: |
| 407 |
if value == "" and old_value != "": |
| 408 |
value = '""' |
| 409 |
if old_value is None: |
| 410 |
cronvar.add_variable(name, value, insertbefore, insertafter) |
| 411 |
changed = True |
| 412 |
elif old_value != value: |
| 413 |
cronvar.update_variable(name, value) |
| 414 |
changed = True |
| 415 |
else: |
| 416 |
if old_value is not None: |
| 417 |
cronvar.remove_variable(name) |
| 418 |
changed = True |
| 419 |
|
| 420 |
res_args = {"vars": cronvar.get_var_names(), "changed": changed} |
| 421 |
|
| 422 |
if changed: |
| 423 |
cronvar.write() |
| 424 |
|
| 425 |
# retain the backup only if crontab or cron file have changed |
| 426 |
if backup: |
| 427 |
if changed: |
| 428 |
res_args["backup_file"] = backup_file |
| 429 |
else: |
| 430 |
os.unlink(backup_file) |
| 431 |
|
| 432 |
if cron_file: |
| 433 |
res_args["cron_file"] = cron_file |
| 434 |
|
| 435 |
module.exit_json(**res_args) |
| 436 |
|
| 437 |
|
| 438 |
if __name__ == "__main__": |
| 439 |
main() |