Debian Codegraph @

ansible_collections/azure/azcollection/plugins/modules/azure_rm_cognitivesearch.py

raw symbols SCIP
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2020 David Duque Hernández, (@next-davidduquehernandez)
4 #
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 __metaclass__ = type
9
10
11 DOCUMENTATION = '''
12 ---
13 module: azure_rm_cognitivesearch
14 version_added: "1.4.0"
15 short_description: Manage Azure Cognitive Search service
16 description:
17 - Create, update or delete Azure Cognitive Search service.
18 options:
19 name:
20 description:
21 - The name of the Azure Cognitive Search service.
22 - Search service names must only contain lowercase letters, digits or dashes.
23 - Cannot use dash as the first two or last one characters.
24 - Cannot contain consecutive dashes.
25 - Must be between 2 and 60 characters in length.
26 - Search service names must be globally unique.
27 - You cannot change the service name after the service is created.
28 type: str
29 required: true
30 resource_group:
31 description:
32 - The name of the resource group within the current subscription.
33 type: str
34 required: true
35 location:
36 description:
37 - Valid azure location. Defaults to location of the resource group.
38 type: str
39 hosting_mode:
40 description:
41 - Applicable only for the standard3 SKU.
42 - You can set this property to enable up to 3 high density partitions that allow up to 1000 indexes.
43 - For the standard3 SKU, the value is either 'default' or 'highDensity'.
44 - For all other SKUs, this value must be 'default'.
45 choices:
46 - default
47 - highDensity
48 type: str
49 default: 'default'
50 identity:
51 description:
52 - The identity for the resource.
53 choices:
54 - None
55 - SystemAssigned
56 type: str
57 default: 'None'
58 network_rule_set:
59 description:
60 - Network specific rules that determine how the Azure Cognitive Search service may be reached.
61 type: list
62 elements: str
63 partition_count:
64 description:
65 - The number of partitions in the search service.
66 - It can be C(1), C(2), C(3), C(4), C(6), or C(12).
67 - Values greater than 1 are only valid for standard SKUs.
68 - For 'standard3' services with hostingMode set to 'highDensity', the allowed values are between 1 and 3.
69 type: int
70 default: 1
71 public_network_access:
72 description:
73 - This value can be set to C(enabled) to avoid breaking changes on existing customer resources and templates.
74 - If set to C(enabled), traffic over public interface is not allowed, and private endpoint connections would be the exclusive access method.
75 choices:
76 - enabled
77 - disabled
78 type: str
79 default: 'enabled'
80 replica_count:
81 description:
82 - The number of replicas in the search service.
83 - It must be a value between 1 and 12 inclusive for I(sku=standard).
84 - It must be a value between 1 and 3 inclusive for I(sku=basic).
85 type: int
86 default: 1
87 sku:
88 description:
89 - The SKU of the Search Service, which determines price tier and capacity limits.
90 - This property is required when creating a new Search Service.
91 choices:
92 - free
93 - basic
94 - standard
95 - standard2
96 - standard3
97 - storage_optimized_l1
98 - storage_optimized_l2
99 type: str
100 default: 'basic'
101 state:
102 description:
103 - Assert the state of the search instance. Set to C(present) to create or update a search instance. Set to C(absent) to remove a search instance.
104 type: str
105 default: present
106 choices:
107 - absent
108 - present
109
110 extends_documentation_fragment:
111 - azure.azcollection.azure
112 - azure.azcollection.azure_tags
113
114 author:
115 - David Duque Hernández (@next-davidduquehernandez)
116 '''
117
118 EXAMPLES = '''
119 - name: Create Azure Cognitive Search
120 azure_rm_cognitivesearch:
121 resource_group: myResourceGroup
122 name: myAzureSearch
123 '''
124
125 RETURN = '''
126 state:
127 description:
128 - Info for Azure Cognitive Search.
129 returned: always
130 type: dict
131 contains:
132 hosting_mode:
133 description:
134 - Type of hosting mode selected.
135 returned: always
136 type: str
137 sample: default
138 id:
139 description:
140 - The unique identifier associated with this Azure Cognitive Search.
141 returned: always
142 type: str
143 sample: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}
144 identity:
145 description:
146 - The identity of the Azure Cognitive Search Service.
147 returned: always
148 type: dict
149 contains:
150 principal_id:
151 description:
152 - Identifier assigned.
153 type: str
154 sample: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
155 type:
156 description:
157 - Identity type.
158 returned: always
159 type: str
160 sample: SystemAssigned
161 sample:
162 principal_id: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
163 type: SystemAssigned
164 location:
165 description:
166 - The geo-location where the Azure Cognitive Search Service lives.
167 returned: always
168 type: str
169 sample: West Europe
170 name:
171 description:
172 - The name of the Azure Cognitive Search Service.
173 returned: always
174 type: str
175 sample: myazuresearch
176 network_rule_set:
177 description:
178 - Network specific rules that determine how the Azure Cognitive Search service may be reached.
179 returned: always
180 type: list
181 sample: ['1.1.1.1', '8.8.8.8/31']
182 partition_count:
183 description:
184 - The number of partitions in the Azure Cognitive Search Service.
185 returned: always
186 type: int
187 sample: 3
188 provisioning_state:
189 description:
190 - The state of the provisioning state of Azure Cognitive Search Service.
191 returned: always
192 type: str
193 sample: succeeded
194 public_network_access:
195 description:
196 - If it's allowed traffic over public interface.
197 returned: always
198 type: str
199 sample: enabled
200 replica_count:
201 description:
202 - The number of replicas in the Azure Cognitive Search Service.
203 returned: always
204 type: int
205 sample: 3
206 sku:
207 description:
208 - The SKU of the Azure Cognitive Search Service.
209 returned: always
210 type: str
211 sample: standard
212 status:
213 description:
214 - The state of the Azure Cognitive Search.
215 returned: always
216 type: str
217 sample: Active running
218 tags:
219 description:
220 - The resource tags.
221 returned: always
222 type: dict
223 sample: { "tag1":"abc" }
224 '''
225
226 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common import AzureRMModuleBase
227
228 try:
229 from azure.core.exceptions import ResourceNotFoundError
230 except ImportError:
231 # This is handled in azure_rm_common
232 pass
233
234
235 class AzureRMSearch(AzureRMModuleBase):
236 def __init__(self):
237
238 self.module_arg_spec = dict(
239 hosting_mode=dict(type='str', default='default', choices=['default', 'highDensity']),
240 identity=dict(type='str', default='None', choices=['None', 'SystemAssigned']),
241 location=dict(type='str'),
242 name=dict(type='str', required=True),
243 network_rule_set=dict(type='list', elements='str'),
244 partition_count=dict(type='int', default=1),
245 public_network_access=dict(type='str', default='enabled', choices=['enabled', 'disabled']),
246 replica_count=dict(type='int', default=1),
247 resource_group=dict(type='str', required=True),
248 sku=dict(type='str', default='basic', choices=['free', 'basic', 'standard', 'standard2', 'standard3',
249 'storage_optimized_l1', 'storage_optimized_l2']),
250 state=dict(type='str', default='present', choices=['present', 'absent']),
251 tags=dict(type='dict')
252 )
253
254 self.hosting_mode = None
255 self.identity = None
256 self.location = None
257 self.name = None
258 self.network_rule_set = list()
259 self.partition_count = None
260 self.public_network_access = None
261 self.replica_count = None
262 self.resource_group = None
263 self.sku = None
264 self.tags = None
265
266 self.results = dict(changed=False)
267 self.account_dict = None
268 self.firewall_list = list()
269
270 super(AzureRMSearch, self).__init__(derived_arg_spec=self.module_arg_spec,
271 supports_check_mode=False,
272 supports_tags=True)
273
274 def exec_module(self, **kwargs):
275 for key in list(self.module_arg_spec.keys()) + ['tags']:
276 setattr(self, key, kwargs[key])
277
278 resource_group = self.get_resource_group(self.resource_group)
279 if not self.location:
280 self.location = resource_group.location
281
282 self.account_dict = self.get_search()
283
284 if self.account_dict is not None:
285 self.results['state'] = self.account_dict
286 else:
287 self.results['state'] = dict()
288
289 if self.state == 'present':
290 if not self.account_dict:
291 self.results['state'] = self.create_search()
292 else:
293 self.results['state'] = self.update_search()
294 else:
295 self.delete_search()
296 self.results['state'] = dict(state='Deleted')
297
298 return self.results
299
300 def get_search(self):
301 self.log('Get properties for azure search {0}'.format(self.name))
302 search_obj = None
303 account_dict = None
304
305 try:
306 search_obj = self.search_client.services.get(self.resource_group, self.name)
307 except ResourceNotFoundError:
308 pass
309
310 if search_obj:
311 account_dict = self.account_obj_to_dict(search_obj)
312
313 return account_dict
314
315 def check_values(self, hosting_mode, sku, partition_count, replica_count):
316 if (
317 hosting_mode == 'highDensity' and
318 sku != 'standard3'
319 ):
320 self.fail("Hosting mode could not be 'highDensity' if sku is not 'standard3'.")
321
322 if (
323 sku == 'standard3' and
324 hosting_mode == 'highDensity'
325 and partition_count not in [1, 2, 3]
326 ):
327 self.fail("Partition count must be 1, 2 or 3 if hosting mode is 'highDensity' and sku 'standard3'.")
328
329 if partition_count not in [1, 2, 3, 4, 6, 12]:
330 self.fail("Partition count must be 1, 2, 3, 4, 6 or 12.")
331
332 if sku == 'basic':
333 if replica_count not in [1, 2, 3]:
334 self.fail("Replica count must be between 1 and 3.")
335 else:
336 if replica_count < 1 or replica_count > 12:
337 self.fail("Replica count must be between 1 and 12.")
338
339 def create_search(self):
340 self.log("Creating search {0}".format(self.name))
341
342 self.check_values(self.hosting_mode, self.sku, self.partition_count, self.replica_count)
343
344 self.check_name_availability()
345 self.results['changed'] = True
346
347 if self.network_rule_set:
348 for rule in self.network_rule_set:
349 self.firewall_list.append(self.search_client.services.models.IpRule(value=rule))
350
351 search_model = self.search_client.services.models.SearchService(
352 hosting_mode=self.hosting_mode,
353 identity=self.search_client.services.models.Identity(type=self.identity),
354 location=self.location,
355 network_rule_set=dict(ip_rules=self.firewall_list) if len(self.firewall_list) > 0 else None,
356 partition_count=self.partition_count,
357 public_network_access=self.public_network_access,
358 replica_count=self.replica_count,
359 sku=self.search_client.services.models.Sku(name=self.sku),
360 tags=self.tags
361 )
362
363 try:
364 poller = self.search_client.services.begin_create_or_update(self.resource_group, self.name, search_model)
365 self.get_poller_result(poller)
366 except Exception as e:
367 self.log('Error creating Azure Search.')
368 self.fail("Failed to create Azure Search: {0}".format(str(e)))
369
370 return self.get_search()
371
372 def update_search(self):
373 self.log("Updating search {0}".format(self.name))
374
375 self.check_values(
376 self.hosting_mode or self.account_dict.get('hosting_mode'),
377 self.sku or self.account_dict.get('sku'),
378 self.partition_count or self.account_dict.get('partition_count'),
379 self.replica_count or self.account_dict.get('replica_count')
380 )
381
382 search_update_model = self.search_client.services.models.SearchServiceUpdate(
383 location=self.location,
384 hosting_mode=None,
385 partition_count=None,
386 public_network_access=None,
387 replica_count=None,
388 sku=self.search_client.services.models.Sku(name=self.account_dict.get('sku'))
389 )
390
391 if self.hosting_mode and self.account_dict.get('hosting_mode') != self.hosting_mode:
392 self.fail("Updating hosting_mode of an existing search service is not allowed.")
393
394 if self.identity and self.account_dict.get('identity').get('type') != self.identity:
395 self.results['changed'] = True
396 search_update_model.identity = self.search_client.services.models.Identity(type=self.identity)
397
398 network_update = False
399 if self.network_rule_set:
400 for rule in self.network_rule_set:
401 if len(self.network_rule_set) != len(self.account_dict.get('network_rule_set')) or rule not in self.account_dict.get('network_rule_set'):
402 self.results['changed'] = True
403 network_update = True
404 self.firewall_list.append(self.search_client.services.models.IpRule(value=rule))
405 search_update_model.network_rule_set = dict(ip_rules=self.firewall_list)
406 elif not network_update:
407 firewall_list = []
408 for rule in self.account_dict.get('network_rule_set', []):
409 firewall_list.append(self.search_client.services.models.IpRule(value=rule))
410 search_update_model.network_rule_set = dict(ip_rules=firewall_list)
411
412 if self.partition_count and self.account_dict.get('partition_count') != self.partition_count:
413 self.results['changed'] = True
414 search_update_model.partition_count = self.partition_count
415 else:
416 search_update_model.partition_count = self.account_dict.get('partition_count')
417
418 if self.public_network_access and self.account_dict.get('public_network_access').lower() != self.public_network_access.lower():
419 self.results['changed'] = True
420 search_update_model.public_network_access = self.public_network_access
421 else:
422 search_update_model.public_network_access = self.account_dict.get('public_network_access')
423
424 if self.replica_count and self.account_dict.get('replica_count') != self.replica_count:
425 self.results['changed'] = True
426 search_update_model.replica_count = self.replica_count
427 else:
428 search_update_model.replica_count = self.account_dict.get('replica_count')
429
430 if self.sku and self.account_dict.get('sku') != self.sku:
431 self.fail("Updating sku of an existing search service is not allowed.")
432
433 update_tags, new_tags = self.update_tags(self.account_dict.get('tags'))
434 if update_tags:
435 self.results['changed'] = True
436 search_update_model.tags = new_tags
437
438 self.log('Updating search {0}'.format(self.name))
439
440 try:
441 if self.results['changed']:
442 poller = self.search_client.services.begin_create_or_update(self.resource_group, self.name, search_update_model)
443 self.get_poller_result(poller)
444 except Exception as e:
445 self.fail("Failed to update the search: {0}".format(str(e)))
446
447 return self.get_search()
448
449 def delete_search(self):
450 self.log('Delete search {0}'.format(self.name))
451
452 try:
453 if self.account_dict is not None:
454 self.results['changed'] = True
455 self.search_client.services.delete(self.resource_group, self.name)
456 except Exception as e:
457 self.fail("Failed to delete the search: {0}".format(str(e)))
458
459 def check_name_availability(self):
460 self.log('Checking name availability for {0}'.format(self.name))
461 try:
462 response = self.search_client.services.check_name_availability(self.name)
463 except Exception as e:
464 self.log('Error attempting to validate name.')
465 self.fail("Error checking name availability: {0}".format(str(e)))
466 if not response.is_name_available:
467 self.log('Error name not available.')
468 self.fail("{0} - {1}".format(response.message, response.reason))
469
470 def account_obj_to_dict(self, search_obj):
471 account_dict = dict(
472 hosting_mode=search_obj.hosting_mode,
473 id=search_obj.id,
474 identity=dict(type=search_obj.identity.type if search_obj.identity else 'None'),
475 location=search_obj.location,
476 name=search_obj.name,
477 network_rule_set=list(),
478 partition_count=search_obj.partition_count,
479 provisioning_state=search_obj.provisioning_state,
480 public_network_access=search_obj.public_network_access,
481 replica_count=search_obj.replica_count,
482 sku=search_obj.sku.name,
483 status=search_obj.status,
484 tags=search_obj.tags
485 )
486
487 if search_obj.identity and search_obj.identity.principal_id:
488 account_dict['identity']['principal_id'] = search_obj.identity.principal_id
489
490 for rule in search_obj.network_rule_set.ip_rules:
491 account_dict['network_rule_set'].append(rule.value)
492
493 return account_dict
494
495
496 def main():
497 AzureRMSearch()
498
499
500 if __name__ == '__main__':
501 main()