Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # (c) 2024, 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_iscsi_target
17 short_description: NetApp E-Series manage iSCSI target configuration
18 description:
19 - Configure the settings of an E-Series iSCSI target
20 version_added: '2.7.0'
21 author: Michael Price (@lmprice)
22 extends_documentation_fragment:
23 - netapp_eseries.santricity.santricity.netapp.eseries
24 options:
25 name:
26 description:
27 - The name/alias to assign to the iSCSI target.
28 - This alias is often used by the initiator software in order to make an iSCSI target easier to identify.
29 type: str
30 aliases:
31 - alias
32 ping:
33 description:
34 - Enable ICMP ping responses from the configured iSCSI ports.
35 type: bool
36 default: yes
37 chap_secret:
38 description:
39 - Enable Challenge-Handshake Authentication Protocol (CHAP), utilizing this value as the password.
40 - When this value is specified, we will always trigger an update (changed=True). We have no way of verifying
41 whether or not the password has changed.
42 - The chap secret may only use ascii characters with values between 32 and 126 decimal.
43 - The chap secret must be no less than 12 characters, but no greater than 57 characters in length.
44 - The chap secret is cleared when not specified or an empty string.
45 type: str
46 aliases:
47 - chap
48 - password
49 unnamed_discovery:
50 description:
51 - When an initiator initiates a discovery session to an initiator port, it is considered an unnamed
52 discovery session if the iSCSI target iqn is not specified in the request.
53 - This option may be disabled to increase security if desired.
54 type: bool
55 default: yes
56 log_path:
57 description:
58 - A local path (on the Ansible controller), to a file to be used for debug logging.
59 type: str
60 required: no
61 notes:
62 - Check mode is supported.
63 - Some of the settings are dependent on the settings applied to the iSCSI interfaces. These can be configured using
64 M(netapp_eseries.santricity.netapp_e_iscsi_interface).
65 - This module requires a Web Services API version of >= 1.3.
66 """
67
68 EXAMPLES = """
69 - name: Enable ping responses and unnamed discovery sessions for all iSCSI ports
70 netapp_e_iscsi_target:
71 api_url: "https://localhost:8443/devmgr/v2"
72 api_username: admin
73 api_password: myPassword
74 ssid: "1"
75 validate_certs: no
76 name: myTarget
77 ping: yes
78 unnamed_discovery: yes
79
80 - name: Set the target alias and the CHAP secret
81 netapp_e_iscsi_target:
82 ssid: "{{ ssid }}"
83 api_url: "{{ netapp_api_url }}"
84 api_username: "{{ netapp_api_username }}"
85 api_password: "{{ netapp_api_password }}"
86 name: myTarget
87 chap: password1234
88 """
89
90 RETURN = """
91 msg:
92 description: Success message
93 returned: on success
94 type: str
95 sample: The iSCSI target settings have been updated.
96 alias:
97 description:
98 - The alias assigned to the iSCSI target.
99 returned: on success
100 sample: myArray
101 type: str
102 iqn:
103 description:
104 - The iqn (iSCSI Qualified Name), assigned to the iSCSI target.
105 returned: on success
106 sample: iqn.1992-08.com.netapp:2800.000a132000b006d2000000005a0e8f45
107 type: str
108 """
109 import json
110 import logging
111 from pprint import pformat
112
113 from ansible.module_utils.basic import AnsibleModule
114 from ansible_collections.netapp_eseries.santricity.plugins.module_utils.netapp import request, eseries_host_argument_spec
115 from ansible.module_utils._text import to_native
116
117 HEADERS = {
118 "Content-Type": "application/json",
119 "Accept": "application/json",
120 }
121
122
123 class IscsiTarget(object):
124 def __init__(self):
125 argument_spec = eseries_host_argument_spec()
126 argument_spec.update(dict(
127 name=dict(type='str', required=False, aliases=['alias']),
128 ping=dict(type='bool', required=False, default=True),
129 chap_secret=dict(type='str', required=False, aliases=['chap', 'password'], no_log=True),
130 unnamed_discovery=dict(type='bool', required=False, default=True),
131 log_path=dict(type='str', required=False),
132 ))
133
134 self.module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True, )
135 args = self.module.params
136
137 self.name = args['name']
138 self.ping = args['ping']
139 self.chap_secret = args['chap_secret']
140 self.unnamed_discovery = args['unnamed_discovery']
141
142 self.ssid = args['ssid']
143 self.url = args['api_url']
144 self.creds = dict(url_password=args['api_password'],
145 validate_certs=args['validate_certs'],
146 url_username=args['api_username'], )
147
148 self.check_mode = self.module.check_mode
149 self.post_body = dict()
150 self.controllers = list()
151
152 log_path = args['log_path']
153
154 # logging setup
155 self._logger = logging.getLogger(self.__class__.__name__)
156
157 if log_path:
158 logging.basicConfig(
159 level=logging.DEBUG, filename=log_path, filemode='w',
160 format='%(relativeCreated)dms %(levelname)s %(module)s.%(funcName)s:%(lineno)d\n %(message)s')
161
162 if not self.url.endswith('/'):
163 self.url += '/'
164
165 if self.chap_secret:
166 if len(self.chap_secret) < 12 or len(self.chap_secret) > 57:
167 self.module.fail_json(msg="The provided CHAP secret is not valid, it must be between 12 and 57"
168 " characters in length.")
169
170 for c in self.chap_secret:
171 ordinal = ord(c)
172 if ordinal < 32 or ordinal > 126:
173 self.module.fail_json(msg="The provided CHAP secret is not valid, it may only utilize ascii"
174 " characters with decimal values between 32 and 126.")
175
176 @property
177 def target(self):
178 """Provide information on the iSCSI Target configuration
179
180 Sample:
181 {
182 'alias': 'myCustomName',
183 'ping': True,
184 'unnamed_discovery': True,
185 'chap': False,
186 'iqn': 'iqn.1992-08.com.netapp:2800.000a132000b006d2000000005a0e8f45',
187 }
188 """
189 target = dict()
190 try:
191 (rc, data) = request(self.url + 'storage-systems/%s/graph/xpath-filter?query=/storagePoolBundle/target'
192 % self.ssid, headers=HEADERS, **self.creds)
193 # This likely isn't an iSCSI-enabled system
194 if not data:
195 self.module.fail_json(
196 msg="This storage-system doesn't appear to have iSCSI interfaces. Array Id [%s]." % (self.ssid))
197
198 data = data[0]
199
200 chap = any(auth for auth in data['configuredAuthMethods']['authMethodData'] if auth['authMethod'] == 'chap')
201
202 target.update(dict(alias=data['alias']['iscsiAlias'],
203 iqn=data['nodeName']['iscsiNodeName'],
204 chap=chap))
205
206 (rc, data) = request(self.url + 'storage-systems/%s/graph/xpath-filter?query=/sa/iscsiEntityData'
207 % self.ssid, headers=HEADERS, **self.creds)
208
209 data = data[0]
210 target.update(dict(ping=data['icmpPingResponseEnabled'],
211 unnamed_discovery=data['unnamedDiscoverySessionsEnabled']))
212
213 except Exception as err:
214 self.module.fail_json(
215 msg="Failed to retrieve the iSCSI target information. Array Id [%s]. Error [%s]."
216 % (self.ssid, to_native(err)))
217
218 return target
219
220 def apply_iscsi_settings(self):
221 """Update the iSCSI target alias and CHAP settings"""
222 update = False
223 target = self.target
224
225 body = dict()
226
227 if self.name is not None and self.name != target['alias']:
228 update = True
229 body['alias'] = self.name
230
231 # If the CHAP secret was provided, we trigger an update.
232 if self.chap_secret:
233 update = True
234 body.update(dict(enableChapAuthentication=True,
235 chapSecret=self.chap_secret))
236 # If no secret was provided, then we disable chap
237 elif target['chap']:
238 update = True
239 body.update(dict(enableChapAuthentication=False))
240
241 if update and not self.check_mode:
242 try:
243 request(self.url + 'storage-systems/%s/iscsi/target-settings' % self.ssid, method='POST',
244 data=json.dumps(body), headers=HEADERS, **self.creds)
245 except Exception as err:
246 self.module.fail_json(
247 msg="Failed to update the iSCSI target settings. Array Id [%s]. Error [%s]."
248 % (self.ssid, to_native(err)))
249
250 return update
251
252 def apply_target_changes(self):
253 update = False
254 target = self.target
255
256 body = dict()
257
258 if self.ping != target['ping']:
259 update = True
260 body['icmpPingResponseEnabled'] = self.ping
261
262 if self.unnamed_discovery != target['unnamed_discovery']:
263 update = True
264 body['unnamedDiscoverySessionsEnabled'] = self.unnamed_discovery
265
266 self._logger.info(pformat(body))
267 if update and not self.check_mode:
268 try:
269 request(self.url + 'storage-systems/%s/iscsi/entity' % self.ssid, method='POST',
270 data=json.dumps(body), timeout=60, headers=HEADERS, **self.creds)
271 except Exception as err:
272 self.module.fail_json(
273 msg="Failed to update the iSCSI target settings. Array Id [%s]. Error [%s]."
274 % (self.ssid, to_native(err)))
275 return update
276
277 def update(self):
278 update = self.apply_iscsi_settings()
279 update = self.apply_target_changes() or update
280
281 target = self.target
282 data = dict((key, target[key]) for key in target if key in ['iqn', 'alias'])
283
284 self.module.exit_json(msg="The interface settings have been updated.", changed=update, **data)
285
286 def __call__(self, *args, **kwargs):
287 self.update()
288
289
290 def main():
291 iface = IscsiTarget()
292 iface()
293
294
295 if __name__ == '__main__':
296 main()