Debian Codegraph @

ansible_collections/azure/azcollection/plugins/modules/azure_rm_webapp.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_webapp
14 version_added: "0.1.2"
15 short_description: Manage Web App instances
16 description:
17 - Create, update and delete instance of Web App.
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 app to create or update. To create or update a deployment slot, use the {slot} parameter.
28 required: True
29 type: str
30
31 location:
32 description:
33 - Resource location. If not set, location from the resource group will be used as default.
34 type: str
35
36 plan:
37 description:
38 - App service plan. Required for creation.
39 - Can be name of existing app service plan in same resource group as web app.
40 - Can be the resource ID of an existing app service plan. For example
41 /subscriptions/<subs_id>/resourceGroups/<resource_group>/providers/Microsoft.Web/serverFarms/<plan_name>.
42 - Can be a dict containing five parameters, defined below.
43 - C(name), name of app service plan.
44 - C(resource_group), resource group of the app service plan.
45 - C(sku), SKU of app service plan, allowed values listed on U(https://azure.microsoft.com/en-us/pricing/details/app-service/linux/).
46 - C(is_linux), whether or not the app service plan is Linux. defaults to C(False).
47 - C(number_of_workers), number of workers for app service plan.
48 type: raw
49
50 frameworks:
51 description:
52 - Set of run time framework settings. Each setting is a dictionary.
53 - See U(https://docs.microsoft.com/en-us/azure/app-service/app-service-web-overview) for more info.
54 type: list
55 elements: dict
56 suboptions:
57 name:
58 description:
59 - Name of the framework.
60 - Supported framework list for Windows web app and Linux web app is different.
61 - Windows web apps support C(java), C(net_framework), C(php), C(python), and C(node) from June 2018.
62 - Windows web apps support multiple framework at the same time.
63 - Linux web apps support C(java), C(ruby), C(php), C(python), C(dotnetcore), and C(node) from June 2018.
64 - Linux web apps support only one framework.
65 - Java framework is mutually exclusive with others.
66 type: str
67 required: true
68 choices:
69 - java
70 - net_framework
71 - php
72 - python
73 - ruby
74 - dotnetcore
75 - node
76 version:
77 description:
78 - Version of the framework. For Linux web app supported value, see U(https://aka.ms/linux-stacks) for more info.
79 - C(net_framework) supported value sample, C(v4.8) for .NET 4.8 and C(v3.5) for .NET 3.5.
80 - C(php) supported value sample, C(8.1), C(8.2).
81 - C(python) supported value sample, C(3.8), C(3.9), C(3.10), C(3.11), C(3.12).
82 - C(node) supported value sample, C(18), C(20).
83 - C(dotnetcore) supported value sample, C(8), C(7), C(6).
84 - C(ruby) supported value sample, C(2.3).
85 - C(java) supported value sample, C(21), C(17), C(11) and C(8).
86 type: str
87 required: true
88 settings:
89 description:
90 - List of settings of the framework.
91 type: dict
92 suboptions:
93 java_container:
94 description:
95 - Name of Java container.
96 - Supported only when I(frameworks=java). Sample values C(Tomcat), C(JavaSE), C(RedHat).
97 type: str
98 required: True
99 java_container_version:
100 description:
101 - Version of Java container.
102 - Supported only when I(frameworks=java).
103 - Sample values for C(Tomcat), C(8.5), C(9.0), C(10.0), C(10.1).
104 type: str
105 required: True
106
107 container_settings:
108 description:
109 - Web app container settings.
110 type: dict
111 suboptions:
112 name:
113 description:
114 - Name of the container, for example C(imagename:tag).
115 - To create a multi-container app, the name should be 'COMPOSE|' or 'KUBE|' followed by base64 encoded configuration.
116 type: str
117 required: True
118 registry_server_url:
119 description:
120 - Container registry server URL, for example C(mydockerregistry.io).
121 type: str
122 registry_server_user:
123 description:
124 - The container registry server user name.
125 type: str
126 registry_server_password:
127 description:
128 - The container registry server password.
129 type: str
130
131 scm_type:
132 description:
133 - Repository type of deployment source, for example C(LocalGit), C(GitHub).
134 - List of supported values maintained at U(https://docs.microsoft.com/en-us/rest/api/appservice/webapps/createorupdate#scmtype).
135 type: str
136
137 always_on:
138 description:
139 - Keeps the app loaded even when there's no traffic.
140 type: bool
141
142 http20_enabled:
143 description:
144 - Configures a web site to allow clients to connect over HTTP 2.0.
145 type: bool
146
147 min_tls_version:
148 description:
149 - The minimum TLS encryption version required for the app.
150 type: str
151 choices:
152 - '1.0'
153 - '1.1'
154 - '1.2'
155
156 ftps_state:
157 description:
158 - The state of the FTP/FTPS service.
159 type: str
160 choices:
161 - AllAllowed
162 - FtpsOnly
163 - Disabled
164
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
175 branch:
176 description:
177 - The branch name of the repository.
178 type: str
179 startup_file:
180 description:
181 - The web's startup file.
182 - Used only for Linux web apps.
183 type: str
184
185 client_affinity_enabled:
186 description:
187 - Whether or not to send session affinity cookies, which route client requests in the same session to the same instance.
188 type: bool
189 default: True
190
191 https_only:
192 description:
193 - Configures web site to accept only https requests.
194 type: bool
195
196 app_settings:
197 description:
198 - Configure web app application settings. Suboptions are in key value pair format.
199 type: dict
200
201 purge_app_settings:
202 description:
203 - Purge any existing application settings. Replace web app application settings with app_settings.
204 type: bool
205 default: False
206
207 app_state:
208 description:
209 - Start/Stop/Restart the web app.
210 type: str
211 choices:
212 - started
213 - stopped
214 - restarted
215 default: started
216 site_auth_settings:
217 description:
218 - Configuration settings for the Azure App Service Authentication / Authorization feature.
219 type: dict
220 suboptions:
221 kind:
222 description:
223 - Kind of resource.
224 type: str
225 enabled:
226 description:
227 - Whether enable or disable the Authentication / Authorization feature for the current app.
228 type: bool
229 runtime_version:
230 description:
231 - The RuntimeVersion of the Authentication / Authorization feature in use for the current app.
232 type: str
233 unauthenticated_client_action:
234 description:
235 - The action to take when an unauthenticated client attempts to access the app.
236 type: str
237 choices:
238 - RedirectToLoginPage
239 - AllowAnonymous
240 token_store_enabled:
241 description:
242 - Whether to use App Service Token Store.
243 type: bool
244 allowed_external_redirect_urls:
245 description:
246 - External URLs that can be redirected to as part of logging in or logging out of the app.
247 - Note that the query string part of the URL is ignored.
248 type: list
249 elements: str
250 default_provider:
251 description:
252 - The default authentication provider to use when multiple providers are configured.
253 type: str
254 choices:
255 - AzureActiveDirectory
256 - Facebook
257 - Google
258 - MicrosoftAccount
259 - Twitter
260 - Github
261 token_refresh_extension_hours:
262 description:
263 - The number of hours after session token expiration that a session token can be used to call the token refresh API.
264 type: float
265 client_id:
266 description:
267 - The Client ID of this relying party application, known as the client_id.
268 type: str
269 client_secret:
270 description:
271 - The Client Secret of this relying party application (in Azure Active Directory, this is also referred to as the Key).
272 type: str
273 client_secret_setting_name:
274 description:
275 - The app setting name that contains the client secret of the relying party application.
276 type: str
277 client_secret_certificate_thumbprint:
278 description:
279 - An alternative to the client secret, that is the thumbprint of a certificate used for signing purposes.
280 - This property acts as a replacement for the Client Secret. It is also optional.
281 type: str
282 issuer:
283 description:
284 - The OpenID Connect Issuer URI that represents the entity which issues access tokens for this application.
285 type: str
286 allowed_audiences:
287 description:
288 - Allowed audience values to consider when validating JWTs issued by Azure Active Directory.
289 type: list
290 elements: str
291 aad_claims_authorization:
292 description:
293 - Gets a JSON string containing the Azure AD Acl settings.
294 type: str
295 additional_login_params:
296 description:
297 - Login parameters to send to the OpenID Connect authorization endpoint when a user logs in.
298 - Each parameter must be in the form "key=value".
299 type: str
300 google_client_id:
301 description:
302 - The OpenID Connect Client ID for the Google web application.
303 type: str
304 google_client_secret:
305 description:
306 - The client secret associated with the Google web application.
307 type: str
308 google_client_secret_setting_name:
309 description:
310 - The app setting name that contains the client secret associated with the Google web application.
311 type: str
312 google_o_auth_scopes:
313 description:
314 - The OAuth 2.0 scopes that will be requested as part of Google Sign-In authentication.
315 - This setting is optional. If not specified, "openid", "profile", and "email" are used as default scopes.
316 type: list
317 elements: str
318 facebook_app_id:
319 description:
320 - The App ID of the Facebook app used for login.
321 type: str
322 facebook_app_secret:
323 description:
324 - The App Secret of the Facebook app used for Facebook Login.
325 type: str
326 facebook_app_secret_setting_name:
327 description:
328 - The app setting name that contains the app secret used for Facebook Login.
329 type: str
330 facebook_o_auth_scopes:
331 description:
332 - The OAuth 2.0 scopes that will be requested as part of Facebook for Facebook Login.
333 type: list
334 elements: str
335 git_hub_client_id:
336 description:
337 - The Client Id of the GitHub app used for login.
338 type: str
339 git_hub_client_secret:
340 description:
341 - The Client Secret of the GitHub app used for Github Login.
342 type: str
343 git_hub_client_secret_setting_name:
344 description:
345 - The app setting name that contains the client secret of the Github app used for GitHub Login.
346 type: str
347 git_hub_o_auth_scopes:
348 description:
349 - The OAuth 2.0 scopes that will be requested as part of GitHub Login authentication.
350 - This setting is optional.
351 type: list
352 elements: str
353 twitter_consumer_key:
354 description:
355 - The OAuth 1.0a consumer key of the Twitter application used for sign-in.
356 type: str
357 twitter_consumer_secret:
358 description:
359 - The OAuth 1.0a consumer secret of the Twitter application used for sign-in.
360 - This setting is required for enabling Twitter Sign-In.
361 type: str
362 twitter_consumer_secret_setting_name:
363 description:
364 - The app setting name that contains the OAuth 1.0a consumer secret of the Twitter application used for sign-in.
365 type: str
366 microsoft_account_client_id:
367 description:
368 - The OAuth 2.0 client ID that was created for the app used for authentication.
369 - This setting is required for enabling Microsoft Account authentication.
370 type: str
371 microsoft_account_client_secret:
372 description:
373 - The OAuth 2.0 client secret that was created for the app used for authentication.
374 type: str
375 microsoft_account_client_secret_setting_name:
376 description:
377 - The app setting name containing the OAuth 2.0 client secret that was created for the app used for authentication.
378 type: str
379 microsoft_account_o_auth_scopes:
380 description:
381 - The OAuth 2.0 scopes that will be requested as part of Microsoft Account authentication.
382 type: list
383 elements: str
384 is_auth_from_file:
385 description:
386 - If I(is_auth_from_file=true), the auth config settings should be read from a file.
387 type: str
388 choices:
389 - 'true'
390 - 'false'
391 auth_file_path:
392 description:
393 - The path of the config file containing auth settings.
394 - If the path is relative, base will the site's root directory.
395 type: str
396 config_version:
397 description:
398 - The ConfigVersion of the Authentication / Authorization feature in use for the current app.
399 - The setting in this value can control the behavior of the control plane for Authentication / Authorization.
400 type: str
401 state:
402 description:
403 - State of the Web App.
404 - Use C(present) to create or update a Web App and C(absent) to delete it.
405 default: present
406 type: str
407 choices:
408 - absent
409 - present
410
411 extends_documentation_fragment:
412 - azure.azcollection.azure
413 - azure.azcollection.azure_tags
414 - azure.azcollection.azure_identity_multiple
415
416 author:
417 - Yunge Zhu (@yungezz)
418
419 '''
420
421 EXAMPLES = '''
422 - name: Create a windows web app with non-exist app service plan
423 azure_rm_webapp:
424 resource_group: myResourceGroup
425 name: myWinWebapp
426 plan:
427 resource_group: myAppServicePlan_rg
428 name: myAppServicePlan
429 is_linux: false
430 sku: S1
431
432 - name: Create a docker web app with some app settings, with docker image
433 azure_rm_webapp:
434 resource_group: myResourceGroup
435 name: myDockerWebapp
436 plan:
437 resource_group: myAppServicePlan_rg
438 name: myAppServicePlan
439 is_linux: true
440 sku: S1
441 number_of_workers: 2
442 app_settings:
443 testkey: testvalue
444 testkey2: testvalue2
445 container_settings:
446 name: ansible/ansible:ubuntu1404
447
448 - name: Create a docker web app with private acr registry
449 azure_rm_webapp:
450 resource_group: myResourceGroup
451 name: myDockerWebapp
452 plan: myAppServicePlan
453 app_settings:
454 testkey: testvalue
455 container_settings:
456 name: ansible/ubuntu1404
457 registry_server_url: myregistry.io
458 registry_server_user: user
459 registry_server_password: "{{ password }}"
460
461 - name: Create a multi-container web app
462 azure_rm_webapp:
463 resource_group: myResourceGroup
464 name: myMultiContainerWebapp
465 plan: myAppServicePlan
466 app_settings:
467 testkey: testvalue
468 container_settings:
469 name: "COMPOSE|{{ lookup('file', 'docker-compose.yml') | b64encode }}"
470
471 - name: Create a linux web app with Node 6.6 framework
472 azure_rm_webapp:
473 resource_group: myResourceGroup
474 name: myLinuxWebapp
475 plan:
476 resource_group: myAppServicePlan_rg
477 name: myAppServicePlan
478 app_settings:
479 testkey: testvalue
480 frameworks:
481 - name: "node"
482 version: "18"
483
484 - name: Create a windows web app with node, php
485 azure_rm_webapp:
486 resource_group: myResourceGroup
487 name: myWinWebapp
488 plan:
489 resource_group: myAppServicePlan_rg
490 name: myAppServicePlan
491 app_settings:
492 testkey: testvalue
493 frameworks:
494 - name: "node"
495 version: 18
496 - name: "php"
497 version: 8.2
498
499 - name: Create a stage deployment slot for an existing web app
500 azure_rm_webapp:
501 resource_group: myResourceGroup
502 name: myWebapp/slots/stage
503 plan:
504 resource_group: myAppServicePlan_rg
505 name: myAppServicePlan
506 app_settings:
507 testkey:testvalue
508
509 - name: Create a linux web app with java framework
510 azure_rm_webapp:
511 resource_group: myResourceGroup
512 name: myLinuxWebapp
513 plan:
514 resource_group: myAppServicePlan_rg
515 name: myAppServicePlan
516 app_settings:
517 testkey: testvalue
518 frameworks:
519 - name: "java"
520 version: "8"
521 settings:
522 java_container: "Tomcat"
523 java_container_version: "8.5"
524
525 - name: Create a windows web app with site_auth_settings
526 azure_rm_webapp:
527 resource_group: myResourceGroup
528 name: myWindowWebapp
529 site_auth_settings:
530 client_id: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
531 default_provider: 'MicrosoftAccount'
532 runtime_version: '-2'
533 token_refresh_extension_hours: 120
534 unauthenticated_client_action: 'RedirectToLoginPage'
535 client_secret: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
536 token_store_enabled: false
537 enabled: true
538 is_auth_from_file: false
539 plan:
540 resource_group: myResourceGroup
541 name: myLinuxwebapp
542 is_linux: false
543 sku: S1
544
545 - name: Create a linux web app with python framework
546 azure_rm_webapp:
547 resource_group: myResourceGroup
548 name: myLinuxWebapp
549 plan:
550 resource_group: myAppServicePlan_rg
551 name: myAppServicePlan
552 app_settings:
553 testkey: testvalue
554 frameworks:
555 - name: "python"
556 version: "3.10"
557 '''
558
559 RETURN = '''
560 id:
561 description:
562 - ID of current web app.
563 returned: always
564 type: str
565 sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.Web/sites/myWebApp"
566 '''
567
568 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common_ext import AzureRMModuleBaseExt
569
570 try:
571 from azure.core.exceptions import ResourceNotFoundError
572 from azure.core.polling import LROPoller
573 from azure.core.exceptions import HttpResponseError
574 from azure.mgmt.web.models import Site, AppServicePlan, SkuDescription, NameValuePair, SiteSourceControl, \
575 StringDictionary, ManagedServiceIdentity, UserAssignedIdentity
576 except ImportError:
577 # This is handled in azure_rm_common
578 pass
579
580 container_settings_spec = dict(
581 name=dict(type='str', required=True),
582 registry_server_url=dict(type='str'),
583 registry_server_user=dict(type='str'),
584 registry_server_password=dict(type='str', no_log=True)
585 )
586
587 deployment_source_spec = dict(
588 url=dict(type='str'),
589 branch=dict(type='str')
590 )
591
592
593 framework_settings_spec = dict(
594 java_container=dict(type='str', required=True),
595 java_container_version=dict(type='str', required=True)
596 )
597
598
599 framework_spec = dict(
600 name=dict(
601 type='str',
602 required=True,
603 choices=['net_framework', 'java', 'php', 'node', 'python', 'dotnetcore', 'ruby']),
604 version=dict(type='str', required=True),
605 settings=dict(type='dict', options=framework_settings_spec)
606 )
607
608
609 site_auth_settings_spec = dict(
610 kind=dict(type='str'),
611 enabled=dict(type='bool'),
612 runtime_version=dict(type='str'),
613 unauthenticated_client_action=dict(type='str', choices=["RedirectToLoginPage", "AllowAnonymous"]),
614 token_store_enabled=dict(type='bool'),
615 allowed_external_redirect_urls=dict(type='list', elements='str'),
616 default_provider=dict(type='str', choices=["Facebook", "Google", "MicrosoftAccount", "Twitter", "Github", "AzureActiveDirectory"]),
617 token_refresh_extension_hours=dict(type='float', no_log=True),
618 client_id=dict(type='str'),
619 client_secret=dict(type='str', no_log=True),
620 client_secret_setting_name=dict(type='str'),
621 client_secret_certificate_thumbprint=dict(type='str', no_log=True),
622 issuer=dict(type='str'),
623 allowed_audiences=dict(type='list', elements='str'),
624 additional_login_params=dict(type='str'),
625 aad_claims_authorization=dict(type='str'),
626 google_client_id=dict(type='str'),
627 google_client_secret=dict(type='str', no_log=True),
628 google_client_secret_setting_name=dict(type='str'),
629 google_o_auth_scopes=dict(type='list', elements='str'),
630 facebook_app_id=dict(type='str'),
631 facebook_app_secret=dict(type='str', no_log=True),
632 facebook_app_secret_setting_name=dict(type='str'),
633 facebook_o_auth_scopes=dict(type='list', elements='str'),
634 git_hub_client_id=dict(type='str'),
635 git_hub_client_secret=dict(type='str', no_log=True),
636 git_hub_client_secret_setting_name=dict(type='str'),
637 git_hub_o_auth_scopes=dict(type='list', elements='str'),
638 twitter_consumer_key=dict(type='str', no_log=True),
639 twitter_consumer_secret=dict(type='str', no_log=True),
640 twitter_consumer_secret_setting_name=dict(type='str'),
641 microsoft_account_client_id=dict(type='str'),
642 microsoft_account_client_secret=dict(type='str', no_log=True),
643 microsoft_account_client_secret_setting_name=dict(type='str'),
644 microsoft_account_o_auth_scopes=dict(type='list', elements='str'),
645 is_auth_from_file=dict(type='str', choices=['true', 'false']),
646 auth_file_path=dict(type='str'),
647 config_version=dict(type='str')
648 )
649
650
651 def _normalize_sku(sku):
652 if sku is None:
653 return sku
654
655 sku = sku.upper()
656 if sku == 'FREE':
657 return 'F1'
658 elif sku == 'SHARED':
659 return 'D1'
660 return sku
661
662
663 def get_sku_name(tier):
664 tier = tier.upper()
665 if tier == 'F1' or tier == "FREE":
666 return 'FREE'
667 elif tier == 'D1' or tier == "SHARED":
668 return 'SHARED'
669 elif tier in ['B1', 'B2', 'B3', 'BASIC']:
670 return 'BASIC'
671 elif tier in ['S1', 'S2', 'S3']:
672 return 'STANDARD'
673 elif tier in ['P1', 'P2', 'P3']:
674 return 'PREMIUM'
675 elif tier in ['P1V2', 'P2V2', 'P3V2']:
676 return 'PREMIUMV2'
677 else:
678 return None
679
680
681 def appserviceplan_to_dict(plan):
682 return dict(
683 id=plan.id,
684 name=plan.name,
685 kind=plan.kind,
686 location=plan.location,
687 reserved=plan.reserved,
688 is_linux=plan.reserved,
689 provisioning_state=plan.provisioning_state,
690 tags=plan.tags if plan.tags else None
691 )
692
693
694 def webapp_to_dict(webapp):
695 return dict(
696 id=webapp.id,
697 name=webapp.name,
698 location=webapp.location,
699 client_cert_enabled=webapp.client_cert_enabled,
700 enabled=webapp.enabled,
701 reserved=webapp.reserved,
702 client_affinity_enabled=webapp.client_affinity_enabled,
703 server_farm_id=webapp.server_farm_id,
704 host_names_disabled=webapp.host_names_disabled,
705 https_only=webapp.https_only if hasattr(webapp, 'https_only') else None,
706 skip_custom_domain_verification=webapp.skip_custom_domain_verification if hasattr(webapp, 'skip_custom_domain_verification') else None,
707 ttl_in_seconds=webapp.ttl_in_seconds if hasattr(webapp, 'ttl_in_seconds') else None,
708 state=webapp.state,
709 identity=webapp.identity.as_dict() if webapp.identity else None,
710 tags=webapp.tags if webapp.tags else None
711 )
712
713
714 class Actions:
715 CreateOrUpdate, UpdateAppSettings, UpdateAuthSettings, Delete = range(4)
716
717
718 class AzureRMWebApps(AzureRMModuleBaseExt):
719 """Configuration class for an Azure RM Web App resource"""
720
721 def __init__(self):
722 self.module_arg_spec = dict(
723 resource_group=dict(
724 type='str',
725 required=True
726 ),
727 name=dict(
728 type='str',
729 required=True
730 ),
731 location=dict(
732 type='str'
733 ),
734 plan=dict(
735 type='raw'
736 ),
737 frameworks=dict(
738 type='list',
739 elements='dict',
740 options=framework_spec
741 ),
742 container_settings=dict(
743 type='dict',
744 options=container_settings_spec
745 ),
746 scm_type=dict(
747 type='str',
748 ),
749 always_on=dict(
750 type='bool',
751 ),
752 http20_enabled=dict(
753 type='bool',
754 ),
755 min_tls_version=dict(
756 type='str',
757 choices=['1.0', '1.1', '1.2'],
758 ),
759 ftps_state=dict(
760 type='str',
761 choices=['AllAllowed', 'FtpsOnly', 'Disabled'],
762 ),
763 deployment_source=dict(
764 type='dict',
765 options=deployment_source_spec
766 ),
767 startup_file=dict(
768 type='str'
769 ),
770 client_affinity_enabled=dict(
771 type='bool',
772 default=True
773 ),
774 https_only=dict(
775 type='bool'
776 ),
777 app_settings=dict(
778 type='dict'
779 ),
780 purge_app_settings=dict(
781 type='bool',
782 default=False
783 ),
784 app_state=dict(
785 type='str',
786 choices=['started', 'stopped', 'restarted'],
787 default='started'
788 ),
789 site_auth_settings=dict(
790 type='dict',
791 options=site_auth_settings_spec
792 ),
793 identity=dict(
794 type='dict',
795 options=self.managed_identity_multiple_spec
796 ),
797 state=dict(
798 type='str',
799 default='present',
800 choices=['present', 'absent']
801 )
802 )
803
804 mutually_exclusive = [['container_settings', 'frameworks']]
805
806 self.resource_group = None
807 self.name = None
808 self.location = None
809
810 # update in create_or_update as parameters
811 self.client_affinity_enabled = True
812 self.https_only = None
813
814 self.tags = None
815
816 # Managed Identity
817 self.identity = None
818
819 # site config, e.g app settings, ssl
820 self.site_config = dict()
821 self.app_settings = dict()
822 self.app_settings_strDic = None
823 self.site_auth_settings = None
824
825 # app service plan
826 self.plan = None
827
828 # siteSourceControl
829 self.deployment_source = dict()
830
831 # site, used at level creation, or update. e.g windows/linux, client_affinity etc first level args
832 self.site = None
833
834 # property for internal usage, not used for sdk
835 self.container_settings = None
836
837 self.purge_app_settings = False
838 self.app_state = 'started'
839
840 self.results = dict(
841 changed=False,
842 id=None,
843 )
844 self.state = None
845 self.to_do = []
846
847 self.frameworks = None
848
849 # set site_config value from kwargs
850 self.site_config_updatable_properties = ["net_framework_version",
851 "java_version",
852 "php_version",
853 "python_version",
854 "scm_type",
855 "always_on",
856 "http20_enabled",
857 "min_tls_version",
858 "ftps_state",
859 "app_command_line"]
860
861 # updatable_properties
862 self.updatable_properties = ["client_affinity_enabled",
863 "https_only"]
864
865 self.supported_linux_frameworks = ['ruby', 'php', 'python', 'dotnetcore', 'node', 'java']
866 self.supported_windows_frameworks = ['net_framework', 'php', 'python', 'node', 'java', 'dotnetcore']
867
868 self._managed_identity = None
869
870 self.startup_file = None
871
872 super(AzureRMWebApps, self).__init__(derived_arg_spec=self.module_arg_spec,
873 mutually_exclusive=mutually_exclusive,
874 supports_check_mode=True,
875 supports_tags=True)
876
877 @property
878 def managed_identity(self):
879 if not self._managed_identity:
880 self._managed_identity = {"identity": ManagedServiceIdentity,
881 "user_assigned": UserAssignedIdentity
882 }
883 return self._managed_identity
884
885 def exec_module(self, **kwargs):
886 """Main module execution method"""
887
888 for key in list(self.module_arg_spec.keys()) + ['tags']:
889 if hasattr(self, key):
890 setattr(self, key, kwargs[key])
891 elif kwargs[key] is not None:
892 if key in ["scm_type", "always_on", "http20_enabled", "min_tls_version", "ftps_state"]:
893 self.site_config[key] = kwargs[key]
894
895 old_response = None
896 response = None
897 to_be_updated = False
898
899 # set location
900 resource_group = self.get_resource_group(self.resource_group)
901 if not self.location:
902 self.location = resource_group.location
903
904 # get existing web app
905 old_response = self.get_webapp()
906
907 if old_response:
908 self.results['id'] = old_response['id']
909 self.results['site_auth_settings'] = self.get_auth_settings()
910
911 if self.state == 'present':
912 if not self.plan and not old_response:
913 self.fail("Please specify plan for newly created web app.")
914
915 if not self.plan:
916 self.plan = old_response['server_farm_id']
917
918 self.plan = self.parse_resource_to_dict(self.plan)
919
920 # get app service plan
921 is_linux = False
922 old_plan = self.get_app_service_plan()
923 if old_plan:
924 is_linux = old_plan['reserved']
925 else:
926 is_linux = self.plan['is_linux'] if 'is_linux' in self.plan else False
927
928 if self.frameworks:
929 # java is mutually exclusive with other frameworks
930 if len(self.frameworks) > 1 and any(f['name'] == 'java' for f in self.frameworks):
931 self.fail('Java is mutually exclusive with other frameworks.')
932
933 if is_linux:
934 if len(self.frameworks) != 1:
935 self.fail('Can specify one framework only for Linux web app.')
936
937 if self.frameworks[0]['name'] not in self.supported_linux_frameworks:
938 self.fail('Unsupported framework {0} for Linux web app.'.format(self.frameworks[0]['name']))
939
940 self.site_config['linux_fx_version'] = (self.frameworks[0]['name'] + '|' + self.frameworks[0]['version']).upper()
941
942 if self.frameworks[0]['name'] == 'java':
943 if self.frameworks[0]['version'] not in ['8', '11', '17', '21']:
944 self.fail("Linux web app only supports java 8, 11, 17 and 21.")
945 if self.frameworks[0]['settings'] and self.frameworks[0]['settings']['java_container'].lower() != 'tomcat':
946 self.fail("Linux web app only supports tomcat container.")
947
948 if self.frameworks[0]['settings'] and self.frameworks[0]['settings']['java_container'].lower() == 'tomcat':
949 self.site_config['linux_fx_version'] = 'TOMCAT|' + self.frameworks[0]['settings']['java_container_version'] + '-jre8'
950 else:
951 self.site_config['linux_fx_version'] = 'JAVA|{0}-jre{0}'.format(self.frameworks[0]['version'])
952 else:
953 for fx in self.frameworks:
954 if fx.get('name') not in self.supported_windows_frameworks:
955 self.fail('Unsupported framework {0} for Windows web app.'.format(fx.get('name')))
956 else:
957 self.site_config[fx.get('name') + '_version'] = fx.get('version')
958
959 if 'settings' in fx and fx['settings'] is not None:
960 for key, value in fx['settings'].items():
961 self.site_config[key] = value
962
963 if not self.app_settings:
964 self.app_settings = dict()
965
966 if self.container_settings:
967 linux_fx_version = 'DOCKER|'
968
969 if self.container_settings.get('registry_server_url'):
970 self.app_settings['DOCKER_REGISTRY_SERVER_URL'] = 'https://' + self.container_settings['registry_server_url']
971
972 linux_fx_version += self.container_settings['registry_server_url'] + '/'
973
974 linux_fx_version += self.container_settings['name']
975
976 # Use given name as is if it starts with allowed values of multi-container application
977 if self.container_settings['name'].startswith('COMPOSE|') or self.container_settings['name'].startswith('KUBE|'):
978 linux_fx_version = self.container_settings['name']
979
980 self.site_config['linux_fx_version'] = linux_fx_version
981
982 if self.container_settings.get('registry_server_user'):
983 self.app_settings['DOCKER_REGISTRY_SERVER_USERNAME'] = self.container_settings['registry_server_user']
984
985 if self.container_settings.get('registry_server_password'):
986 self.app_settings['DOCKER_REGISTRY_SERVER_PASSWORD'] = self.container_settings['registry_server_password']
987
988 # init site
989 self.site = Site(location=self.location, site_config=self.site_config)
990
991 if self.https_only is not None:
992 self.site.https_only = self.https_only
993
994 self.site.client_affinity_enabled = self.client_affinity_enabled
995
996 # check if the web app already present in the resource group
997 if not old_response:
998 self.log("Web App instance doesn't exist")
999
1000 to_be_updated = True
1001 self.to_do.append(Actions.CreateOrUpdate)
1002 if self.site_auth_settings is not None:
1003 self.to_do.append(Actions.UpdateAuthSettings)
1004 self.site.tags = self.tags
1005
1006 if self.identity:
1007 update_identity, self.site.identity = self.update_managed_identity(new_identity=self.identity)
1008
1009 # service plan is required for creation
1010 if not self.plan:
1011 self.fail("Please specify app service plan in plan parameter.")
1012
1013 if not old_plan:
1014 # no existing service plan, create one
1015 if (not self.plan.get('name') or not self.plan.get('sku')):
1016 self.fail('Please specify name, is_linux, sku in plan')
1017
1018 if 'location' not in self.plan:
1019 plan_resource_group = self.get_resource_group(self.plan['resource_group'])
1020 self.plan['location'] = plan_resource_group.location
1021
1022 old_plan = self.create_app_service_plan()
1023
1024 self.site.server_farm_id = old_plan['id']
1025
1026 # if linux, setup startup_file
1027 if old_plan['is_linux']:
1028 if hasattr(self, 'startup_file'):
1029 self.site_config['app_command_line'] = self.startup_file
1030
1031 # set app setting
1032 if self.app_settings:
1033 app_settings = []
1034 for key in self.app_settings.keys():
1035 app_settings.append(NameValuePair(name=key, value=self.app_settings[key]))
1036
1037 self.site_config['app_settings'] = app_settings
1038 else:
1039 # existing web app, do update
1040 self.log("Web App instance already exists")
1041
1042 self.log('Result: {0}'.format(old_response))
1043
1044 if self.identity:
1045 update_identity, self.site.identity = self.update_managed_identity(new_identity=self.identity,
1046 curr_identity=old_response.get('identity', None))
1047
1048 if update_identity:
1049 to_be_updated = True
1050 self.to_do.append(Actions.CreateOrUpdate)
1051
1052 update_tags, self.site.tags = self.update_tags(old_response.get('tags', None))
1053
1054 if update_tags:
1055 to_be_updated = True
1056 self.to_do.append(Actions.CreateOrUpdate)
1057
1058 # check if root level property changed
1059 if self.is_updatable_property_changed(old_response):
1060 to_be_updated = True
1061 self.to_do.append(Actions.CreateOrUpdate)
1062
1063 # check if site_config changed
1064 old_config = self.get_webapp_configuration()
1065
1066 if self.is_startup_file_changed(old_config):
1067 self.site_config['app_command_line'] = self.startup_file
1068
1069 if self.is_site_config_changed(old_config):
1070 to_be_updated = True
1071 self.to_do.append(Actions.CreateOrUpdate)
1072
1073 # check if linux_fx_version changed
1074 if old_config.linux_fx_version != self.site_config.get('linux_fx_version', ''):
1075 to_be_updated = True
1076 self.to_do.append(Actions.CreateOrUpdate)
1077
1078 self.app_settings_strDic = self.list_app_settings()
1079
1080 # purge existing app_settings:
1081 if self.purge_app_settings:
1082 to_be_updated = True
1083 self.app_settings_strDic = dict()
1084 self.to_do.append(Actions.UpdateAppSettings)
1085
1086 # check if app settings changed
1087 if self.purge_app_settings or self.is_app_settings_changed():
1088 to_be_updated = True
1089 self.to_do.append(Actions.UpdateAppSettings)
1090
1091 if self.app_settings:
1092 for key in self.app_settings.keys():
1093 self.app_settings_strDic[key] = self.app_settings[key]
1094
1095 if self.site_auth_settings is not None:
1096 result = dict(compare=[])
1097 if not self.default_compare({}, self.site_auth_settings, self.results['site_auth_settings'], '', dict(compare=[])):
1098 to_be_updated = True
1099 self.to_do.append(Actions.UpdateAuthSettings)
1100
1101 elif self.state == 'absent':
1102 if old_response:
1103 self.log("Delete Web App instance")
1104 self.results['changed'] = True
1105
1106 if self.check_mode:
1107 return self.results
1108
1109 self.delete_webapp()
1110
1111 self.log('Web App instance deleted')
1112
1113 else:
1114 self.log("Web app {0} not exists.".format(self.name))
1115
1116 if to_be_updated:
1117 self.log('Need to Create/Update web app')
1118 self.results['changed'] = True
1119
1120 if self.check_mode:
1121 return self.results
1122
1123 if Actions.CreateOrUpdate in self.to_do:
1124 response = self.create_update_webapp()
1125
1126 self.results['id'] = response['id']
1127
1128 if Actions.UpdateAppSettings in self.to_do:
1129 update_response = self.update_app_settings()
1130 self.results['id'] = update_response.id
1131
1132 if Actions.UpdateAuthSettings in self.to_do:
1133 auth_settings = self.update_auth_settings(self.site_auth_settings)
1134 self.results['site_auth_settings'] = auth_settings
1135 else:
1136 self.results['site_auth_settings'] = self.get_auth_settings()
1137
1138 webapp = None
1139 if old_response:
1140 webapp = old_response
1141 if response:
1142 webapp = response
1143
1144 if webapp:
1145 if (webapp['state'] != 'Stopped' and self.app_state == 'stopped') or \
1146 (webapp['state'] != 'Running' and self.app_state == 'started') or \
1147 self.app_state == 'restarted':
1148
1149 self.results['changed'] = True
1150 if self.check_mode:
1151 return self.results
1152
1153 self.set_webapp_state(self.app_state)
1154
1155 return self.results
1156
1157 # compare existing web app with input, determine weather it's update operation
1158 def is_updatable_property_changed(self, existing_webapp):
1159 for property_name in self.updatable_properties:
1160 if hasattr(self, property_name) and getattr(self, property_name) is not None and \
1161 getattr(self, property_name) != existing_webapp.get(property_name, None):
1162 return True
1163
1164 return False
1165
1166 # compare xxx_version
1167 def is_site_config_changed(self, existing_config):
1168 for updatable_property in self.site_config_updatable_properties:
1169 if updatable_property in self.site_config:
1170 if not getattr(existing_config, updatable_property) or \
1171 str(getattr(existing_config, updatable_property)).upper() != str(self.site_config.get(updatable_property)).upper():
1172 return True
1173
1174 return False
1175
1176 # check if startup file changed
1177 def is_startup_file_changed(self, existing_config):
1178 self_name = "startup_file"
1179 property_name = "app_command_line"
1180 if hasattr(self, self_name) and getattr(self, self_name) is not None:
1181 if not getattr(existing_config, property_name) or \
1182 str(getattr(existing_config, property_name)).upper() != str(self.startup_file).upper():
1183 return True
1184
1185 return False
1186
1187 # comparing existing app setting with input, determine whether it's changed
1188 def is_app_settings_changed(self):
1189 if self.app_settings:
1190 if self.app_settings_strDic:
1191 for key in self.app_settings.keys():
1192 if self.app_settings[key] != self.app_settings_strDic.get(key, None):
1193 return True
1194 else:
1195 return True
1196 return False
1197
1198 # comparing deployment source with input, determine wheather it's changed
1199 def is_deployment_source_changed(self, existing_webapp):
1200 if self.deployment_source:
1201 if self.deployment_source.get('url') \
1202 and self.deployment_source['url'] != existing_webapp.get('site_source_control')['url']:
1203 return True
1204
1205 if self.deployment_source.get('branch') \
1206 and self.deployment_source['branch'] != existing_webapp.get('site_source_control')['branch']:
1207 return True
1208
1209 return False
1210
1211 def create_update_webapp(self):
1212 '''
1213 Creates or updates Web App with the specified configuration.
1214
1215 :return: deserialized Web App instance state dictionary
1216 '''
1217 self.log(
1218 "Creating / Updating the Web App instance {0}".format(self.name))
1219
1220 try:
1221 response = self.web_client.web_apps.begin_create_or_update(resource_group_name=self.resource_group,
1222 name=self.name,
1223 site_envelope=self.site)
1224 if isinstance(response, LROPoller):
1225 response = self.get_poller_result(response)
1226
1227 except Exception as exc:
1228 self.log('Error attempting to create the Web App instance.')
1229 self.fail("Error creating the Web App instance: {0}".format(str(exc)))
1230 return webapp_to_dict(response)
1231
1232 def delete_webapp(self):
1233 '''
1234 Deletes specified Web App instance in the specified subscription and resource group.
1235
1236 :return: True
1237 '''
1238 self.log("Deleting the Web App instance {0}".format(self.name))
1239 try:
1240 self.web_client.web_apps.delete(resource_group_name=self.resource_group, name=self.name)
1241 except Exception as e:
1242 self.log('Error attempting to delete the Web App instance.')
1243 self.fail("Error deleting the Web App instance: {0}".format(str(e)))
1244
1245 return True
1246
1247 def get_webapp(self):
1248 '''
1249 Gets the properties of the specified Web App.
1250
1251 :return: deserialized Web App instance state dictionary
1252 '''
1253 self.log(
1254 "Checking if the Web App instance {0} is present".format(self.name))
1255
1256 response = None
1257
1258 try:
1259 response = self.web_client.web_apps.get(resource_group_name=self.resource_group, name=self.name)
1260
1261 # Newer SDK versions (0.40.0+) seem to return None if it doesn't exist instead of raising error
1262 if response is not None:
1263 self.log("Response : {0}".format(response))
1264 self.log("Web App instance : {0} found".format(response.name))
1265 return webapp_to_dict(response)
1266
1267 except ResourceNotFoundError:
1268 pass
1269
1270 self.log("Didn't find web app {0} in resource group {1}".format(self.name, self.resource_group))
1271
1272 return False
1273
1274 def get_app_service_plan(self):
1275 '''
1276 Gets app service plan
1277 :return: deserialized app service plan dictionary
1278 '''
1279 self.log("Get App Service Plan {0}".format(self.plan['name']))
1280
1281 try:
1282 response = self.web_client.app_service_plans.get(
1283 resource_group_name=self.plan['resource_group'],
1284 name=self.plan['name'])
1285
1286 # Newer SDK versions (0.40.0+) seem to return None if it doesn't exist instead of raising error
1287 if response is not None:
1288 self.log("Response : {0}".format(response))
1289 self.log("App Service Plan : {0} found".format(response.name))
1290
1291 return appserviceplan_to_dict(response)
1292 except ResourceNotFoundError:
1293 pass
1294
1295 self.log("Didn't find app service plan {0} in resource group {1}".format(
1296 self.plan['name'], self.plan['resource_group']))
1297
1298 return False
1299
1300 def create_app_service_plan(self):
1301 '''
1302 Creates app service plan
1303 :return: deserialized app service plan dictionary
1304 '''
1305 self.log("Create App Service Plan {0}".format(self.plan['name']))
1306
1307 try:
1308 # normalize sku
1309 sku = _normalize_sku(self.plan['sku'])
1310
1311 sku_def = SkuDescription(tier=get_sku_name(
1312 sku), name=sku, capacity=(self.plan.get('number_of_workers', None)))
1313 plan_def = AppServicePlan(
1314 location=self.plan['location'], app_service_plan_name=self.plan['name'], sku=sku_def, reserved=(self.plan.get('is_linux', None)))
1315
1316 poller = self.web_client.app_service_plans.begin_create_or_update(
1317 resource_group_name=self.plan['resource_group'], name=self.plan['name'], app_service_plan=plan_def)
1318
1319 if isinstance(poller, LROPoller):
1320 response = self.get_poller_result(poller)
1321
1322 self.log("Response : {0}".format(response))
1323
1324 return appserviceplan_to_dict(response)
1325 except Exception as ex:
1326 self.fail("Failed to create app service plan {0} in resource group {1}: {2}".format(
1327 self.plan['name'], self.plan['resource_group'], str(ex)))
1328
1329 def list_app_settings(self):
1330 '''
1331 List application settings
1332 :return: deserialized list response
1333 '''
1334 self.log("List application setting")
1335
1336 try:
1337 response = self.web_client.web_apps.list_application_settings(resource_group_name=self.resource_group, name=self.name)
1338 self.log("Response : {0}".format(response))
1339
1340 return response.properties
1341 except Exception as ex:
1342 self.fail("Failed to list application settings for web app {0} in resource group {1}: {2}".format(
1343 self.name, self.resource_group, str(ex)))
1344
1345 def update_auth_settings(self, body):
1346 '''
1347 Update web app auth settings
1348 :return: deserialized updating response
1349 '''
1350 self.log("Update web app auth settings")
1351
1352 try:
1353 response = self.web_client.web_apps.update_auth_settings(self.resource_group, self.name, body)
1354 self.log("Response : {0}".format(response))
1355 return response.as_dict()
1356 except HttpResponseError as ex:
1357 self.fail("Failed to update web app auth settings for web app {0} in resource group {1}: {2}".format(
1358 self.name, self.resource_group, str(ex)))
1359
1360 def get_auth_settings(self):
1361 '''
1362 Get the web app auth settings
1363 :return: deserialized updating response
1364 '''
1365 self.log("Get the web app auth settings")
1366
1367 try:
1368 response = self.web_client.web_apps.get_auth_settings(self.resource_group, self.name)
1369 self.log("Response : {0}".format(response))
1370 return response.as_dict()
1371 except HttpResponseError as ex:
1372 self.log("Failed to Get web app auth settings for web app {0} in resource group {1}: {2}".format(
1373 self.name, self.resource_group, str(ex)))
1374
1375 def update_app_settings(self):
1376 '''
1377 Update application settings
1378 :return: deserialized updating response
1379 '''
1380 self.log("Update application setting")
1381
1382 try:
1383 settings = StringDictionary(
1384 properties=self.app_settings_strDic
1385 )
1386 response = self.web_client.web_apps.update_application_settings(
1387 resource_group_name=self.resource_group, name=self.name, app_settings=settings)
1388 self.log("Response : {0}".format(response))
1389 return response
1390 except HttpResponseError as ex:
1391 self.fail("Failed to update application settings for web app {0} in resource group {1}: {2}".format(
1392 self.name, self.resource_group, str(ex)))
1393
1394 def create_or_update_source_control(self):
1395 '''
1396 Update site source control
1397 :return: deserialized updating response
1398 '''
1399 self.log("Update site source control")
1400
1401 if self.deployment_source is None:
1402 return False
1403
1404 self.deployment_source['is_manual_integration'] = False
1405 self.deployment_source['is_mercurial'] = False
1406
1407 try:
1408 site_source_control = SiteSourceControl(
1409 repo_url=self.deployment_source.get('url'),
1410 branch=self.deployment_source.get('branch')
1411 )
1412 response = self.web_client.web_apps.begin_create_or_update_source_control(
1413 resource_group_name=self.resource_group, name=self.name, site_source_control=site_source_control)
1414 self.log("Response : {0}".format(response))
1415
1416 return response.as_dict()
1417 except Exception:
1418 self.fail("Failed to update site source control for web app {0} in resource group {1}".format(
1419 self.name, self.resource_group))
1420
1421 def get_webapp_configuration(self):
1422 '''
1423 Get web app configuration
1424 :return: deserialized web app configuration response
1425 '''
1426 self.log("Get web app configuration")
1427
1428 try:
1429 response = self.web_client.web_apps.get_configuration(
1430 resource_group_name=self.resource_group, name=self.name)
1431 self.log("Response : {0}".format(response))
1432
1433 return response
1434 except ResourceNotFoundError as ex:
1435 self.log("Failed to get configuration for web app {0} in resource group {1}: {2}".format(
1436 self.name, self.resource_group, str(ex)))
1437
1438 return False
1439
1440 def set_webapp_state(self, appstate):
1441 '''
1442 Start/stop/restart web app
1443 :return: deserialized updating response
1444 '''
1445 try:
1446 if appstate == 'started':
1447 response = self.web_client.web_apps.start(resource_group_name=self.resource_group, name=self.name)
1448 elif appstate == 'stopped':
1449 response = self.web_client.web_apps.stop(resource_group_name=self.resource_group, name=self.name)
1450 elif appstate == 'restarted':
1451 response = self.web_client.web_apps.restart(resource_group_name=self.resource_group, name=self.name)
1452 else:
1453 self.fail("Invalid web app state {0}".format(appstate))
1454
1455 self.log("Response : {0}".format(response))
1456
1457 return response
1458 except Exception as ex:
1459 request_id = ex.request_id if ex.request_id else ''
1460 self.log("Failed to {0} web app {1} in resource group {2}, request_id {3} - {4}".format(
1461 appstate, self.name, self.resource_group, request_id, str(ex)))
1462
1463
1464 def main():
1465 """Main execution"""
1466 AzureRMWebApps()
1467
1468
1469 if __name__ == '__main__':
1470 main()