Debian Codegraph @

ansible_collections/netapp/ontap/plugins/modules/na_ontap_igroup_initiator.py

raw
1 #!/usr/bin/python
2 ''' This is an Ansible module for ONTAP, to manage initiators in an Igroup
3
4 (c) 2019-2026, NetApp, Inc
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6 '''
7
8 from __future__ import absolute_import, division, print_function
9 __metaclass__ = type
10
11
12 DOCUMENTATION = '''
13
14 module: na_ontap_igroup_initiator
15 short_description: NetApp ONTAP igroup initiator configuration
16 extends_documentation_fragment:
17 - netapp.ontap.netapp.na_ontap
18 version_added: 2.8.0
19 author: NetApp Ansible Team (@carchi8py) <[email protected]>
20
21 description:
22 - Add/Remove initiators from an igroup
23
24 options:
25 state:
26 description:
27 - Whether the specified initiator should exist or not in an igroup.
28 choices: ['present', 'absent']
29 type: str
30 default: present
31
32 names:
33 description:
34 - List of initiators to manage.
35 required: true
36 aliases:
37 - name
38 type: list
39 elements: str
40
41 initiator_group:
42 description:
43 - Name of the initiator group to which the initiator belongs.
44 required: true
45 type: str
46
47 force_remove:
48 description:
49 - Forcibly remove the initiators even if there are existing LUNs mapped to the initiator group.
50 type: bool
51 default: false
52 version_added: '20.1.0'
53
54 vserver:
55 description:
56 - The name of the vserver to use.
57 required: true
58 type: str
59
60 lambda_config:
61 description:
62 - Configuration parameters for AWS Lambda proxy functionality.
63 - These option and suboptions are only supported with REST.
64 type: dict
65 version_added: 23.4.0
66 suboptions:
67 function_name:
68 description:
69 - The name of the AWS Lambda function to invoke.
70 type: str
71 required: true
72 aws_region:
73 description:
74 - The name of the AWS region.
75 type: str
76 required: true
77 aws_profile:
78 description:
79 - The name of the AWS profile to use for authentication.
80 type: str
81
82 notes:
83 - Supports AWS Lambda proxy functionality when using REST. See the README file for examples.
84 '''
85
86 EXAMPLES = '''
87 - name: Add initiators to an igroup
88 netapp.ontap.na_ontap_igroup_initiator:
89 names: abc.test:def.com,def.test:efg.com
90 initiator_group: test_group
91 vserver: ansibleVServer
92 hostname: "{{ netapp_hostname }}"
93 username: "{{ netapp_username }}"
94 password: "{{ netapp_password }}"
95
96 - name: Remove an initiator from an igroup
97 netapp.ontap.na_ontap_igroup_initiator:
98 state: absent
99 names: abc.test:def.com
100 initiator_group: test_group
101 vserver: ansibleVServer
102 hostname: "{{ netapp_hostname }}"
103 username: "{{ netapp_username }}"
104 password: "{{ netapp_password }}"
105 '''
106
107 RETURN = '''
108 '''
109
110 import traceback
111
112 from ansible.module_utils.basic import AnsibleModule
113 from ansible.module_utils._text import to_native
114 import ansible_collections.netapp.ontap.plugins.module_utils.netapp as netapp_utils
115 from ansible_collections.netapp.ontap.plugins.module_utils.netapp_module import NetAppModule
116 from ansible_collections.netapp.ontap.plugins.module_utils.netapp import OntapRestAPI
117 from ansible_collections.netapp.ontap.plugins.module_utils import rest_generic
118
119
120 class NetAppOntapIgroupInitiator(object):
121
122 def __init__(self):
123
124 self.argument_spec = netapp_utils.na_ontap_host_argument_spec()
125 self.argument_spec.update(dict(
126 state=dict(required=False, type='str', choices=['present', 'absent'], default='present'),
127 names=dict(required=True, type='list', elements='str', aliases=['name']),
128 initiator_group=dict(required=True, type='str'),
129 force_remove=dict(required=False, type='bool', default=False),
130 vserver=dict(required=True, type='str'),
131 ))
132
133 self.argument_spec.update(netapp_utils.na_ontap_lambda_argument_spec())
134
135 self.module = AnsibleModule(
136 argument_spec=self.argument_spec,
137 supports_check_mode=True,
138 required_if=[
139 ['use_lambda', True, ('lambda_config',)]
140 ],
141 )
142
143 self.na_helper = NetAppModule()
144 self.parameters = self.na_helper.set_parameters(self.module.params)
145
146 self.rest_api = OntapRestAPI(self.module)
147 self.use_rest = self.rest_api.is_rest()
148 self.uuid = None
149
150 if not self.use_rest:
151 if self.parameters.get('use_lambda'):
152 self.module.fail_json(msg="Error: AWS Lambda proxy for ONTAP APIs is only supported with REST.")
153 if not netapp_utils.has_netapp_lib():
154 self.module.fail_json(msg=netapp_utils.netapp_lib_is_required())
155 self.server = netapp_utils.setup_na_ontap_zapi(module=self.module, vserver=self.parameters['vserver'])
156
157 def get_initiators(self):
158 """
159 Get the existing list of initiators from an igroup
160 :rtype: list() or None
161 """
162 if self.use_rest:
163 return self.get_initiators_rest()
164 igroup_info = netapp_utils.zapi.NaElement('igroup-get-iter')
165 attributes = dict(query={'initiator-group-info': {'initiator-group-name': self.parameters['initiator_group'],
166 'vserver': self.parameters['vserver']}})
167 igroup_info.translate_struct(attributes)
168 result, current = None, []
169
170 try:
171 result = self.server.invoke_successfully(igroup_info, True)
172 except netapp_utils.zapi.NaApiError as error:
173 self.module.fail_json(msg='Error fetching igroup info %s: %s' % (self.parameters['initiator_group'],
174 to_native(error)),
175 exception=traceback.format_exc())
176
177 if result.get_child_by_name('num-records') and int(result.get_child_content('num-records')) >= 1:
178 igroup_info = result.get_child_by_name('attributes-list').get_child_by_name('initiator-group-info')
179 if igroup_info.get_child_by_name('initiators') is not None:
180 current = [initiator['initiator-name'] for initiator in igroup_info['initiators'].get_children()]
181 return current
182
183 def modify_initiator(self, initiator_name, zapi):
184 """
185 Add or remove an initiator to/from an igroup
186 """
187 if self.use_rest:
188 return self.modify_initiator_rest(initiator_name, zapi)
189 options = {'initiator-group-name': self.parameters['initiator_group'],
190 'initiator': initiator_name,
191 'force': 'true' if zapi == 'igroup-remove' and self.parameters['force_remove'] else 'false'}
192 initiator_modify = netapp_utils.zapi.NaElement.create_node_with_children(zapi, **options)
193
194 try:
195 self.server.invoke_successfully(initiator_modify, enable_tunneling=True)
196 except netapp_utils.zapi.NaApiError as error:
197 self.module.fail_json(msg='Error modifying igroup initiator %s: %s' % (initiator_name,
198 to_native(error)),
199 exception=traceback.format_exc())
200
201 def get_initiators_rest(self):
202 api = 'protocols/san/igroups'
203 query = {'name': self.parameters['initiator_group'], 'svm.name': self.parameters['vserver']}
204 fields = 'initiators,uuid'
205 record, error = rest_generic.get_one_record(self.rest_api, api, query, fields)
206 if error:
207 self.module.fail_json(msg="Error fetching igroup info %s: %s" % (self.parameters['initiator_group'], error))
208 current = []
209 if record:
210 self.uuid = record['uuid']
211 # igroup may have 0 initiators.
212 if 'initiators' in record:
213 current = [initiator['name'] for initiator in record['initiators']]
214 return current
215
216 def modify_initiator_rest(self, initiator_name, modify_action):
217 if self.uuid is None:
218 self.module.fail_json(msg="Error modifying igroup initiator %s: igroup not found" % initiator_name)
219 api = 'protocols/san/igroups/%s/initiators' % self.uuid
220 if modify_action == 'igroup-add':
221 body = {"name": initiator_name}
222 dummy, error = rest_generic.post_async(self.rest_api, api, body)
223 else:
224 query = {'allow_delete_while_mapped': self.parameters['force_remove']}
225 dummy, error = rest_generic.delete_async(self.rest_api, api, initiator_name.lower(), query)
226 if error:
227 self.module.fail_json(msg="Error modifying igroup initiator %s: %s" % (initiator_name, error))
228
229 def apply(self):
230 initiators = self.get_initiators()
231 for initiator in self.parameters['names']:
232 present = None
233 initiator = self.na_helper.sanitize_wwn(initiator)
234 if initiator.lower() in initiators:
235 present = True
236 cd_action = self.na_helper.get_cd_action(present, self.parameters)
237 if self.na_helper.changed and not self.module.check_mode:
238 if cd_action == 'create':
239 self.modify_initiator(initiator, 'igroup-add')
240 elif cd_action == 'delete':
241 self.modify_initiator(initiator, 'igroup-remove')
242 result = netapp_utils.generate_result(self.na_helper.changed, cd_action)
243 self.module.exit_json(**result)
244
245
246 def main():
247 obj = NetAppOntapIgroupInitiator()
248 obj.apply()
249
250
251 if __name__ == '__main__':
252 main()