|
| 1 | +#!/usr/bin/python |
| 2 | + |
| 3 | +from __future__ import absolute_import, division, print_function |
| 4 | + |
| 5 | +__metaclass__ = type |
| 6 | + |
| 7 | +DOCUMENTATION = """ |
| 8 | +--- |
| 9 | +module: sr_fingerprint |
| 10 | +short_description: Write a message string to syslog using Ansible C(module.log) function. |
| 11 | +description: |
| 12 | + - Writes the given string to the system log using Ansible C(module.log) function. |
| 13 | + - Intended for role-internal or diagnostic use. |
| 14 | +author: Rich Megginson (@richm) |
| 15 | +options: |
| 16 | + sr_message: |
| 17 | + description: Text to record in syslog. |
| 18 | + type: str |
| 19 | + required: true |
| 20 | +""" |
| 21 | + |
| 22 | +EXAMPLES = """ |
| 23 | +- name: Record a fingerprint message in syslog |
| 24 | + sr_fingerprint: |
| 25 | + sr_message: "system_role:ROLENAME" |
| 26 | +""" |
| 27 | + |
| 28 | +RETURN = r""" # """ |
| 29 | + |
| 30 | +from ansible.module_utils.basic import AnsibleModule |
| 31 | + |
| 32 | +import datetime |
| 33 | + |
| 34 | + |
| 35 | +def _local_iso8601_no_microseconds(): |
| 36 | + """System local wall clock with local tz offset, ISO 8601, seconds only.""" |
| 37 | + try: |
| 38 | + utc = datetime.timezone.utc |
| 39 | + except AttributeError: |
| 40 | + import time |
| 41 | + |
| 42 | + return time.strftime("%Y-%m-%dT%H:%M:%S%z", time.localtime()) |
| 43 | + # Prefer the local clock interpreted in the system timezone (not UTC displayed). |
| 44 | + now = datetime.datetime.now() |
| 45 | + astimezone = getattr(now, "astimezone", None) |
| 46 | + if astimezone is not None: |
| 47 | + try: |
| 48 | + return astimezone().replace(microsecond=0).isoformat() |
| 49 | + except (OSError, TypeError, ValueError): |
| 50 | + pass |
| 51 | + return datetime.datetime.now(utc).astimezone().replace(microsecond=0).isoformat() |
| 52 | + |
| 53 | + |
| 54 | +def run_module(): |
| 55 | + module_args = dict( |
| 56 | + sr_message=dict(type="str", required=True), |
| 57 | + ) |
| 58 | + |
| 59 | + module = AnsibleModule( |
| 60 | + argument_spec=module_args, |
| 61 | + supports_check_mode=True, |
| 62 | + ) |
| 63 | + |
| 64 | + log_message = "%s %s" % ( |
| 65 | + module.params["sr_message"], |
| 66 | + _local_iso8601_no_microseconds(), |
| 67 | + ) |
| 68 | + |
| 69 | + if module.check_mode: |
| 70 | + module.exit_json( |
| 71 | + changed=False, |
| 72 | + message="Check mode: message not logged - [%s]" % log_message, |
| 73 | + ) |
| 74 | + |
| 75 | + module.log(log_message) |
| 76 | + |
| 77 | + # we don't actually change anything, so we're not changed - writing a log message |
| 78 | + # is not considered a change |
| 79 | + # also, we don't want to report changed every time the role runs |
| 80 | + module.exit_json(changed=False) |
| 81 | + |
| 82 | + |
| 83 | +def main(): |
| 84 | + run_module() |
| 85 | + |
| 86 | + |
| 87 | +if __name__ == "__main__": |
| 88 | + main() |
0 commit comments