Debian Codegraph @

ansible_collections/purestorage/flasharray/plugins/modules/purefa_audits.py

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # (c) 2024, Simon Dodsley ([email protected])
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 from __future__ import absolute_import, division, print_function
8
9 __metaclass__ = type
10
11 ANSIBLE_METADATA = {
12 "metadata_version": "1.1",
13 "status": ["preview"],
14 "supported_by": "community",
15 }
16
17 DOCUMENTATION = r"""
18 ---
19 module: purefa_audits
20 version_added: '1.29.0'
21 short_description: List FlashArray Audit Events
22 description:
23 - List audit events based on filters provided
24 author:
25 - Pure Storage Ansible Team (@sdodsley) <[email protected]>
26 options:
27 start:
28 description:
29 - Start date and time (based on array local time)
30 - If not provided epoch is assumed
31 - Expected format "YYYY-MM-DD hh:mm:ss"
32 type: str
33 timezone:
34 description:
35 - The timezone of the FlashArray
36 - If not provided, the module will attempt to get the current local timezone
37 from the server however from Purity//FA 6.5.3 this value will calculated
38 automatically from the FlashArray
39 type: str
40 context:
41 description:
42 - Name of fleet member on which to perform the operation.
43 - This requires the array receiving the request is a member of a fleet
44 and the context name to be a member of the same fleet.
45 type: str
46 default: ""
47 version_added: '1.39.0'
48 extends_documentation_fragment:
49 - purestorage.flasharray.purestorage.fa
50 """
51
52 EXAMPLES = r"""
53 - name: Show all audit events that started after the specified date/time and TZ
54 purefa_audits:
55 start: "2024-06-29 12:31:34"
56 timezone: "America/New_York"
57 fa_url: 10.10.10.2
58 api_token: 89a9356f-c203-d263-8a89-c229486a13ba
59
60 - name: Show all audit events that have been logged by the array (to the internal limit of the array)
61 purefa_audits:
62 fa_url: 10.10.10.2
63 api_token: 89a9356f-c203-d263-8a89-c229486a13ba
64 """
65
66 RETURN = r"""
67 """
68
69 HAS_PYTZ = True
70 try:
71 import pytz
72 except ImportError:
73 HAS_PYTX = False
74
75 import datetime
76 from ansible.module_utils.basic import AnsibleModule
77 from ansible_collections.purestorage.flasharray.plugins.module_utils.purefa import (
78 get_array,
79 purefa_argument_spec,
80 )
81 from ansible_collections.purestorage.flasharray.plugins.module_utils.version import (
82 LooseVersion,
83 )
84 from ansible_collections.purestorage.flasharray.plugins.module_utils.common import (
85 get_local_tz,
86 )
87
88 TZ_VERSION = "2.26"
89 CONTEXT_VERSION = "2.38"
90
91
92 def _get_filter_string(module, timezone):
93 filter_string = ""
94 if module.params["start"] and module.params["start"] != "0":
95 start = module.params["start"] + " " + timezone
96 start_timestamp = int(
97 1000
98 * datetime.datetime.timestamp(
99 datetime.datetime.strptime(start, "%Y-%m-%d %H:%M:%S %z")
100 )
101 )
102 else:
103 start_timestamp = 0
104 filter_string = "time>=" + str(start_timestamp)
105 return filter_string
106
107
108 def main():
109 argument_spec = purefa_argument_spec()
110 argument_spec.update(
111 dict(
112 start=dict(type="str"),
113 timezone=dict(type="str"),
114 context=dict(type="str", default=""),
115 )
116 )
117
118 module = AnsibleModule(argument_spec, supports_check_mode=True)
119
120 if not HAS_PYTZ:
121 module.fail_json(msg="pytz is required for this module")
122
123 array = get_array(module)
124 api_version = array.get_rest_version()
125 if not module.params["timezone"] and LooseVersion(TZ_VERSION) <= LooseVersion(
126 api_version
127 ):
128 if LooseVersion(CONTEXT_VERSION) <= LooseVersion(api_version):
129 timezone = list(
130 array.get_arrays(context_names=[module.params["context"]]).items
131 )[0].time_zone
132 else:
133 timezone = list(array.get_arrays().items)[0].time_zone
134 elif not module.params["timezone"]:
135 timezone = get_local_tz(module)
136 elif module.params["timezone"] not in pytz.all_timezones_set:
137 module.fail_json(
138 msg="Timezone {0} is not valid".format(module.params["timezone"])
139 )
140 else:
141 timezone = module.params["timezone"]
142 tzoffset = datetime.datetime.now(pytz.timezone(timezone)).strftime("%z")
143 filter_string = _get_filter_string(module, tzoffset)
144 audit_log = {}
145 if LooseVersion(CONTEXT_VERSION) <= LooseVersion(api_version):
146 if filter_string:
147 res = array.get_audits(
148 context_names=[module.params["context"]], filter=filter_string
149 )
150 else:
151 res = array.get_audits(context_names=[module.params["context"]])
152 else:
153 if filter_string:
154 res = array.get_audits(
155 context_names=[module.params["context"]], filter=filter_string
156 )
157 else:
158 res = array.get_audits(context_names=[module.params["context"]])
159 if res.status_code == 200:
160 audits = list(res.items)
161 else:
162 module.fail_json(
163 msg="Failed to get audit events. Error: {0}".format(res.errors[0].message)
164 )
165 for audit in audits:
166 name = audit.name
167 time = datetime.datetime.fromtimestamp(
168 audit.time / 1000, tz=pytz.timezone(timezone)
169 ).strftime("%Y-%m-%d %H:%M:%S %Z")
170 audit_log[name] = {
171 "time": time,
172 "arguments": audit.arguments,
173 "user": audit.user,
174 "command": audit.command,
175 "subcommand": audit.subcommand,
176 "origin": audit.origin.name,
177 }
178 module.exit_json(changed=False, purefa_audits=audit_log)
179
180
181 if __name__ == "__main__":
182 main()