Debian Codegraph @

ansible_collections/netapp_eseries/santricity/plugins/modules/netapp_e_syslog.py

raw
1 #!/usr/bin/python
2
3 # (c) 2018, NetApp, Inc
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 from __future__ import absolute_import, division, print_function
7
8 __metaclass__ = type
9
10 ANSIBLE_METADATA = {'metadata_version': '1.1',
11 'status': ['deprecated'],
12 'supported_by': 'community'}
13
14 DOCUMENTATION = """
15 ---
16 module: netapp_e_syslog
17 short_description: NetApp E-Series manage syslog settings
18 description:
19 - Allow the syslog settings to be configured for an individual E-Series storage-system
20 version_added: '2.7.0'
21 author: Nathan Swartz (@ndswartz)
22 extends_documentation_fragment:
23 - netapp_eseries.santricity.santricity.netapp.eseries
24 options:
25 state:
26 description:
27 - Add or remove the syslog server configuration for E-Series storage array.
28 - Existing syslog server configuration will be removed or updated when its address matches I(address).
29 - Fully qualified hostname that resolve to an IPv4 address that matches I(address) will not be
30 treated as a match.
31 choices:
32 - present
33 - absent
34 type: str
35 default: present
36 address:
37 description:
38 - The syslog server's IPv4 address or a fully qualified hostname.
39 - All existing syslog configurations will be removed when I(state=absent) and I(address=None).
40 type: str
41 port:
42 description:
43 - This is the port the syslog server is using.
44 default: 514
45 type: int
46 protocol:
47 description:
48 - This is the transmission protocol the syslog server's using to receive syslog messages.
49 choices:
50 - udp
51 - tcp
52 - tls
53 default: udp
54 type: str
55 components:
56 description:
57 - The e-series logging components define the specific logs to transfer to the syslog server.
58 - At the time of writing, 'auditLog' is the only logging component but more may become available.
59 default: ["auditLog"]
60 type: list
61 elements: str
62 test:
63 description:
64 - This forces a test syslog message to be sent to the stated syslog server.
65 - Only attempts transmission when I(state=present).
66 type: bool
67 default: no
68 log_path:
69 description:
70 - This argument specifies a local path for logging purposes.
71 type: str
72 required: no
73 notes:
74 - Check mode is supported.
75 - This API is currently only supported with the Embedded Web Services API v2.12 (bundled with
76 SANtricity OS 11.40.2) and higher.
77 """
78
79 EXAMPLES = """
80 - name: Add two syslog server configurations to NetApp E-Series storage array.
81 netapp_e_syslog:
82 state: present
83 address: "{{ item }}"
84 port: 514
85 protocol: tcp
86 component: "auditLog"
87 api_url: "10.1.1.1:8443"
88 api_username: "admin"
89 api_password: "myPass"
90 loop:
91 - "192.168.1.1"
92 - "192.168.1.100"
93 """
94
95 RETURN = """
96 msg:
97 description: Success message
98 returned: on success
99 type: str
100 sample: The settings have been updated.
101 syslog:
102 description:
103 - True if syslog server configuration has been added to e-series storage array.
104 returned: on success
105 sample: True
106 type: bool
107 """
108
109 import json
110 import logging
111
112 from ansible.module_utils.basic import AnsibleModule
113 from ansible_collections.netapp_eseries.santricity.plugins.module_utils.netapp import request, eseries_host_argument_spec
114 from ansible.module_utils._text import to_native
115
116 HEADERS = {
117 "Content-Type": "application/json",
118 "Accept": "application/json",
119 }
120
121
122 class Syslog(object):
123 def __init__(self):
124 argument_spec = eseries_host_argument_spec()
125 argument_spec.update(dict(
126 state=dict(choices=["present", "absent"], required=False, default="present"),
127 address=dict(type="str", required=False),
128 port=dict(type="int", default=514, required=False),
129 protocol=dict(choices=["tcp", "tls", "udp"], default="udp", required=False),
130 components=dict(type="list", elements="str", required=False, default=["auditLog"]),
131 test=dict(type="bool", default=False, required=False),
132 log_path=dict(type="str", required=False),
133 ))
134
135 required_if = [
136 ["state", "present", ["address", "port", "protocol", "components"]],
137 ]
138
139 mutually_exclusive = None
140
141 self.module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True, required_if=required_if,
142 mutually_exclusive=mutually_exclusive)
143 args = self.module.params
144
145 self.syslog = args["state"] in ["present"]
146 self.address = args["address"]
147 self.port = args["port"]
148 self.protocol = args["protocol"]
149 self.components = args["components"]
150 self.test = args["test"]
151 self.ssid = args["ssid"]
152 self.url = args["api_url"]
153 self.creds = dict(url_password=args["api_password"],
154 validate_certs=args["validate_certs"],
155 url_username=args["api_username"], )
156
157 self.components.sort()
158
159 self.check_mode = self.module.check_mode
160
161 # logging setup
162 log_path = args["log_path"]
163 self._logger = logging.getLogger(self.__class__.__name__)
164 if log_path:
165 logging.basicConfig(
166 level=logging.DEBUG, filename=log_path, filemode='w',
167 format='%(relativeCreated)dms %(levelname)s %(module)s.%(funcName)s:%(lineno)d\n %(message)s')
168
169 if not self.url.endswith('/'):
170 self.url += '/'
171
172 def get_configuration(self):
173 """Retrieve existing syslog configuration."""
174 try:
175 (rc, result) = request(self.url + "storage-systems/{0}/syslog".format(self.ssid),
176 headers=HEADERS, **self.creds)
177 return result
178 except Exception as err:
179 self.module.fail_json(msg="Failed to retrieve syslog configuration! Array Id [%s]. Error [%s]."
180 % (self.ssid, to_native(err)))
181
182 def test_configuration(self, body):
183 """Send test syslog message to the storage array.
184
185 Allows fix number of retries to occur before failure is issued to give the storage array time to create
186 new syslog server record.
187 """
188 try:
189 (rc, result) = request(self.url + "storage-systems/{0}/syslog/{1}/test".format(self.ssid, body["id"]),
190 method='POST', headers=HEADERS, **self.creds)
191 except Exception as err:
192 self.module.fail_json(
193 msg="We failed to send test message! Array Id [{0}]. Error [{1}].".format(self.ssid, to_native(err)))
194
195 def update_configuration(self):
196 """Post the syslog request to array."""
197 config_match = None
198 perfect_match = None
199 update = False
200 body = dict()
201
202 # search existing configuration for syslog server entry match
203 configs = self.get_configuration()
204 if self.address:
205 for config in configs:
206 if config["serverAddress"] == self.address:
207 config_match = config
208 if (config["port"] == self.port and config["protocol"] == self.protocol and
209 len(config["components"]) == len(self.components) and
210 all(component["type"] in self.components for component in config["components"])):
211 perfect_match = config_match
212 break
213
214 # generate body for the http request
215 if self.syslog:
216 if not perfect_match:
217 update = True
218 if config_match:
219 body.update(dict(id=config_match["id"]))
220 components = [dict(type=component_type) for component_type in self.components]
221 body.update(dict(serverAddress=self.address, port=self.port,
222 protocol=self.protocol, components=components))
223 self._logger.info(body)
224 self.make_configuration_request(body)
225
226 # remove specific syslog server configuration
227 elif self.address:
228 update = True
229 body.update(dict(id=config_match["id"]))
230 self._logger.info(body)
231 self.make_configuration_request(body)
232
233 # if no address is specified, remove all syslog server configurations
234 elif configs:
235 update = True
236 for config in configs:
237 body.update(dict(id=config["id"]))
238 self._logger.info(body)
239 self.make_configuration_request(body)
240
241 return update
242
243 def make_configuration_request(self, body):
244 # make http request(s)
245 if not self.check_mode:
246 try:
247 if self.syslog:
248 if "id" in body:
249 (rc, result) = request(
250 self.url + "storage-systems/{0}/syslog/{1}".format(self.ssid, body["id"]),
251 method='POST', data=json.dumps(body), headers=HEADERS, **self.creds)
252 else:
253 (rc, result) = request(self.url + "storage-systems/{0}/syslog".format(self.ssid),
254 method='POST', data=json.dumps(body), headers=HEADERS, **self.creds)
255 body.update(result)
256
257 # send syslog test message
258 if self.test:
259 self.test_configuration(body)
260
261 elif "id" in body:
262 (rc, result) = request(self.url + "storage-systems/{0}/syslog/{1}".format(self.ssid, body["id"]),
263 method='DELETE', headers=HEADERS, **self.creds)
264
265 # This is going to catch cases like a connection failure
266 except Exception as err:
267 self.module.fail_json(msg="We failed to modify syslog configuration! Array Id [%s]. Error [%s]."
268 % (self.ssid, to_native(err)))
269
270 def update(self):
271 """Update configuration and respond to ansible."""
272 update = self.update_configuration()
273 self.module.exit_json(msg="The syslog settings have been updated.", changed=update)
274
275 def __call__(self, *args, **kwargs):
276 self.update()
277
278
279 def main():
280 settings = Syslog()
281 settings()
282
283
284 if __name__ == "__main__":
285 main()