Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2018 Yunge Zhu, <[email protected]>
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_rediscache
14 version_added: "0.1.2"
15 short_description: Manage Azure Cache for Redis instance
16 description:
17 - Create, update and delete instance of Azure Cache for Redis.
18
19 options:
20 resource_group:
21 description:
22 - Name of the resource group to which the resource belongs.
23 required: True
24 type: str
25 name:
26 description:
27 - Unique name of the Azure Cache for Redis to create or update.
28 required: True
29 type: str
30 location:
31 description:
32 - Resource location. If not set, location from the resource group will be used as default.
33 type: str
34 sku:
35 description:
36 - SKU info of Azure Cache for Redis.
37 type: dict
38 required: true
39 suboptions:
40 name:
41 description:
42 - Type of Azure Cache for Redis to deploy.
43 type: str
44 required: true
45 choices:
46 - basic
47 - standard
48 - premium
49 size:
50 description:
51 - Size of Azure Cache for Redis to deploy.
52 - When I(sku=basic) or I(sku=standard), allowed values are C(C0), C(C1), C(C2), C(C3), C(C4), C(C5), C(C6).
53 - When I(sku=premium), allowed values are C(P1), C(P2), C(P3), C(P4).
54 - Please see U(https://docs.microsoft.com/en-us/rest/api/redis/redis/create#sku) for allowed values.
55 type: str
56 required: true
57 choices:
58 - C0
59 - C1
60 - C2
61 - C3
62 - C4
63 - C5
64 - C6
65 - P1
66 - P2
67 - P3
68 - P4
69 enable_non_ssl_port:
70 description:
71 - When set I(enable_non_ssl_port=true), the non-ssl Redis server port 6379 will be enabled.
72 type: bool
73 default: false
74 maxfragmentationmemory_reserved:
75 description:
76 - Configures the amount of memory in MB that is reserved to accommodate for memory fragmentation.
77 - Please see U(https://docs.microsoft.com/en-us/azure/redis-cache/cache-configure#advanced-settings) for more detail.
78 type: int
79 maxmemory_reserved:
80 description:
81 - Configures the amount of memory in MB that is reserved for non-cache operations.
82 - Please see U(https://docs.microsoft.com/en-us/azure/redis-cache/cache-configure#advanced-settings) for more detail.
83 type: int
84 maxmemory_policy:
85 description:
86 - Configures the eviction policy of the cache.
87 - Please see U(https://docs.microsoft.com/en-us/azure/redis-cache/cache-configure#advanced-settings) for more detail.
88 type: str
89 choices:
90 - volatile_lru
91 - allkeys_lru
92 - volatile_random
93 - allkeys_random
94 - volatile_ttl
95 - noeviction
96 minimum_tls_version:
97 description:
98 - Require clients to use a specified TLS version.
99 type: str
100 choices:
101 - "1.0"
102 - "1.1"
103 - "1.2"
104 version_added: "1.10.0"
105 public_network_access:
106 description:
107 - Whether or not public endpoint access is allowed for this cache.
108 type: str
109 default: Enabled
110 choices:
111 - Enabled
112 - Disabled
113 version_added: "1.10.0"
114 notify_keyspace_events:
115 description:
116 - Allows clients to receive notifications when certain events occur.
117 - Please see U(https://docs.microsoft.com/en-us/azure/redis-cache/cache-configure#advanced-settings) for more detail.
118 type: str
119 redis_version:
120 description:
121 - The major version of Redis.
122 type: str
123 choices:
124 - "4"
125 - "6"
126 default: "6"
127 version_added: "1.10.0"
128 shard_count:
129 description:
130 - The number of shards to be created when I(sku=premium).
131 type: int
132 static_ip:
133 description:
134 - Static IP address. Required when deploying an Azure Cache for Redis inside an existing Azure virtual network.
135 type: str
136 subnet:
137 description:
138 - Subnet in a virtual network to deploy the Azure Cache for Redis in.
139 - It can be resource id of subnet, for example
140 /subscriptions/{subid}/resourceGroups/{resourceGroupName}/Microsoft.{Network|ClassicNetwork}/VirtualNetworks/vnet1/subnets/subnet1.
141 - It can be a dictionary where contains I(name), I(virtual_network_name) and I(resource_group).
142 - I(name). Name of the subnet.
143 - I(resource_group). Resource group name of the subnet.
144 - I(virtual_network_name). Name of virtual network to which this subnet belongs.
145 type: raw
146 tenant_settings:
147 description:
148 - Dict of tenant settings.
149 type: dict
150 reboot:
151 description:
152 - Reboot specified Redis node(s). There can be potential data loss.
153 type: dict
154 suboptions:
155 shard_id:
156 description:
157 - If clustering is enabled, the id of the shard to be rebooted.
158 type: str
159 reboot_type:
160 description:
161 - Which Redis node(s) to reboot.
162 type: str
163 choices:
164 - primary
165 - secondary
166 - all
167 regenerate_key:
168 description:
169 - Regenerate Redis cache's access keys.
170 type: dict
171 suboptions:
172 key_type:
173 description:
174 - The Redis key to regenerate.
175 type: str
176 choices:
177 - primary
178 - secondary
179 wait_for_provisioning:
180 description:
181 - Wait till the Azure Cache for Redis instance provisioning_state is Succeeded.
182 - It takes several minutes for Azure Cache for Redis to be provisioned ready for use after creating/updating/rebooting.
183 - Set this option to C(true) to wait for provisioning_state. Set to C(false) if you don't care about provisioning_state.
184 - Poll wait timeout is 60 minutes.
185 type: bool
186 default: True
187 state:
188 description:
189 - Assert the state of the Azure Cache for Redis.
190 - Use C(present) to create or update an Azure Cache for Redis and C(absent) to delete it.
191 default: present
192 type: str
193 choices:
194 - absent
195 - present
196
197 extends_documentation_fragment:
198 - azure.azcollection.azure
199 - azure.azcollection.azure_tags
200 - azure.azcollection.azure_identity_multiple
201
202 author:
203 - Yunge Zhu(@yungezz)
204
205 '''
206
207 EXAMPLES = '''
208 - name: Create an Azure Cache for Redis
209 azure_rm_rediscache:
210 resource_group: myResourceGroup
211 name: myRedis
212 sku:
213 name: basic
214 size: C1
215
216 - name: Scale up the Azure Cache for Redis
217 azure_rm_rediscache:
218 resource_group: myResourceGroup
219 name: myRedis
220 sku:
221 name: standard
222 size: C1
223 tags:
224 testing: foo
225
226 - name: Force reboot the redis cache
227 azure_rm_rediscache:
228 resource_group: myResourceGroup
229 name: myRedisCache
230 reboot:
231 reboot_type: all
232
233 - name: Create Azure Cache for Redis with subnet
234 azure_rm_rediscache:
235 resource_group: myResourceGroup
236 name: myRedis
237 sku:
238 name: premium
239 size: P1
240 subnet: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.Network/virtualNetworks/myVirt
241 ualNetwork/subnets/mySubnet"
242
243 - name: Regenerate primary Redis key
244 azure_rm_rediscache:
245 resource_group: myResourceGroup
246 name: myRedis
247 regenerate_key:
248 key_type: primary
249 '''
250
251 RETURN = '''
252 id:
253 description:
254 - Id of the Azure Cache for Redis.
255 returned: always
256 type: str
257 sample: "/subscriptions/xxxxxxxx-xxxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.Cache/Redis/myRedis"
258 host_name:
259 description:
260 - Host name of the Azure Cache for Redis.
261 returned: when I(state=present)
262 type: str
263 sample: "myredis.redis.cache.windows.net"
264 '''
265
266 import time
267
268 try:
269 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common_ext import AzureRMModuleBaseExt
270 from azure.core.exceptions import ResourceNotFoundError
271 from azure.core.polling import LROPoller
272 from azure.mgmt.redis import RedisManagementClient
273 from azure.mgmt.redis.models import (
274 RedisCreateParameters, RedisUpdateParameters, Sku, RedisRebootParameters,
275 RedisRegenerateKeyParameters, ManagedServiceIdentity, UserAssignedIdentity
276 )
277 except ImportError:
278 # This is handled in azure_rm_common
279 pass
280
281
282 sku_spec = dict(
283 name=dict(
284 type='str',
285 required=True,
286 choices=['basic', 'standard', 'premium']),
287 size=dict(
288 type='str',
289 required=True,
290 choices=['C0', 'C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'P1', 'P2', 'P3', 'P4']
291 )
292 )
293
294
295 reboot_spec = dict(
296 shard_id=dict(
297 type='str'
298 ),
299 reboot_type=dict(
300 type='str',
301 choices=['primary', 'secondary', 'all']
302 )
303 )
304
305
306 regenerate_key_spec = dict(
307 key_type=dict(
308 type='str',
309 choices=['primary', 'secondary']
310 )
311 )
312
313
314 def rediscache_to_dict(redis):
315 result = dict(
316 id=redis.id,
317 name=redis.name,
318 location=redis.location,
319 sku=dict(
320 name=redis.sku.name.lower(),
321 size=redis.sku.family + str(redis.sku.capacity)
322 ),
323 enable_non_ssl_port=redis.enable_non_ssl_port,
324 host_name=redis.host_name,
325 minimum_tls_version=redis.minimum_tls_version,
326 public_network_access=redis.public_network_access,
327 redis_version=redis.redis_version,
328 shard_count=redis.shard_count,
329 subnet=redis.subnet_id,
330 static_ip=redis.static_ip,
331 provisioning_state=redis.provisioning_state,
332 tenant_settings=redis.tenant_settings,
333 tags=redis.tags if redis.tags else None,
334 identity=redis.identity.as_dict() if redis.identity else None,
335 configuration=redis.redis_configuration.as_dict() if redis.redis_configuration else None
336 )
337 return result
338
339
340 def hyphen_to_underline(input):
341 if input and isinstance(input, str):
342 return input.replace("-", "_")
343 return input
344
345
346 def underline_to_hyphen(input):
347 if input and isinstance(input, str):
348 return input.replace("_", "-")
349 return input
350
351
352 def get_reboot_type(type):
353 if type == "primary":
354 return "PrimaryNode"
355 if type == "secondary":
356 return "SecondaryNode"
357 if type == "all":
358 return "AllNodes"
359 return type
360
361
362 class Actions:
363 NoAction, Create, Update, Delete = range(4)
364
365
366 class AzureRMRedisCaches(AzureRMModuleBaseExt):
367 """Configuration class for an Azure RM Cache for Redis resource"""
368
369 def __init__(self):
370 self.module_arg_spec = dict(
371 resource_group=dict(
372 type='str',
373 required=True
374 ),
375 name=dict(
376 type='str',
377 required=True
378 ),
379 location=dict(
380 type='str'
381 ),
382 sku=dict(
383 type='dict',
384 required=True,
385 options=sku_spec
386 ),
387 enable_non_ssl_port=dict(
388 type='bool',
389 default=False
390 ),
391 maxfragmentationmemory_reserved=dict(
392 type='int'
393 ),
394 maxmemory_reserved=dict(
395 type='int'
396 ),
397 maxmemory_policy=dict(
398 type='str',
399 choices=[
400 "volatile_lru",
401 "allkeys_lru",
402 "volatile_random",
403 "allkeys_random",
404 "volatile_ttl",
405 "noeviction"
406 ]
407 ),
408 minimum_tls_version=dict(
409 type="str",
410 choices=["1.0", "1.1", "1.2"]
411 ),
412 notify_keyspace_events=dict(
413 type='str',
414 no_log=True
415 ),
416 public_network_access=dict(
417 type="str",
418 default="Enabled",
419 choices=["Enabled", "Disabled"]
420 ),
421 redis_version=dict(
422 type="str",
423 default="6",
424 choices=["4", "6"]
425 ),
426 shard_count=dict(
427 type='int'
428 ),
429 static_ip=dict(
430 type='str'
431 ),
432 subnet=dict(
433 type='raw'
434 ),
435 tenant_settings=dict(
436 type='dict'
437 ),
438 state=dict(
439 type='str',
440 default='present',
441 choices=['present', 'absent']
442 ),
443 reboot=dict(
444 type='dict',
445 options=reboot_spec
446 ),
447 regenerate_key=dict(
448 type='dict',
449 no_log=True,
450 options=regenerate_key_spec
451 ),
452 identity=dict(
453 type='dict',
454 options=self.managed_identity_multiple_spec
455 ),
456 wait_for_provisioning=dict(
457 type='bool',
458 default='True'
459 )
460 )
461
462 self._client = None
463
464 self.resource_group = None
465 self.name = None
466 self.location = None
467
468 self.sku = None
469 self.size = None
470 self.enable_non_ssl_port = False
471 self.configuration_file_path = None
472 self.minimum_tls_version = None
473 self.public_network_access = None
474 self.redis_version = None
475 self.shard_count = None
476 self.static_ip = None
477 self.subnet = None
478 self.tenant_settings = None
479 self.reboot = None
480 self.regenerate_key = None
481 self.identity = None
482 self._managed_identity = None
483 self.update_identity = False
484
485 self.wait_for_provisioning = None
486 self.wait_for_provisioning_polling_interval_in_seconds = 30
487 self.wait_for_provisioning_polling_times = 120
488
489 self.tags = None
490
491 self.results = dict(
492 changed=False,
493 id=None,
494 host_name=None
495 )
496 self.state = None
497 self.to_do = Actions.NoAction
498
499 super(AzureRMRedisCaches, self).__init__(derived_arg_spec=self.module_arg_spec,
500 supports_check_mode=True,
501 supports_tags=True)
502
503 @property
504 def managed_identity(self):
505 if not self._managed_identity:
506 self._managed_identity = {"identity": ManagedServiceIdentity,
507 "user_assigned": UserAssignedIdentity
508 }
509 return self._managed_identity
510
511 def exec_module(self, **kwargs):
512 """Main module execution method"""
513
514 for key in list(self.module_arg_spec.keys()) + ['tags']:
515 setattr(self, key, kwargs[key])
516
517 old_response = None
518 response = None
519 to_be_updated = False
520
521 # define redis_configuration properties
522 self.redis_configuration_properties = ["maxfragmentationmemory_reserved",
523 "maxmemory_reserved",
524 "maxmemory_policy",
525 "notify_keyspace_events"]
526
527 # get management client
528 self._client = self.get_mgmt_svc_client(RedisManagementClient,
529 base_url=self._cloud_environment.endpoints.resource_manager,
530 api_version='2024-03-01')
531
532 # set location
533 resource_group = self.get_resource_group(self.resource_group)
534 if not self.location:
535 self.location = resource_group.location
536
537 # check subnet exists
538 if self.subnet:
539 self.subnet = self.parse_subnet()
540
541 # get existing Azure Cache for Redis
542 old_response = self.get_rediscache()
543
544 if old_response:
545 self.results['id'] = old_response['id']
546
547 curr_identity = old_response.get('identity') if old_response else None
548
549 if self.identity:
550 self.update_identity, identity_result = self.update_managed_identity(curr_identity=curr_identity,
551 new_identity=self.identity)
552 self.identity = identity_result.as_dict()
553
554 if self.state == 'present':
555 # if redis not exists
556 if not old_response:
557 self.log("Azure Cache for Redis instance doesn't exist")
558
559 to_be_updated = True
560 self.to_do = Actions.Create
561
562 if not self.sku:
563 self.fail("Please specify sku to creating new Azure Cache for Redis.")
564
565 else:
566 # redis exists already, do update
567 self.log("Azure Cache for Redis instance already exists")
568
569 update_tags, self.tags = self.update_tags(old_response.get('tags', None))
570
571 if update_tags:
572 to_be_updated = True
573 self.to_do = Actions.Update
574
575 if self.update_identity:
576 to_be_updated = True
577 self.to_do = Actions.Update
578
579 # check if update
580 if self.check_update(old_response):
581 to_be_updated = True
582 self.to_do = Actions.Update
583
584 elif self.state == 'absent':
585 if old_response:
586 self.log("Delete Azure Cache for Redis instance")
587 self.results['id'] = old_response['id']
588 to_be_updated = True
589 self.to_do = Actions.Delete
590 else:
591 self.results['changed'] = False
592 self.log("Azure Cache for Redis {0} not exists.".format(self.name))
593
594 if to_be_updated:
595 self.log('Need to Create/Update Azure Cache for Redis')
596 self.results['changed'] = True
597
598 if self.check_mode:
599 return self.results
600
601 if self.to_do == Actions.Create:
602 response = self.create_rediscache()
603 self.results['id'] = response['id']
604 self.results['host_name'] = response['host_name']
605
606 if self.to_do == Actions.Update:
607 response = self.update_rediscache()
608 self.results['id'] = response['id']
609 self.results['host_name'] = response['host_name']
610
611 if self.to_do == Actions.Delete:
612 self.delete_rediscache()
613 self.log('Azure Cache for Redis instance deleted')
614
615 if self.reboot:
616 self.reboot['reboot_type'] = get_reboot_type(self.reboot['reboot_type'])
617 self.force_reboot_rediscache()
618 self.results['changed'] = True
619
620 if self.regenerate_key:
621 response = self.regenerate_rediscache_key()
622 self.results['changed'] = True
623 self.results['keys'] = response
624
625 return self.results
626
627 def check_update(self, existing):
628 if self.enable_non_ssl_port is not None and existing['enable_non_ssl_port'] != self.enable_non_ssl_port:
629 self.log("enable_non_ssl_port diff: origin {0} / update {1}".format(existing['enable_non_ssl_port'], self.enable_non_ssl_port))
630 return True
631 if self.sku is not None:
632 if existing['sku']['name'] != self.sku['name']:
633 self.log("sku diff: origin {0} / update {1}".format(existing['sku']['name'], self.sku['name']))
634 return True
635 if existing['sku']['size'] != self.sku['size']:
636 self.log("size diff: origin {0} / update {1}".format(existing['sku']['size'], self.sku['size']))
637 return True
638 if self.tenant_settings is not None and existing['tenant_settings'] != self.tenant_settings:
639 self.log("tenant_settings diff: origin {0} / update {1}".format(existing['tenant_settings'], self.tenant_settings))
640 return True
641 if self.shard_count is not None and existing['shard_count'] != self.shard_count:
642 self.log("shard_count diff: origin {0} / update {1}".format(existing['shard_count'], self.shard_count))
643 return True
644 if self.subnet is not None and existing['subnet'] != self.subnet:
645 self.log("subnet diff: origin {0} / update {1}".format(existing['subnet'], self.subnet))
646 return True
647 if self.static_ip is not None and existing['static_ip'] != self.static_ip:
648 self.log("static_ip diff: origin {0} / update {1}".format(existing['static_ip'], self.static_ip))
649 return True
650 if self.minimum_tls_version is not None and existing['minimum_tls_version'] != self.minimum_tls_version:
651 self.log("minimum_tls_version diff: origin {0} / update {1}".format(existing['minimum_tls_version'], self.minimum_tls_version))
652 return True
653 if self.public_network_access is not None and existing['public_network_access'] != self.public_network_access:
654 self.log("public_network_access diff: origin {0} / update {1}".format(existing['public_network_access'], self.public_network_access))
655 return True
656 if self.redis_version is not None and existing['redis_version'][0] != self.redis_version[0]:
657 self.log("redis_version diff: origin {0} / update {1}".format(existing['redis_version'], self.redis_version))
658 return True
659 for config in self.redis_configuration_properties:
660 if getattr(self, config) is not None and existing.get(config, None) != getattr(self, config, None):
661 self.log("redis_configuration {0} diff: origin {1} / update {2}".format(config, existing.get(config, None), getattr(self, config, None)))
662 return True
663 return False
664
665 def create_rediscache(self):
666 '''
667 Creates Azure Cache for Redis instance with the specified configuration.
668
669 :return: deserialized Azure Cache for Redis instance state dictionary
670 '''
671 self.log(
672 "Creating Azure Cache for Redis instance {0}".format(self.name))
673
674 try:
675 redis_config = dict()
676 for key in self.redis_configuration_properties:
677 if getattr(self, key, None):
678 redis_config[underline_to_hyphen(key)] = underline_to_hyphen(getattr(self, key))
679
680 params = RedisCreateParameters(
681 location=self.location,
682 sku=Sku(name=self.sku['name'].title(), family=self.sku['size'][0], capacity=self.sku['size'][1:]),
683 tags=self.tags,
684 redis_configuration=redis_config,
685 enable_non_ssl_port=self.enable_non_ssl_port,
686 tenant_settings=self.tenant_settings,
687 minimum_tls_version=self.minimum_tls_version,
688 public_network_access=self.public_network_access,
689 redis_version=self.redis_version,
690 shard_count=self.shard_count,
691 subnet_id=self.subnet,
692 static_ip=self.static_ip,
693 identity=self.identity
694 )
695
696 response = self._client.redis.begin_create(resource_group_name=self.resource_group,
697 name=self.name,
698 parameters=params)
699
700 if isinstance(response, LROPoller):
701 response = self.get_poller_result(response)
702
703 if self.wait_for_provisioning:
704 self.wait_for_redis_running()
705 except Exception as exc:
706 self.log('Error attempting to create the Azure Cache for Redis instance.')
707 self.fail(
708 "Error creating the Azure Cache for Redis instance: {0}".format(str(exc)))
709 return rediscache_to_dict(response)
710
711 def update_rediscache(self):
712 '''
713 Updates Azure Cache for Redis instance with the specified configuration.
714
715 :return: Azure Cache for Redis instance state dictionary
716 '''
717 self.log(
718 "Updating Azure Cache for Redis instance {0}".format(self.name))
719
720 try:
721 redis_config = dict()
722 for key in self.redis_configuration_properties:
723 if getattr(self, key, None):
724 redis_config[underline_to_hyphen(key)] = underline_to_hyphen(getattr(self, key))
725
726 params = RedisUpdateParameters(
727 redis_configuration=redis_config,
728 enable_non_ssl_port=self.enable_non_ssl_port,
729 tenant_settings=self.tenant_settings,
730 minimum_tls_version=self.minimum_tls_version,
731 public_network_access=self.public_network_access,
732 redis_version=self.redis_version,
733 shard_count=self.shard_count,
734 sku=Sku(name=self.sku['name'].title(), family=self.sku['size'][0], capacity=self.sku['size'][1:]),
735 tags=self.tags,
736 identity=self.identity
737 )
738
739 response = self._client.redis.begin_update(resource_group_name=self.resource_group,
740 name=self.name,
741 parameters=params)
742 if isinstance(response, LROPoller):
743 response = self.get_poller_result(response)
744
745 if self.wait_for_provisioning:
746 self.wait_for_redis_running()
747
748 except Exception as exc:
749 self.log('Error attempting to update the Azure Cache for Redis instance.')
750 self.fail(
751 "Error updating the Azure Cache for Redis instance: {0}".format(str(exc)))
752 return rediscache_to_dict(response)
753
754 def delete_rediscache(self):
755 '''
756 Deletes specified Azure Cache for Redis instance in the specified subscription and resource group.
757
758 :return: True
759 '''
760 self.log("Deleting the Azure Cache for Redis instance {0}".format(self.name))
761 try:
762 self._client.redis.begin_delete(resource_group_name=self.resource_group,
763 name=self.name)
764 except Exception as e:
765 self.log('Error attempting to delete the Azure Cache for Redis instance.')
766 self.fail(
767 "Error deleting the Azure Cache for Redis instance: {0}".format(str(e)))
768 return True
769
770 def get_rediscache(self):
771 '''
772 Gets the properties of the specified Azure Cache for Redis instance.
773
774 :return: Azure Cache for Redis instance state dictionary
775 '''
776 self.log("Checking if the Azure Cache for Redis instance {0} is present".format(self.name))
777
778 response = None
779
780 try:
781 response = self._client.redis.get(resource_group_name=self.resource_group,
782 name=self.name)
783
784 self.log("Response : {0}".format(response))
785 self.log("Azure Cache for Redis instance : {0} found".format(response.name))
786 return rediscache_to_dict(response)
787 except ResourceNotFoundError:
788 self.log("Didn't find Azure Cache for Redis {0} in resource group {1}".format(
789 self.name, self.resource_group))
790
791 return False
792
793 def force_reboot_rediscache(self):
794 '''
795 Force reboot specified redis cache instance in the specified subscription and resource group.
796
797 :return: True
798 '''
799 self.log("Force reboot the redis cache instance {0}".format(self.name))
800 try:
801 params = RedisRebootParameters(
802 reboot_type=self.reboot['reboot_type'],
803 shard_id=self.reboot.get('shard_id'),
804 )
805 response = self._client.redis.force_reboot(resource_group_name=self.resource_group,
806 name=self.name,
807 parameters=params)
808 if isinstance(response, LROPoller):
809 response = self.get_poller_result(response)
810
811 if self.wait_for_provisioning:
812 self.wait_for_redis_running()
813 except Exception as e:
814 self.log('Error attempting to force reboot the redis cache instance.')
815 self.fail(
816 "Error force rebooting the redis cache instance: {0}".format(str(e)))
817 return True
818
819 def regenerate_rediscache_key(self):
820 '''
821 Regenerate key of redis cache instance in the specified subscription and resource group.
822
823 :return: True
824 '''
825 self.log("Regenerate key of redis cache instance {0}".format(self.name))
826 try:
827 params = RedisRegenerateKeyParameters(
828 key_type=self.regenerate_key['key_type'].title(),
829 )
830 response = self._client.redis.regenerate_key(resource_group_name=self.resource_group,
831 name=self.name,
832 parameters=params)
833 return response.as_dict()
834 except Exception as e:
835 self.log('Error attempting to regenerate key of redis cache instance.')
836 self.fail(
837 "Error regenerate key of redis cache instance: {0}".format(str(e)))
838
839 def get_subnet(self):
840 '''
841 Gets the properties of the specified subnet.
842
843 :return: subnet id
844 '''
845 self.log("Checking if the subnet {0} is present".format(self.name))
846
847 response = None
848
849 try:
850 response = self.network_client.subnets.get(self.subnet['resource_group'],
851 self.subnet['virtual_network_name'],
852 self.subnet['name'])
853
854 self.log("Subnet found : {0}".format(response))
855 return response.id
856
857 except ResourceNotFoundError as ex:
858 self.log("Didn't find subnet {0} in resource group {1}".format(
859 self.subnet['name'], self.subnet['resource_group']))
860
861 return False
862
863 def parse_subnet(self):
864 if isinstance(self.subnet, dict):
865 if 'virtual_network_name' not in self.subnet or \
866 'name' not in self.subnet:
867 self.fail("Subnet dict must contains virtual_network_name and name")
868 if 'resource_group' not in self.subnet:
869 self.subnet['resource_group'] = self.resource_group
870 subnet_id = self.get_subnet()
871 else:
872 subnet_id = self.subnet
873 return subnet_id
874
875 def wait_for_redis_running(self):
876 try:
877 response = self._client.redis.get(resource_group_name=self.resource_group, name=self.name)
878 status = response.provisioning_state
879 polling_times = 0
880
881 while polling_times < self.wait_for_provisioning_polling_times:
882 if status.lower() != "succeeded":
883 polling_times += 1
884 time.sleep(self.wait_for_provisioning_polling_interval_in_seconds)
885 response = self._client.redis.get(resource_group_name=self.resource_group, name=self.name)
886 status = response.provisioning_state
887 else:
888 return True
889 self.fail("Azure Cache for Redis is not running after 60 mins.")
890 except Exception as e:
891 self.fail("Failed to get Azure Cache for Redis: {0}".format(str(e)))
892
893
894 def main():
895 """Main execution"""
896 AzureRMRedisCaches()
897
898
899 if __name__ == '__main__':
900 main()