Debian Codegraph @

ansible_collections/azure/azcollection/plugins/modules/azure_rm_webappslot.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_webappslot
14 version_added: "0.1.2"
15 short_description: Manage Azure Web App slot
16 description:
17 - Create, update and delete Azure Web App slot.
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 deployment slot to create or update.
28 required: True
29 type: str
30 webapp_name:
31 description:
32 - Web app name which this deployment slot belongs to.
33 required: True
34 type: str
35 location:
36 description:
37 - Resource location. If not set, location from the resource group will be used as default.
38 type: str
39 configuration_source:
40 description:
41 - Source slot to clone configurations from when creating slot. Use webapp's name to refer to the production slot.
42 type: str
43 auto_swap_slot_name:
44 description:
45 - Used to configure target slot name to auto swap, or disable auto swap.
46 - Set it target slot name to auto swap.
47 - Set it to False to disable auto slot swap.
48 type: raw
49 swap:
50 description:
51 - Swap deployment slots of a web app.
52 type: dict
53 suboptions:
54 action:
55 description:
56 - Swap types.
57 - C(preview) is to apply target slot settings on source slot first.
58 - C(swap) is to complete swapping.
59 - C(reset) is to reset the swap.
60 type: str
61 choices:
62 - preview
63 - swap
64 - reset
65 default: preview
66 target_slot:
67 description:
68 - Name of target slot to swap. If set to None, then swap with production slot.
69 type: str
70 preserve_vnet:
71 description:
72 - C(True) to preserve virtual network to the slot during swap. Otherwise C(False).
73 type: bool
74 default: True
75 frameworks:
76 description:
77 - Set of run time framework settings. Each setting is a dictionary.
78 - See U(https://docs.microsoft.com/en-us/azure/app-service/app-service-web-overview) for more info.
79 type: list
80 elements: dict
81 suboptions:
82 name:
83 description:
84 - Name of the framework.
85 - Supported framework list for Windows web app and Linux web app is different.
86 - Windows web apps support C(java), C(net_framework), C(php), C(python), and C(node) from June 2018.
87 - Windows web apps support multiple framework at same time.
88 - Linux web apps support C(java), C(ruby), C(php), C(dotnetcore), and C(node) from June 2018.
89 - Linux web apps support only one framework.
90 - Java framework is mutually exclusive with others.
91 type: str
92 required: true
93 choices:
94 - java
95 - net_framework
96 - php
97 - python
98 - ruby
99 - dotnetcore
100 - node
101 version:
102 description:
103 - Version of the framework. For Linux web app supported value, see U(https://aka.ms/linux-stacks) for more info.
104 - C(net_framework) supported value sample, C(v4.0) for .NET 4.6 and C(v3.0) for .NET 3.5.
105 - C(php) supported value sample, C(5.5), C(5.6), C(7.0).
106 - C(python) supported value sample, C(5.5), C(5.6), C(7.0).
107 - C(node) supported value sample, C(6.6), C(6.9).
108 - C(dotnetcore) supported value sample, C(1.0), C(1.1), C(1.2).
109 - C(ruby) supported value sample, 2.3.
110 - C(java) supported value sample, C(1.9) for Windows web app. C(1.8) for Linux web app.
111 type: str
112 required: true
113 settings:
114 description:
115 - List of settings of the framework.
116 type: dict
117 suboptions:
118 java_container:
119 description:
120 - Name of Java container. This is supported by specific framework C(java) onlys, for example C(Tomcat), C(Jetty).
121 type: str
122 required: true
123 java_container_version:
124 description:
125 - Version of Java container. This is supported by specific framework C(java) only.
126 - For C(Tomcat), for example C(8.0), C(8.5), C(9.0). For C(Jetty), for example C(9.1), C(9.3).
127 type: str
128 required: true
129 container_settings:
130 description:
131 - Web app slot container settings.
132 type: dict
133 suboptions:
134 name:
135 description:
136 - Name of container, for example C(imagename:tag).
137 type: str
138 required: true
139 registry_server_url:
140 description:
141 - Container registry server URL, for example C(mydockerregistry.io).
142 type: str
143 registry_server_user:
144 description:
145 - The container registry server user name.
146 type: str
147 registry_server_password:
148 description:
149 - The container registry server password.
150 type: str
151 startup_file:
152 description:
153 - The slot startup file.
154 - This only applies for Linux web app slot.
155 type: str
156 app_settings:
157 description:
158 - Configure web app slot application settings. Suboptions are in key value pair format.
159 type: dict
160 purge_app_settings:
161 description:
162 - Purge any existing application settings. Replace slot application settings with app_settings.
163 type: bool
164 default: False
165 deployment_source:
166 description:
167 - Deployment source for git.
168 type: dict
169 suboptions:
170 url:
171 description:
172 - Repository URL of deployment source.
173 type: str
174 branch:
175 description:
176 - The branch name of the repository.
177 type: str
178 app_state:
179 description:
180 - Start/Stop/Restart the slot.
181 type: str
182 choices:
183 - started
184 - stopped
185 - restarted
186 default: started
187 state:
188 description:
189 - State of the Web App deployment slot.
190 - Use C(present) to create or update a slot 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
201 author:
202 - Yunge Zhu(@yungezz)
203
204 '''
205
206 EXAMPLES = '''
207 - name: Create a webapp slot
208 azure_rm_webappslot:
209 resource_group: myResourceGroup
210 webapp_name: myJavaWebApp
211 name: stage
212 configuration_source: myJavaWebApp
213 app_settings:
214 testkey: testvalue
215
216 - name: swap the slot with production slot
217 azure_rm_webappslot:
218 resource_group: myResourceGroup
219 webapp_name: myJavaWebApp
220 name: stage
221 swap:
222 action: swap
223
224 - name: stop the slot
225 azure_rm_webappslot:
226 resource_group: myResourceGroup
227 webapp_name: myJavaWebApp
228 name: stage
229 app_state: stopped
230
231 - name: udpate a webapp slot app settings
232 azure_rm_webappslot:
233 resource_group: myResourceGroup
234 webapp_name: myJavaWebApp
235 name: stage
236 app_settings:
237 testkey: testvalue2
238
239 - name: udpate a webapp slot frameworks
240 azure_rm_webappslot:
241 resource_group: myResourceGroup
242 webapp_name: myJavaWebApp
243 name: stage
244 frameworks:
245 - name: "node"
246 version: "10.1"
247 '''
248
249 RETURN = '''
250 id:
251 description:
252 - ID of current slot.
253 returned: always
254 type: str
255 sample: /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.Web/sites/testapp/slots/stage1
256 '''
257
258 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common import AzureRMModuleBase
259
260 try:
261 from azure.core.exceptions import ResourceNotFoundError
262 from azure.core.polling import LROPoller
263 from azure.mgmt.web.models import Site, NameValuePair, SiteSourceControl, CsmSlotEntity, StringDictionary
264 except ImportError:
265 # This is handled in azure_rm_common
266 pass
267
268 swap_spec = dict(
269 action=dict(
270 type='str',
271 choices=[
272 'preview',
273 'swap',
274 'reset'
275 ],
276 default='preview'
277 ),
278 target_slot=dict(
279 type='str'
280 ),
281 preserve_vnet=dict(
282 type='bool',
283 default=True
284 )
285 )
286
287 container_settings_spec = dict(
288 name=dict(type='str', required=True),
289 registry_server_url=dict(type='str'),
290 registry_server_user=dict(type='str'),
291 registry_server_password=dict(type='str', no_log=True)
292 )
293
294 deployment_source_spec = dict(
295 url=dict(type='str'),
296 branch=dict(type='str')
297 )
298
299
300 framework_settings_spec = dict(
301 java_container=dict(type='str', required=True),
302 java_container_version=dict(type='str', required=True)
303 )
304
305
306 framework_spec = dict(
307 name=dict(
308 type='str',
309 required=True,
310 choices=['net_framework', 'java', 'php', 'node', 'python', 'dotnetcore', 'ruby']),
311 version=dict(type='str', required=True),
312 settings=dict(type='dict', options=framework_settings_spec)
313 )
314
315
316 def webapp_to_dict(webapp):
317 return dict(
318 id=webapp.id,
319 name=webapp.name,
320 location=webapp.location,
321 client_cert_enabled=webapp.client_cert_enabled,
322 enabled=webapp.enabled,
323 reserved=webapp.reserved,
324 client_affinity_enabled=webapp.client_affinity_enabled,
325 server_farm_id=webapp.server_farm_id,
326 host_names_disabled=webapp.host_names_disabled,
327 https_only=webapp.https_only if hasattr(webapp, 'https_only') else None,
328 skip_custom_domain_verification=webapp.skip_custom_domain_verification if hasattr(webapp, 'skip_custom_domain_verification') else None,
329 ttl_in_seconds=webapp.ttl_in_seconds if hasattr(webapp, 'ttl_in_seconds') else None,
330 state=webapp.state,
331 tags=webapp.tags if webapp.tags else None
332 )
333
334
335 def slot_to_dict(slot):
336 return dict(
337 id=slot.id,
338 resource_group=slot.resource_group,
339 server_farm_id=slot.server_farm_id,
340 target_swap_slot=slot.target_swap_slot,
341 enabled_host_names=slot.enabled_host_names,
342 slot_swap_status=slot.slot_swap_status,
343 name=slot.name,
344 location=slot.location,
345 enabled=slot.enabled,
346 reserved=slot.reserved,
347 host_names_disabled=slot.host_names_disabled,
348 state=slot.state,
349 repository_site_name=slot.repository_site_name,
350 default_host_name=slot.default_host_name,
351 kind=slot.kind,
352 site_config=slot.site_config,
353 tags=slot.tags if slot.tags else None
354 )
355
356
357 class Actions:
358 NoAction, CreateOrUpdate, UpdateAppSettings, Delete = range(4)
359
360
361 class AzureRMWebAppSlots(AzureRMModuleBase):
362 """Configuration class for an Azure RM Web App slot resource"""
363
364 def __init__(self):
365 self.module_arg_spec = dict(
366 resource_group=dict(
367 type='str',
368 required=True
369 ),
370 name=dict(
371 type='str',
372 required=True
373 ),
374 webapp_name=dict(
375 type='str',
376 required=True
377 ),
378 location=dict(
379 type='str'
380 ),
381 configuration_source=dict(
382 type='str'
383 ),
384 auto_swap_slot_name=dict(
385 type='raw'
386 ),
387 swap=dict(
388 type='dict',
389 options=swap_spec
390 ),
391 frameworks=dict(
392 type='list',
393 elements='dict',
394 options=framework_spec
395 ),
396 container_settings=dict(
397 type='dict',
398 options=container_settings_spec
399 ),
400 deployment_source=dict(
401 type='dict',
402 options=deployment_source_spec
403 ),
404 startup_file=dict(
405 type='str'
406 ),
407 app_settings=dict(
408 type='dict'
409 ),
410 purge_app_settings=dict(
411 type='bool',
412 default=False
413 ),
414 app_state=dict(
415 type='str',
416 choices=['started', 'stopped', 'restarted'],
417 default='started'
418 ),
419 state=dict(
420 type='str',
421 default='present',
422 choices=['present', 'absent']
423 )
424 )
425
426 mutually_exclusive = [['container_settings', 'frameworks']]
427
428 self.resource_group = None
429 self.name = None
430 self.webapp_name = None
431 self.location = None
432
433 self.auto_swap_slot_name = None
434 self.swap = None
435 self.tags = None
436 self.startup_file = None
437 self.configuration_source = None
438 self.clone = False
439
440 # site config, e.g app settings, ssl
441 self.site_config = dict()
442 self.app_settings = dict()
443 self.app_settings_strDic = None
444
445 # siteSourceControl
446 self.deployment_source = dict()
447
448 # site, used at level creation, or update.
449 self.site = None
450
451 # property for internal usage, not used for sdk
452 self.container_settings = None
453
454 self.purge_app_settings = False
455 self.app_state = 'started'
456
457 self.results = dict(
458 changed=False,
459 id=None,
460 )
461 self.state = None
462 self.to_do = Actions.NoAction
463
464 self.frameworks = None
465
466 # set site_config value from kwargs
467 self.site_config_updatable_frameworks = ["net_framework_version",
468 "java_version",
469 "php_version",
470 "python_version",
471 "linux_fx_version"]
472
473 self.supported_linux_frameworks = ['ruby', 'php', 'dotnetcore', 'node', 'java']
474 self.supported_windows_frameworks = ['net_framework', 'php', 'python', 'node', 'java']
475
476 super(AzureRMWebAppSlots, self).__init__(derived_arg_spec=self.module_arg_spec,
477 mutually_exclusive=mutually_exclusive,
478 supports_check_mode=True,
479 supports_tags=True)
480
481 def exec_module(self, **kwargs):
482 """Main module execution method"""
483
484 for key in list(self.module_arg_spec.keys()) + ['tags']:
485 if hasattr(self, key):
486 setattr(self, key, kwargs[key])
487 elif kwargs[key] is not None:
488 if key == "scm_type":
489 self.site_config[key] = kwargs[key]
490
491 old_response = None
492 response = None
493 to_be_updated = False
494
495 # set location
496 resource_group = self.get_resource_group(self.resource_group)
497 if not self.location:
498 self.location = resource_group.location
499
500 # get web app
501 webapp_response = self.get_webapp()
502
503 if not webapp_response:
504 self.fail("Web app {0} does not exist in resource group {1}.".format(self.webapp_name, self.resource_group))
505
506 # get slot
507 old_response = self.get_slot()
508
509 # set is_linux
510 is_linux = True if webapp_response['reserved'] else False
511
512 if self.state == 'present':
513 if self.frameworks:
514 # java is mutually exclusive with other frameworks
515 if len(self.frameworks) > 1 and any(f['name'] == 'java' for f in self.frameworks):
516 self.fail('Java is mutually exclusive with other frameworks.')
517
518 if is_linux:
519 if len(self.frameworks) != 1:
520 self.fail('Can specify one framework only for Linux web app.')
521
522 if self.frameworks[0]['name'] not in self.supported_linux_frameworks:
523 self.fail('Unsupported framework {0} for Linux web app.'.format(self.frameworks[0]['name']))
524
525 self.site_config['linux_fx_version'] = (self.frameworks[0]['name'] + '|' + self.frameworks[0]['version']).upper()
526
527 if self.frameworks[0]['name'] == 'java':
528 if self.frameworks[0]['version'] != '8':
529 self.fail("Linux web app only supports java 8.")
530
531 if self.frameworks[0].get('settings', {}) and self.frameworks[0]['settings'].get('java_container', None) and \
532 self.frameworks[0]['settings']['java_container'].lower() != 'tomcat':
533 self.fail("Linux web app only supports tomcat container.")
534
535 if self.frameworks[0].get('settings', {}) and self.frameworks[0]['settings'].get('java_container', None) and \
536 self.frameworks[0]['settings']['java_container'].lower() == 'tomcat':
537 self.site_config['linux_fx_version'] = 'TOMCAT|' + self.frameworks[0]['settings']['java_container_version'] + '-jre8'
538 else:
539 self.site_config['linux_fx_version'] = 'JAVA|8-jre8'
540 else:
541 for fx in self.frameworks:
542 if fx.get('name') not in self.supported_windows_frameworks:
543 self.fail('Unsupported framework {0} for Windows web app.'.format(fx.get('name')))
544 else:
545 self.site_config[fx.get('name') + '_version'] = fx.get('version')
546
547 if 'settings' in fx and fx['settings'] is not None:
548 for key, value in fx['settings'].items():
549 self.site_config[key] = value
550
551 if not self.app_settings:
552 self.app_settings = dict()
553
554 if self.container_settings:
555 linux_fx_version = 'DOCKER|'
556
557 if self.container_settings.get('registry_server_url'):
558 self.app_settings['DOCKER_REGISTRY_SERVER_URL'] = 'https://' + self.container_settings['registry_server_url']
559
560 linux_fx_version += self.container_settings['registry_server_url'] + '/'
561
562 linux_fx_version += self.container_settings['name']
563
564 self.site_config['linux_fx_version'] = linux_fx_version
565
566 if self.container_settings.get('registry_server_user'):
567 self.app_settings['DOCKER_REGISTRY_SERVER_USERNAME'] = self.container_settings['registry_server_user']
568
569 if self.container_settings.get('registry_server_password'):
570 self.app_settings['DOCKER_REGISTRY_SERVER_PASSWORD'] = self.container_settings['registry_server_password']
571
572 # set auto_swap_slot_name
573 if self.auto_swap_slot_name and isinstance(self.auto_swap_slot_name, str):
574 self.site_config['auto_swap_slot_name'] = self.auto_swap_slot_name
575 if self.auto_swap_slot_name is False:
576 self.site_config['auto_swap_slot_name'] = None
577
578 # init site
579 self.site = Site(location=self.location, site_config=self.site_config)
580
581 # check if the slot already present in the webapp
582 if not old_response:
583 self.log("Web App slot doesn't exist")
584
585 to_be_updated = True
586 self.to_do = Actions.CreateOrUpdate
587 self.site.tags = self.tags
588
589 # if linux, setup startup_file
590 if self.startup_file:
591 self.site_config['app_command_line'] = self.startup_file
592
593 # set app setting
594 if self.app_settings:
595 app_settings = []
596 for key in self.app_settings.keys():
597 app_settings.append(NameValuePair(name=key, value=self.app_settings[key]))
598
599 self.site_config['app_settings'] = app_settings
600
601 # clone slot
602 if self.configuration_source:
603 self.clone = True
604
605 else:
606 # existing slot, do update
607 self.log("Web App slot already exists")
608
609 self.log('Result: {0}'.format(old_response))
610
611 update_tags, self.site.tags = self.update_tags(old_response.get('tags', None))
612
613 if update_tags:
614 to_be_updated = True
615
616 # check if site_config changed
617 old_config = self.get_configuration_slot(self.name)
618
619 if self.is_site_config_changed(old_config):
620 to_be_updated = True
621 self.to_do = Actions.CreateOrUpdate
622
623 self.app_settings_strDic = self.list_app_settings_slot(self.name)
624
625 # purge existing app_settings:
626 if self.purge_app_settings:
627 to_be_updated = True
628 self.to_do = Actions.UpdateAppSettings
629 self.app_settings_strDic = dict()
630
631 # check if app settings changed
632 if self.purge_app_settings or self.is_app_settings_changed():
633 to_be_updated = True
634 self.to_do = Actions.UpdateAppSettings
635
636 if self.app_settings:
637 for key in self.app_settings.keys():
638 self.app_settings_strDic[key] = self.app_settings[key]
639
640 elif self.state == 'absent':
641 if old_response:
642 self.log("Delete Web App slot")
643 self.results['changed'] = True
644
645 if self.check_mode:
646 return self.results
647
648 self.delete_slot()
649
650 self.log('Web App slot deleted')
651
652 else:
653 self.log("Web app slot {0} not exists.".format(self.name))
654
655 if to_be_updated:
656 self.log('Need to Create/Update web app')
657 self.results['changed'] = True
658
659 if self.check_mode:
660 return self.results
661
662 if self.to_do == Actions.CreateOrUpdate:
663 response = self.create_update_slot()
664
665 self.results['id'] = response['id']
666
667 if self.clone:
668 self.clone_slot()
669
670 if self.to_do == Actions.UpdateAppSettings:
671 self.update_app_settings_slot()
672
673 slot = None
674 if response:
675 slot = response
676 if old_response:
677 slot = old_response
678
679 if slot:
680 if (slot['state'] != 'Stopped' and self.app_state == 'stopped') or \
681 (slot['state'] != 'Running' and self.app_state == 'started') or \
682 self.app_state == 'restarted':
683
684 self.results['changed'] = True
685 if self.check_mode:
686 return self.results
687
688 self.set_state_slot(self.app_state)
689
690 if self.swap:
691 self.results['changed'] = True
692 if self.check_mode:
693 return self.results
694
695 self.swap_slot()
696
697 return self.results
698
699 # compare site config
700 def is_site_config_changed(self, existing_config):
701 for fx_version in self.site_config_updatable_frameworks:
702 if self.site_config.get(fx_version):
703 if not getattr(existing_config, fx_version) or \
704 getattr(existing_config, fx_version).upper() != self.site_config.get(fx_version).upper():
705 return True
706
707 if self.auto_swap_slot_name is False and existing_config.auto_swap_slot_name is not None:
708 return True
709 elif self.auto_swap_slot_name and self.auto_swap_slot_name != getattr(existing_config, 'auto_swap_slot_name', None):
710 return True
711 return False
712
713 # comparing existing app setting with input, determine whether it's changed
714 def is_app_settings_changed(self):
715 if self.app_settings:
716 if len(self.app_settings_strDic) != len(self.app_settings):
717 return True
718
719 if self.app_settings_strDic != self.app_settings:
720 return True
721 return False
722
723 # comparing deployment source with input, determine whether it's changed
724 def is_deployment_source_changed(self, existing_webapp):
725 if self.deployment_source:
726 if self.deployment_source.get('url') \
727 and self.deployment_source['url'] != existing_webapp.get('site_source_control')['url']:
728 return True
729
730 if self.deployment_source.get('branch') \
731 and self.deployment_source['branch'] != existing_webapp.get('site_source_control')['branch']:
732 return True
733
734 return False
735
736 def create_update_slot(self):
737 '''
738 Creates or updates Web App slot with the specified configuration.
739
740 :return: deserialized Web App instance state dictionary
741 '''
742 self.log(
743 "Creating / Updating the Web App slot {0}".format(self.name))
744
745 try:
746 response = self.web_client.web_apps.begin_create_or_update_slot(resource_group_name=self.resource_group,
747 slot=self.name,
748 name=self.webapp_name,
749 site_envelope=self.site)
750 if isinstance(response, LROPoller):
751 response = self.get_poller_result(response)
752
753 except Exception as exc:
754 self.log('Error attempting to create the Web App slot instance.')
755 self.fail("Error creating the Web App slot: {0}".format(str(exc)))
756 return slot_to_dict(response)
757
758 def delete_slot(self):
759 '''
760 Deletes specified Web App slot in the specified subscription and resource group.
761
762 :return: True
763 '''
764 self.log("Deleting the Web App slot {0}".format(self.name))
765 try:
766 self.web_client.web_apps.delete_slot(resource_group_name=self.resource_group,
767 name=self.webapp_name,
768 slot=self.name)
769 except Exception as e:
770 self.log('Error attempting to delete the Web App slot.')
771 self.fail(
772 "Error deleting the Web App slots: {0}".format(str(e)))
773
774 return True
775
776 def get_webapp(self):
777 '''
778 Gets the properties of the specified Web App.
779
780 :return: deserialized Web App instance state dictionary
781 '''
782 self.log(
783 "Checking if the Web App instance {0} is present".format(self.webapp_name))
784
785 response = None
786
787 try:
788 response = self.web_client.web_apps.get(resource_group_name=self.resource_group,
789 name=self.webapp_name)
790
791 # Newer SDK versions (0.40.0+) seem to return None if it doesn't exist instead of raising error
792 if response is not None:
793 self.log("Response : {0}".format(response))
794 self.log("Web App instance : {0} found".format(response.name))
795 return webapp_to_dict(response)
796
797 except ResourceNotFoundError:
798 pass
799
800 self.log("Didn't find web app {0} in resource group {1}".format(
801 self.webapp_name, self.resource_group))
802
803 return False
804
805 def get_slot(self):
806 '''
807 Gets the properties of the specified Web App slot.
808
809 :return: deserialized Web App slot state dictionary
810 '''
811 self.log(
812 "Checking if the Web App slot {0} is present".format(self.name))
813
814 response = None
815
816 try:
817 response = self.web_client.web_apps.get_slot(resource_group_name=self.resource_group,
818 name=self.webapp_name,
819 slot=self.name)
820
821 # Newer SDK versions (0.40.0+) seem to return None if it doesn't exist instead of raising error
822 if response is not None:
823 self.log("Response : {0}".format(response))
824 self.log("Web App slot: {0} found".format(response.name))
825 return slot_to_dict(response)
826
827 except ResourceNotFoundError:
828 pass
829
830 self.log("Does not find web app slot {0} in resource group {1}".format(self.name, self.resource_group))
831
832 return False
833
834 def list_app_settings(self):
835 '''
836 List webapp application settings
837 :return: deserialized list response
838 '''
839 self.log("List webapp application setting")
840
841 try:
842 response = self.web_client.web_apps.list_application_settings(
843 resource_group_name=self.resource_group, name=self.webapp_name)
844 self.log("Response : {0}".format(response))
845
846 return response.properties
847 except Exception as ex:
848 self.fail("Failed to list application settings for web app {0} in resource group {1}: {2}".format(
849 self.name, self.resource_group, str(ex)))
850
851 def list_app_settings_slot(self, slot_name):
852 '''
853 List application settings
854 :return: deserialized list response
855 '''
856 self.log("List application setting")
857
858 try:
859 response = self.web_client.web_apps.list_application_settings_slot(
860 resource_group_name=self.resource_group, name=self.webapp_name, slot=slot_name)
861 self.log("Response : {0}".format(response))
862
863 return response.properties
864 except Exception as ex:
865 self.fail("Failed to list application settings for web app slot {0} in resource group {1}: {2}".format(
866 self.name, self.resource_group, str(ex)))
867
868 def update_app_settings_slot(self, slot_name=None, app_settings=None):
869 '''
870 Update application settings
871 :return: deserialized updating response
872 '''
873 self.log("Update application setting")
874
875 if slot_name is None:
876 slot_name = self.name
877 if app_settings is None:
878 app_settings = self.app_settings_strDic
879 try:
880 settings = StringDictionary(
881 properties=self.app_settings
882 )
883 response = self.web_client.web_apps.update_application_settings_slot(resource_group_name=self.resource_group,
884 name=self.webapp_name,
885 slot=slot_name,
886 app_settings=settings)
887 self.log("Response : {0}".format(response))
888
889 return response.as_dict()
890 except Exception as ex:
891 self.fail("Failed to update application settings for web app slot {0} in resource group {1}: {2}".format(
892 self.name, self.resource_group, str(ex)))
893
894 return response
895
896 def create_or_update_source_control_slot(self):
897 '''
898 Update site source control
899 :return: deserialized updating response
900 '''
901 self.log("Update site source control")
902
903 if self.deployment_source is None:
904 return False
905
906 self.deployment_source['is_manual_integration'] = False
907 self.deployment_source['is_mercurial'] = False
908
909 try:
910 site_source_control = SiteSourceControl(
911 repo_url=self.deployment_source.get('url'),
912 branch=self.deployment_source.get('branch')
913 )
914 response = self.web_client.web_client.begin_create_or_update_source_control_slot(
915 resource_group_name=self.resource_group,
916 name=self.webapp_name,
917 site_source_control=site_source_control,
918 slot=self.name)
919 self.log("Response : {0}".format(response))
920
921 return response.as_dict()
922 except Exception as ex:
923 self.fail("Failed to update site source control for web app slot {0} in resource group {1}: {2}".format(
924 self.name, self.resource_group, str(ex)))
925
926 def get_configuration(self):
927 '''
928 Get web app configuration
929 :return: deserialized web app configuration response
930 '''
931 self.log("Get web app configuration")
932
933 try:
934 response = self.web_client.web_apps.get_configuration(
935 resource_group_name=self.resource_group, name=self.webapp_name)
936 self.log("Response : {0}".format(response))
937
938 return response
939 except Exception as ex:
940 self.fail("Failed to get configuration for web app {0} in resource group {1}: {2}".format(
941 self.webapp_name, self.resource_group, str(ex)))
942
943 def get_configuration_slot(self, slot_name):
944 '''
945 Get slot configuration
946 :return: deserialized slot configuration response
947 '''
948 self.log("Get web app slot configuration")
949
950 try:
951 response = self.web_client.web_apps.get_configuration_slot(
952 resource_group_name=self.resource_group, name=self.webapp_name, slot=slot_name)
953 self.log("Response : {0}".format(response))
954
955 return response
956 except Exception as ex:
957 self.fail("Failed to get configuration for web app slot {0} in resource group {1}: {2}".format(
958 slot_name, self.resource_group, str(ex)))
959
960 def update_configuration_slot(self, slot_name=None, site_config=None):
961 '''
962 Update slot configuration
963 :return: deserialized slot configuration response
964 '''
965 self.log("Update web app slot configuration")
966
967 if slot_name is None:
968 slot_name = self.name
969 if site_config is None:
970 site_config = self.site_config
971 try:
972 response = self.web_client.web_apps.update_configuration_slot(
973 resource_group_name=self.resource_group, name=self.webapp_name, slot=slot_name, site_config=site_config)
974 self.log("Response : {0}".format(response))
975
976 return response
977 except Exception as ex:
978 self.fail("Failed to update configuration for web app slot {0} in resource group {1}: {2}".format(
979 slot_name, self.resource_group, str(ex)))
980
981 def set_state_slot(self, appstate):
982 '''
983 Start/stop/restart web app slot
984 :return: deserialized updating response
985 '''
986 try:
987 if appstate == 'started':
988 response = self.web_client.web_apps.start_slot(resource_group_name=self.resource_group, name=self.webapp_name, slot=self.name)
989 elif appstate == 'stopped':
990 response = self.web_client.web_apps.stop_slot(resource_group_name=self.resource_group, name=self.webapp_name, slot=self.name)
991 elif appstate == 'restarted':
992 response = self.web_client.web_apps.restart_slot(resource_group_name=self.resource_group, name=self.webapp_name, slot=self.name)
993 else:
994 self.fail("Invalid web app slot state {0}".format(appstate))
995
996 self.log("Response : {0}".format(response))
997
998 return response
999 except Exception as ex:
1000 request_id = ex.request_id if ex.request_id else ''
1001 self.fail("Failed to {0} web app slot {1} in resource group {2}, request_id {3} - {4}".format(
1002 appstate, self.name, self.resource_group, request_id, str(ex)))
1003
1004 def swap_slot(self):
1005 '''
1006 Swap slot
1007 :return: deserialized response
1008 '''
1009 self.log("Swap slot")
1010
1011 try:
1012 if self.swap['action'] == 'swap':
1013 if self.swap['target_slot'] is None:
1014 slot_swap_entity = CsmSlotEntity(
1015 target_slot=self.name,
1016 preserve_vnet=self.swap['preserve_vnet']
1017 )
1018 response = self.web_client.web_apps.begin_swap_slot_with_production(resource_group_name=self.resource_group,
1019 name=self.webapp_name,
1020 slot_swap_entity=slot_swap_entity)
1021 else:
1022 slot_swap_entity = CsmSlotEntity(
1023 target_slot=self.swap['target_slot'],
1024 preserve_vnet=self.swap['preserve_vnet']
1025 )
1026 response = self.web_client.web_apps.begin_swap_slot(resource_group_name=self.resource_group,
1027 name=self.webapp_name,
1028 slot=self.name,
1029 slot_swap_entity=slot_swap_entity)
1030 elif self.swap['action'] == 'preview':
1031 if self.swap['target_slot'] is None:
1032 slot_swap_entity = CsmSlotEntity(
1033 target_slot=self.name,
1034 preserve_vnet=self.swap['preserve_vnet']
1035 )
1036 response = self.web_client.web_apps.apply_slot_config_to_production(resource_group_name=self.resource_group,
1037 name=self.webapp_name,
1038 slot_swap_entity=slot_swap_entity)
1039 else:
1040 slot_swap_entity = CsmSlotEntity(
1041 target_slot=self.swap['target_slot'],
1042 preserve_vnet=self.swap['preserve_vnet']
1043 )
1044 response = self.web_client.web_apps.apply_slot_configuration_slot(resource_group_name=self.resource_group,
1045 name=self.webapp_name,
1046 slot=self.name,
1047 slot_swap_entity=slot_swap_entity)
1048 elif self.swap['action'] == 'reset':
1049 if self.swap['target_slot'] is None:
1050 response = self.web_client.web_apps.reset_production_slot_config(resource_group_name=self.resource_group,
1051 name=self.webapp_name)
1052 else:
1053 response = self.web_client.web_apps.reset_slot_configuration_slot(resource_group_name=self.resource_group,
1054 name=self.webapp_name,
1055 slot=self.swap['target_slot'])
1056 response = self.web_client.web_apps.reset_slot_configuration_slot(resource_group_name=self.resource_group,
1057 name=self.webapp_name,
1058 slot=self.name)
1059
1060 self.log("Response : {0}".format(response))
1061
1062 return response
1063 except Exception as ex:
1064 self.fail("Failed to swap web app slot {0} in resource group {1}: {2}".format(self.name, self.resource_group, str(ex)))
1065
1066 def clone_slot(self):
1067 if self.configuration_source:
1068 src_slot = None if self.configuration_source.lower() == self.webapp_name.lower() else self.configuration_source
1069
1070 if src_slot is None:
1071 site_config_clone_from = self.get_configuration()
1072 else:
1073 site_config_clone_from = self.get_configuration_slot(slot_name=src_slot)
1074
1075 self.update_configuration_slot(site_config=site_config_clone_from)
1076
1077 if src_slot is None:
1078 app_setting_clone_from = self.list_app_settings()
1079 else:
1080 app_setting_clone_from = self.list_app_settings_slot(src_slot)
1081
1082 if self.app_settings:
1083 app_setting_clone_from.update(self.app_settings)
1084
1085 self.update_app_settings_slot(app_settings=app_setting_clone_from)
1086
1087
1088 def main():
1089 """Main execution"""
1090 AzureRMWebAppSlots()
1091
1092
1093 if __name__ == '__main__':
1094 main()