Debian Codegraph @

ansible_collections/azure/azcollection/plugins/modules/azure_rm_appserviceplan.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_appserviceplan
14 version_added: "0.1.2"
15 short_description: Manage App Service Plan
16 description:
17 - Create, update and delete instance of App Service Plan.
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
26 name:
27 description:
28 - Unique name of the app service plan to create or update.
29 required: True
30 type: str
31
32 location:
33 description:
34 - Resource location. If not set, location from the resource group will be used as default.
35 type: str
36 sku:
37 description:
38 - The pricing tiers, e.g., C(F1), C(D1), C(B1), C(B2), C(B3), C(S1), C(P1), C(P1V2) etc.
39 - Please see U(https://azure.microsoft.com/en-us/pricing/details/app-service/plans/) for more detail.
40 - For Linux app service plan, please see U(https://azure.microsoft.com/en-us/pricing/details/app-service/linux/) for more detail.
41 type: str
42 is_linux:
43 description:
44 - Describe whether to host webapp on Linux worker.
45 type: bool
46 default: false
47
48 number_of_workers:
49 description:
50 - Describe number of workers to be allocated.
51 type: str
52
53 state:
54 description:
55 - Assert the state of the app service plan.
56 - Use C(present) to create or update an app service plan and C(absent) to delete it.
57 default: present
58 type: str
59 choices:
60 - absent
61 - present
62
63 extends_documentation_fragment:
64 - azure.azcollection.azure
65 - azure.azcollection.azure_tags
66
67 author:
68 - Yunge Zhu (@yungezz)
69
70 '''
71
72 EXAMPLES = '''
73 - name: Create a windows app service plan
74 azure_rm_appserviceplan:
75 resource_group: myResourceGroup
76 name: myAppPlan
77 location: eastus
78 sku: S1
79
80 - name: Create a linux app service plan
81 azure_rm_appserviceplan:
82 resource_group: myResourceGroup
83 name: myAppPlan
84 location: eastus
85 sku: S1
86 is_linux: true
87 number_of_workers: 1
88
89 - name: update sku of existing windows app service plan
90 azure_rm_appserviceplan:
91 resource_group: myResourceGroup
92 name: myAppPlan
93 location: eastus
94 sku: S2
95 '''
96
97 RETURN = '''
98 azure_appserviceplan:
99 description: Facts about the current state of the app service plan.
100 returned: always
101 type: dict
102 sample: {
103 "id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.Web/serverfarms/myAppPlan"
104 }
105 '''
106
107 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common import AzureRMModuleBase
108
109 try:
110 from azure.core.exceptions import ResourceNotFoundError
111 from azure.core.polling import LROPoller
112 from azure.mgmt.web.models import AppServicePlan, SkuDescription
113 except ImportError:
114 # This is handled in azure_rm_common
115 pass
116
117
118 def _normalize_sku(sku):
119 if sku is None:
120 return sku
121
122 sku = sku.upper()
123 if sku == 'FREE':
124 return 'F1'
125 elif sku == 'SHARED':
126 return 'D1'
127 return sku
128
129
130 def get_sku_name(tier):
131 tier = tier.upper()
132 if tier == 'F1' or tier == "FREE":
133 return 'FREE'
134 elif tier == 'D1' or tier == "SHARED":
135 return 'SHARED'
136 elif tier in ['B1', 'B2', 'B3', 'BASIC']:
137 return 'BASIC'
138 elif tier in ['S1', 'S2', 'S3']:
139 return 'STANDARD'
140 elif tier in ['P1', 'P2', 'P3']:
141 return 'PREMIUM'
142 elif tier in ['P1V2', 'P2V2', 'P3V2']:
143 return 'PREMIUMV2'
144 else:
145 return None
146
147
148 def appserviceplan_to_dict(plan):
149 return dict(
150 id=plan.id,
151 name=plan.name,
152 kind=plan.kind,
153 location=plan.location,
154 reserved=plan.reserved,
155 is_linux=plan.reserved,
156 provisioning_state=plan.provisioning_state,
157 status=plan.status,
158 target_worker_count=plan.target_worker_count,
159 sku=dict(
160 name=plan.sku.name,
161 size=plan.sku.size,
162 tier=plan.sku.tier,
163 family=plan.sku.family,
164 capacity=plan.sku.capacity
165 ),
166 resource_group=plan.resource_group,
167 number_of_sites=plan.number_of_sites,
168 tags=plan.tags if plan.tags else None
169 )
170
171
172 class AzureRMAppServicePlans(AzureRMModuleBase):
173 """Configuration class for an Azure RM App Service Plan resource"""
174
175 def __init__(self):
176 self.module_arg_spec = dict(
177 resource_group=dict(
178 type='str',
179 required=True
180 ),
181 name=dict(
182 type='str',
183 required=True
184 ),
185 location=dict(
186 type='str'
187 ),
188 sku=dict(
189 type='str'
190 ),
191 is_linux=dict(
192 type='bool',
193 default=False
194 ),
195 number_of_workers=dict(
196 type='str'
197 ),
198 state=dict(
199 type='str',
200 default='present',
201 choices=['present', 'absent']
202 )
203 )
204
205 self.resource_group = None
206 self.name = None
207 self.location = None
208
209 self.sku = None
210 self.is_linux = None
211 self.number_of_workers = 1
212
213 self.tags = None
214
215 self.results = dict(
216 changed=False,
217 ansible_facts=dict(azure_appserviceplan=None)
218 )
219 self.state = None
220
221 super(AzureRMAppServicePlans, self).__init__(derived_arg_spec=self.module_arg_spec,
222 supports_check_mode=True,
223 supports_tags=True)
224
225 def exec_module(self, **kwargs):
226 """Main module execution method"""
227
228 for key in list(self.module_arg_spec.keys()) + ['tags']:
229 if kwargs[key]:
230 setattr(self, key, kwargs[key])
231
232 old_response = None
233 response = None
234 to_be_updated = False
235
236 # set location
237 resource_group = self.get_resource_group(self.resource_group)
238 if not self.location:
239 self.location = resource_group.location
240
241 # get app service plan
242 old_response = self.get_plan()
243
244 # if not existing
245 if not old_response:
246 self.log("App Service plan doesn't exist")
247
248 if self.state == "present":
249 to_be_updated = True
250
251 if not self.sku:
252 self.fail('Please specify sku in plan when creation')
253
254 else:
255 # existing app service plan, do update
256 self.log("App Service Plan already exists")
257
258 if self.state == 'present':
259 self.log('Result: {0}'.format(old_response))
260
261 update_tags, newtags = self.update_tags(old_response.get('tags', dict()))
262
263 if update_tags:
264 to_be_updated = True
265 self.tags = newtags
266
267 # check if sku changed
268 if self.sku and _normalize_sku(self.sku) != _normalize_sku(old_response['sku']['size']):
269 to_be_updated = True
270
271 # check if number_of_workers changed
272 if self.number_of_workers and int(self.number_of_workers) != old_response['sku']['capacity']:
273 to_be_updated = True
274
275 if self.is_linux and self.is_linux != old_response['reserved']:
276 self.fail("Operation not allowed: cannot update reserved of app service plan.")
277
278 if old_response:
279 self.results['id'] = old_response['id']
280
281 if to_be_updated:
282 self.log('Need to Create/Update app service plan')
283 self.results['changed'] = True
284
285 if self.check_mode:
286 return self.results
287
288 response = self.create_or_update_plan()
289 self.results['id'] = response['id']
290
291 if self.state == 'absent' and old_response:
292 self.log("Delete app service plan")
293 self.results['changed'] = True
294
295 if self.check_mode:
296 return self.results
297
298 self.delete_plan()
299
300 self.log('App service plan instance deleted')
301
302 return self.results
303
304 def get_plan(self):
305 '''
306 Gets app service plan
307 :return: deserialized app service plan dictionary
308 '''
309 self.log("Get App Service Plan {0}".format(self.name))
310
311 try:
312 response = self.web_client.app_service_plans.get(resource_group_name=self.resource_group, name=self.name)
313 if response:
314 self.log("Response : {0}".format(response))
315 self.log("App Service Plan : {0} found".format(response.name))
316
317 return appserviceplan_to_dict(response)
318 except ResourceNotFoundError:
319 self.log("Didn't find app service plan {0} in resource group {1}".format(self.name, self.resource_group))
320
321 return False
322
323 def create_or_update_plan(self):
324 '''
325 Creates app service plan
326 :return: deserialized app service plan dictionary
327 '''
328 self.log("Create App Service Plan {0}".format(self.name))
329
330 try:
331 # normalize sku
332 sku = _normalize_sku(self.sku)
333
334 sku_def = SkuDescription(tier=get_sku_name(
335 sku), name=sku, capacity=self.number_of_workers)
336 plan_def = AppServicePlan(
337 location=self.location, app_service_plan_name=self.name, sku=sku_def, reserved=self.is_linux, tags=self.tags if self.tags else None)
338
339 response = self.web_client.app_service_plans.begin_create_or_update(resource_group_name=self.resource_group,
340 name=self.name,
341 app_service_plan=plan_def)
342
343 if isinstance(response, LROPoller):
344 response = self.get_poller_result(response)
345
346 self.log("Response : {0}".format(response))
347
348 return appserviceplan_to_dict(response)
349 except Exception as ex:
350 self.fail("Failed to create app service plan {0} in resource group {1}: {2}".format(self.name, self.resource_group, str(ex)))
351
352 def delete_plan(self):
353 '''
354 Deletes specified App service plan in the specified subscription and resource group.
355
356 :return: True
357 '''
358 self.log("Deleting the App service plan {0}".format(self.name))
359 try:
360 self.web_client.app_service_plans.delete(resource_group_name=self.resource_group, name=self.name)
361 except ResourceNotFoundError as e:
362 self.log('Error attempting to delete App service plan.')
363 self.fail("Error deleting the App service plan : {0}".format(str(e)))
364
365 return True
366
367
368 def main():
369 """Main execution"""
370 AzureRMAppServicePlans()
371
372
373 if __name__ == '__main__':
374 main()