Debian Codegraph @

ansible_collections/netapp_eseries/santricity/plugins/modules/netapp_e_lun_mapping.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_lun_mapping
17 author:
18 - Kevin Hulquest (@hulquest)
19 - Nathan Swartz (@swartzn)
20 - Vu Tran (@VuTran007)
21 short_description: NetApp E-Series create, delete, or modify lun mappings
22 description:
23 - Create, delete, or modify mappings between a volume and a targeted host/host+ group.
24 version_added: "2.2.0"
25 extends_documentation_fragment:
26 - netapp_eseries.santricity.santricity.netapp.eseries
27 options:
28 state:
29 description:
30 - Present will ensure the mapping exists, absent will remove the mapping.
31 required: True
32 type: str
33 choices: ["present", "absent"]
34 target:
35 description:
36 - The name of host or hostgroup you wish to assign to the mapping
37 - If omitted, the default hostgroup is used.
38 - If the supplied I(volume_name) is associated with a different target, it will be updated to what is supplied here.
39 type: str
40 required: False
41 volume_name:
42 description:
43 - The name of the volume you wish to include in the mapping.
44 required: True
45 type: str
46 aliases:
47 - volume
48 lun:
49 description:
50 - The LUN value you wish to give the mapping.
51 - If the supplied I(volume_name) is associated with a different LUN, it will be updated to what is supplied here.
52 - LUN value will be determine by the storage-system when not specified.
53 version_added: 2.7.0
54 type: int
55 required: no
56 target_type:
57 description:
58 - This option specifies the whether the target should be a host or a group of hosts
59 - Only necessary when the target name is used for both a host and a group of hosts
60 choices:
61 - host
62 - group
63 version_added: 2.7.0
64 type: str
65 required: no
66 '''
67
68 EXAMPLES = '''
69 ---
70 - name: Map volume1 to the host target host1
71 netapp_e_lun_mapping:
72 ssid: 1
73 api_url: "{{ netapp_api_url }}"
74 api_username: "{{ netapp_api_username }}"
75 api_password: "{{ netapp_api_password }}"
76 validate_certs: no
77 state: present
78 target: host1
79 volume: volume1
80 - name: Delete the lun mapping between volume1 and host1
81 netapp_e_lun_mapping:
82 ssid: 1
83 api_url: "{{ netapp_api_url }}"
84 api_username: "{{ netapp_api_username }}"
85 api_password: "{{ netapp_api_password }}"
86 validate_certs: yes
87 state: absent
88 target: host1
89 volume: volume1
90 '''
91 RETURN = '''
92 msg:
93 description: success of the module
94 returned: always
95 type: str
96 sample: Lun mapping is complete
97 '''
98 import json
99
100 from ansible.module_utils.basic import AnsibleModule
101 from ansible_collections.netapp_eseries.santricity.plugins.module_utils.netapp import request, eseries_host_argument_spec
102 from ansible.module_utils._text import to_native
103
104 HEADERS = {
105 "Content-Type": "application/json",
106 "Accept": "application/json"
107 }
108
109
110 class LunMapping(object):
111 def __init__(self):
112 argument_spec = eseries_host_argument_spec()
113 argument_spec.update(dict(
114 state=dict(required=True, choices=["present", "absent"]),
115 target=dict(required=False, default=None),
116 volume_name=dict(required=True, aliases=["volume"]),
117 lun=dict(type="int", required=False),
118 target_type=dict(required=False, choices=["host", "group"])))
119 self.module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)
120 args = self.module.params
121
122 self.state = args["state"] in ["present"]
123 self.target = args["target"]
124 self.volume = args["volume_name"]
125 self.lun = args["lun"]
126 self.target_type = args["target_type"]
127 self.ssid = args["ssid"]
128 self.url = args["api_url"]
129 self.check_mode = self.module.check_mode
130 self.creds = dict(url_username=args["api_username"],
131 url_password=args["api_password"],
132 validate_certs=args["validate_certs"])
133 self.mapping_info = None
134
135 if not self.url.endswith('/'):
136 self.url += '/'
137
138 def update_mapping_info(self):
139 """Collect the current state of the storage array."""
140 response = None
141 try:
142 rc, response = request(self.url + "storage-systems/%s/graph" % self.ssid,
143 method="GET", headers=HEADERS, **self.creds)
144
145 except Exception as error:
146 self.module.fail_json(
147 msg="Failed to retrieve storage array graph. Id [%s]. Error [%s]" % (self.ssid, to_native(error)))
148
149 # Create dictionary containing host/cluster references mapped to their names
150 target_reference = {}
151 target_name = {}
152 target_type = {}
153
154 if self.target_type is None or self.target_type == "host":
155 for host in response["storagePoolBundle"]["host"]:
156 target_reference.update({host["hostRef"]: host["name"]})
157 target_name.update({host["name"]: host["hostRef"]})
158 target_type.update({host["name"]: "host"})
159
160 if self.target_type is None or self.target_type == "group":
161 for cluster in response["storagePoolBundle"]["cluster"]:
162
163 # Verify there is no ambiguity between target's type (ie host and group has the same name)
164 if self.target and self.target_type is None and cluster["name"] == self.target and \
165 self.target in target_name.keys():
166 self.module.fail_json(msg="Ambiguous target type: target name is used for both host and group"
167 " targets! Id [%s]" % self.ssid)
168
169 target_reference.update({cluster["clusterRef"]: cluster["name"]})
170 target_name.update({cluster["name"]: cluster["clusterRef"]})
171 target_type.update({cluster["name"]: "group"})
172
173 volume_reference = {}
174 volume_name = {}
175 lun_name = {}
176 for volume in response["volume"]:
177 volume_reference.update({volume["volumeRef"]: volume["name"]})
178 volume_name.update({volume["name"]: volume["volumeRef"]})
179 if volume["listOfMappings"]:
180 lun_name.update({volume["name"]: volume["listOfMappings"][0]["lun"]})
181 for volume in response["highLevelVolBundle"]["thinVolume"]:
182 volume_reference.update({volume["volumeRef"]: volume["name"]})
183 volume_name.update({volume["name"]: volume["volumeRef"]})
184 if volume["listOfMappings"]:
185 lun_name.update({volume["name"]: volume["listOfMappings"][0]["lun"]})
186
187 # Build current mapping object
188 self.mapping_info = dict(lun_mapping=[dict(volume_reference=mapping["volumeRef"],
189 map_reference=mapping["mapRef"],
190 lun_mapping_reference=mapping["lunMappingRef"],
191 lun=mapping["lun"]
192 ) for mapping in response["storagePoolBundle"]["lunMapping"]],
193 volume_by_reference=volume_reference,
194 volume_by_name=volume_name,
195 lun_by_name=lun_name,
196 target_by_reference=target_reference,
197 target_by_name=target_name,
198 target_type_by_name=target_type)
199
200 def get_lun_mapping(self):
201 """Find the matching lun mapping reference.
202
203 Returns: tuple(bool, int, int): contains volume match, volume mapping reference and mapping lun
204 """
205 target_match = False
206 reference = None
207 lun = None
208
209 self.update_mapping_info()
210
211 # Verify that when a lun is specified that it does not match an existing lun value unless it is associated with
212 # the specified volume (ie for an update)
213 if self.lun and any((self.lun == lun_mapping["lun"] and
214 self.target == self.mapping_info["target_by_reference"][lun_mapping["map_reference"]] and
215 self.volume != self.mapping_info["volume_by_reference"][lun_mapping["volume_reference"]]
216 ) for lun_mapping in self.mapping_info["lun_mapping"]):
217 self.module.fail_json(msg="Option lun value is already in use for target! Array Id [%s]." % self.ssid)
218
219 # Verify that when target_type is specified then it matches the target's actually type
220 if self.target and self.target_type and self.target in self.mapping_info["target_type_by_name"].keys() and \
221 self.mapping_info["target_type_by_name"][self.target] != self.target_type:
222 self.module.fail_json(
223 msg="Option target does not match the specified target_type! Id [%s]." % self.ssid)
224
225 # Verify volume and target exist if needed for expected state.
226 if self.state:
227 if self.volume not in self.mapping_info["volume_by_name"].keys():
228 self.module.fail_json(msg="Volume does not exist. Id [%s]." % self.ssid)
229 if self.target and self.target not in self.mapping_info["target_by_name"].keys():
230 self.module.fail_json(msg="Target does not exist. Id [%s'." % self.ssid)
231
232 for lun_mapping in self.mapping_info["lun_mapping"]:
233
234 # Find matching volume reference
235 if lun_mapping["volume_reference"] == self.mapping_info["volume_by_name"][self.volume]:
236 reference = lun_mapping["lun_mapping_reference"]
237 lun = lun_mapping["lun"]
238
239 # Determine if lun mapping is attached to target with the
240 if (lun_mapping["map_reference"] in self.mapping_info["target_by_reference"].keys() and
241 self.mapping_info["target_by_reference"][lun_mapping["map_reference"]] == self.target and
242 (self.lun is None or lun == self.lun)):
243 target_match = True
244
245 return target_match, reference, lun
246
247 def update(self):
248 """Execute the changes the require changes on the storage array."""
249 target_match, lun_reference, lun = self.get_lun_mapping()
250 update = (self.state and not target_match) or (not self.state and target_match)
251
252 if update and not self.check_mode:
253 try:
254 if self.state:
255 body = dict()
256 target = None if not self.target else self.mapping_info["target_by_name"][self.target]
257 if target:
258 body.update(dict(targetId=target))
259 if self.lun is not None:
260 body.update(dict(lun=self.lun))
261
262 if lun_reference:
263
264 rc, response = request(self.url + "storage-systems/%s/volume-mappings/%s/move"
265 % (self.ssid, lun_reference), method="POST", data=json.dumps(body),
266 headers=HEADERS, **self.creds)
267 else:
268 body.update(dict(mappableObjectId=self.mapping_info["volume_by_name"][self.volume]))
269 rc, response = request(self.url + "storage-systems/%s/volume-mappings" % self.ssid,
270 method="POST", data=json.dumps(body), headers=HEADERS, **self.creds)
271
272 else: # Remove existing lun mapping for volume and target
273 rc, response = request(self.url + "storage-systems/%s/volume-mappings/%s"
274 % (self.ssid, lun_reference),
275 method="DELETE", headers=HEADERS, **self.creds)
276 except Exception as error:
277 self.module.fail_json(
278 msg="Failed to update storage array lun mapping. Id [%s]. Error [%s]"
279 % (self.ssid, to_native(error)))
280
281 self.module.exit_json(msg="Lun mapping is complete.", changed=update)
282
283
284 def main():
285 lun_mapping = LunMapping()
286 lun_mapping.update()
287
288
289 if __name__ == '__main__':
290 main()