mirror of
https://github.com/ansible-collections/community.general.git
synced 2026-03-26 21:33:12 +00:00
Reformat everything.
This commit is contained in:
@@ -114,25 +114,34 @@ class CronVarError(Exception):
|
||||
|
||||
class CronVar:
|
||||
"""
|
||||
CronVar object to write variables to crontabs.
|
||||
CronVar object to write variables to crontabs.
|
||||
|
||||
user - the user of the crontab (defaults to root)
|
||||
cron_file - a cron file under /etc/cron.d
|
||||
user - the user of the crontab (defaults to root)
|
||||
cron_file - a cron file under /etc/cron.d
|
||||
"""
|
||||
|
||||
def __init__(self, module, user=None, cron_file=None):
|
||||
self.module = module
|
||||
self.user = user
|
||||
self.lines = None
|
||||
self.wordchars = ''.join(chr(x) for x in range(128) if chr(x) not in ('=', "'", '"',))
|
||||
self.cron_cmd = self.module.get_bin_path('crontab', required=True)
|
||||
self.wordchars = "".join(
|
||||
chr(x)
|
||||
for x in range(128)
|
||||
if chr(x)
|
||||
not in (
|
||||
"=",
|
||||
"'",
|
||||
'"',
|
||||
)
|
||||
)
|
||||
self.cron_cmd = self.module.get_bin_path("crontab", required=True)
|
||||
|
||||
if cron_file:
|
||||
self.cron_file = ""
|
||||
if os.path.isabs(cron_file):
|
||||
self.cron_file = cron_file
|
||||
else:
|
||||
self.cron_file = os.path.join('/etc/cron.d', cron_file)
|
||||
self.cron_file = os.path.join("/etc/cron.d", cron_file)
|
||||
parent_dir = os.path.dirname(self.cron_file)
|
||||
if parent_dir and not os.path.isdir(parent_dir):
|
||||
module.fail_json(msg=f"Parent directory '{parent_dir}' does not exist for cron_file: '{cron_file}'")
|
||||
@@ -147,7 +156,7 @@ class CronVar:
|
||||
if self.cron_file:
|
||||
# read the cronfile
|
||||
try:
|
||||
with open(self.cron_file, 'r') as f:
|
||||
with open(self.cron_file, "r") as f:
|
||||
self.lines = f.read().splitlines()
|
||||
except IOError:
|
||||
# cron file does not exist
|
||||
@@ -164,8 +173,11 @@ class CronVar:
|
||||
lines = out.splitlines()
|
||||
count = 0
|
||||
for l in lines:
|
||||
if count > 2 or (not re.match(r'# DO NOT EDIT THIS FILE - edit the master and reinstall.', l
|
||||
) and not re.match(r'# \(/tmp/.*installed on.*\)', l) and not re.match(r'# \(.*version.*\)', l)):
|
||||
if count > 2 or (
|
||||
not re.match(r"# DO NOT EDIT THIS FILE - edit the master and reinstall.", l)
|
||||
and not re.match(r"# \(/tmp/.*installed on.*\)", l)
|
||||
and not re.match(r"# \(.*version.*\)", l)
|
||||
):
|
||||
self.lines.append(l)
|
||||
count += 1
|
||||
|
||||
@@ -177,13 +189,13 @@ class CronVar:
|
||||
Write the crontab to the system. Saves all information.
|
||||
"""
|
||||
if backup_file:
|
||||
fileh = open(backup_file, 'w')
|
||||
fileh = open(backup_file, "w")
|
||||
elif self.cron_file:
|
||||
fileh = open(self.cron_file, 'w')
|
||||
fileh = open(self.cron_file, "w")
|
||||
path = None
|
||||
else:
|
||||
filed, path = tempfile.mkstemp(prefix='crontab')
|
||||
fileh = os.fdopen(filed, 'w')
|
||||
filed, path = tempfile.mkstemp(prefix="crontab")
|
||||
fileh = os.fdopen(filed, "w")
|
||||
|
||||
fileh.write(self.render())
|
||||
fileh.close()
|
||||
@@ -215,8 +227,8 @@ class CronVar:
|
||||
lexer = shlex.shlex(line)
|
||||
lexer.wordchars = self.wordchars
|
||||
varname = lexer.get_token()
|
||||
is_env_var = lexer.get_token() == '='
|
||||
value = ''.join(lexer)
|
||||
is_env_var = lexer.get_token() == "="
|
||||
value = "".join(lexer)
|
||||
if is_env_var:
|
||||
return (varname, value)
|
||||
raise CronVarError("Not a variable.")
|
||||
@@ -284,43 +296,44 @@ class CronVar:
|
||||
"""
|
||||
Render a proper crontab
|
||||
"""
|
||||
result = '\n'.join(self.lines)
|
||||
if result and result[-1] not in ['\n', '\r']:
|
||||
result += '\n'
|
||||
result = "\n".join(self.lines)
|
||||
if result and result[-1] not in ["\n", "\r"]:
|
||||
result += "\n"
|
||||
return result
|
||||
|
||||
def _read_user_execute(self):
|
||||
"""
|
||||
Returns the command line for reading a crontab
|
||||
"""
|
||||
user = ''
|
||||
user = ""
|
||||
|
||||
if self.user:
|
||||
if platform.system() == 'SunOS':
|
||||
if platform.system() == "SunOS":
|
||||
return f"su {shlex_quote(self.user)} -c '{shlex_quote(self.cron_cmd)} -l'"
|
||||
elif platform.system() == 'AIX':
|
||||
elif platform.system() == "AIX":
|
||||
return f"{shlex_quote(self.cron_cmd)} -l {shlex_quote(self.user)}"
|
||||
elif platform.system() == 'HP-UX':
|
||||
elif platform.system() == "HP-UX":
|
||||
return f"{self.cron_cmd} -l {shlex_quote(self.user)}"
|
||||
elif pwd.getpwuid(os.getuid())[0] != self.user:
|
||||
user = f'-u {shlex_quote(self.user)}'
|
||||
user = f"-u {shlex_quote(self.user)}"
|
||||
return f"{self.cron_cmd} {user} -l"
|
||||
|
||||
def _write_execute(self, path):
|
||||
"""
|
||||
Return the command line for writing a crontab
|
||||
"""
|
||||
user = ''
|
||||
user = ""
|
||||
if self.user:
|
||||
if platform.system() in ['SunOS', 'HP-UX', 'AIX']:
|
||||
if platform.system() in ["SunOS", "HP-UX", "AIX"]:
|
||||
return f"chown {shlex_quote(self.user)} {shlex_quote(path)} ; su '{shlex_quote(self.user)}' -c '{self.cron_cmd} {shlex_quote(path)}'"
|
||||
elif pwd.getpwuid(os.getuid())[0] != self.user:
|
||||
user = f'-u {shlex_quote(self.user)}'
|
||||
user = f"-u {shlex_quote(self.user)}"
|
||||
return f"{self.cron_cmd} {user} {shlex_quote(path)}"
|
||||
|
||||
|
||||
# ==================================================
|
||||
|
||||
|
||||
def main():
|
||||
# The following example playbooks:
|
||||
#
|
||||
@@ -338,34 +351,34 @@ def main():
|
||||
|
||||
module = AnsibleModule(
|
||||
argument_spec=dict(
|
||||
name=dict(type='str', required=True),
|
||||
value=dict(type='str'),
|
||||
user=dict(type='str'),
|
||||
cron_file=dict(type='str'),
|
||||
insertafter=dict(type='str'),
|
||||
insertbefore=dict(type='str'),
|
||||
state=dict(type='str', default='present', choices=['absent', 'present']),
|
||||
backup=dict(type='bool', default=False),
|
||||
name=dict(type="str", required=True),
|
||||
value=dict(type="str"),
|
||||
user=dict(type="str"),
|
||||
cron_file=dict(type="str"),
|
||||
insertafter=dict(type="str"),
|
||||
insertbefore=dict(type="str"),
|
||||
state=dict(type="str", default="present", choices=["absent", "present"]),
|
||||
backup=dict(type="bool", default=False),
|
||||
),
|
||||
mutually_exclusive=[['insertbefore', 'insertafter']],
|
||||
mutually_exclusive=[["insertbefore", "insertafter"]],
|
||||
supports_check_mode=False,
|
||||
)
|
||||
|
||||
name = module.params['name']
|
||||
value = module.params['value']
|
||||
user = module.params['user']
|
||||
cron_file = module.params['cron_file']
|
||||
insertafter = module.params['insertafter']
|
||||
insertbefore = module.params['insertbefore']
|
||||
state = module.params['state']
|
||||
backup = module.params['backup']
|
||||
ensure_present = state == 'present'
|
||||
name = module.params["name"]
|
||||
value = module.params["value"]
|
||||
user = module.params["user"]
|
||||
cron_file = module.params["cron_file"]
|
||||
insertafter = module.params["insertafter"]
|
||||
insertbefore = module.params["insertbefore"]
|
||||
state = module.params["state"]
|
||||
backup = module.params["backup"]
|
||||
ensure_present = state == "present"
|
||||
|
||||
changed = False
|
||||
res_args = dict()
|
||||
|
||||
# Ensure all files generated are only writable by the owning user. Primarily relevant for the cron_file option.
|
||||
os.umask(int('022', 8))
|
||||
os.umask(int("022", 8))
|
||||
cronvar = CronVar(module, user, cron_file)
|
||||
|
||||
module.debug(f'cronvar instantiated - name: "{name}"')
|
||||
@@ -383,7 +396,7 @@ def main():
|
||||
|
||||
# if requested make a backup before making a change
|
||||
if backup:
|
||||
dummy, backup_file = tempfile.mkstemp(prefix='cronvar')
|
||||
dummy, backup_file = tempfile.mkstemp(prefix="cronvar")
|
||||
cronvar.write(backup_file)
|
||||
|
||||
if cronvar.cron_file and not name and not ensure_present:
|
||||
@@ -406,10 +419,7 @@ def main():
|
||||
cronvar.remove_variable(name)
|
||||
changed = True
|
||||
|
||||
res_args = {
|
||||
"vars": cronvar.get_var_names(),
|
||||
"changed": changed
|
||||
}
|
||||
res_args = {"vars": cronvar.get_var_names(), "changed": changed}
|
||||
|
||||
if changed:
|
||||
cronvar.write()
|
||||
@@ -417,15 +427,15 @@ def main():
|
||||
# retain the backup only if crontab or cron file have changed
|
||||
if backup:
|
||||
if changed:
|
||||
res_args['backup_file'] = backup_file
|
||||
res_args["backup_file"] = backup_file
|
||||
else:
|
||||
os.unlink(backup_file)
|
||||
|
||||
if cron_file:
|
||||
res_args['cron_file'] = cron_file
|
||||
res_args["cron_file"] = cron_file
|
||||
|
||||
module.exit_json(**res_args)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
Reference in New Issue
Block a user