Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2020 Nikhil Patne (@nikhilpatne), Sakar Mehra (@sakar97)
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_apimanagementservice
14 version_added: '1.5.0'
15 short_description: Manage Azure ApiManagementService instance
16 description:
17 - Create and delete instance of Azure ApiManagementService.
18 - Updates are not currently supported, this feature should be added in a later release.
19 options:
20 resource_group:
21 description:
22 - The name of the resource group.
23 required: true
24 type: str
25 name:
26 description:
27 - Service name.
28 required: true
29 type: str
30 location:
31 description:
32 - Location of the Api management service.
33 type: str
34 publisher_name:
35 description:
36 - Publisher name.
37 type: str
38 publisher_email:
39 description:
40 - Publisher email.
41 type: str
42 sku_name:
43 description:
44 - Name of the Sku.
45 choices:
46 - Developer
47 - Standard
48 - Premium
49 - Basic
50 - Consumption
51 type: str
52 sku_capacity:
53 description:
54 - Capacity of the SKU (number of deployed units of the SKU).
55 type: int
56 state:
57 description:
58 - Assert the state of the ApiManagementService.
59 - Use C(present) to create or update an ApiManagementService.
60 - Use C(absent) to delete an ApiManagementService.
61 type: str
62 default: present
63 choices:
64 - absent
65 - present
66
67 extends_documentation_fragment:
68 - azure.azcollection.azure
69 - azure.azcollection.azure_tags
70 author:
71 - Nikhil Patne (@nikhilpatne)
72 - Sakar Mehra (@sakar97)
73 '''
74
75 EXAMPLES = '''
76 - name: Create Api Management Service
77 azure_rm_apimanagementservice:
78 resource_group: myResourceGroup
79 name: myService
80 publisher_email: [email protected]
81 publisher_name: Publisher Name
82 sku_name: Developer
83 sku_capacity: 1
84
85 - name: Delete Api Management Service
86 azure_rm_apimanagementservice:
87 resource_group: myResourceGroup
88 name: myService
89 state: absent
90 '''
91
92 RETURN = '''
93 id:
94 description:
95 - Resource ID.
96 returned: always
97 type: str
98 sample: null
99 '''
100
101 import time
102 import json
103 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common_rest import GenericRestClient
104 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common_ext import AzureRMModuleBaseExt
105
106
107 class Actions:
108 NoAction, Create, Update, Delete = range(4)
109
110
111 class AzureRMApiManagementService(AzureRMModuleBaseExt):
112 def __init__(self):
113 self.module_arg_spec = dict(
114 resource_group=dict(
115 type='str',
116 required=True
117 ),
118 name=dict(
119 type='str',
120 required=True
121 ),
122 location=dict(
123 type='str',
124 ),
125 publisher_name=dict(
126 type='str',
127 ),
128 publisher_email=dict(
129 type='str',
130 ),
131 sku_name=dict(
132 type='str',
133 choices=['Developer',
134 'Standard',
135 'Premium',
136 'Basic',
137 'Consumption']
138 ),
139 sku_capacity=dict(
140 type='int',
141 ),
142 state=dict(
143 type='str',
144 default='present',
145 choices=['present', 'absent']
146 )
147 )
148
149 self.resource_group = None
150 self.name = None
151 self.location = None
152
153 self.results = dict(changed=False)
154 self.mgmt_client = None
155 self.state = None
156 self.url = None
157 self.status_code = [200, 201, 202]
158 self.to_do = Actions.NoAction
159
160 self.body = {}
161 self.body['properties'] = {}
162 self.body['sku'] = {}
163 self.query_parameters = {}
164 self.query_parameters['api-version'] = '2022-08-01'
165 self.header_parameters = {}
166 self.header_parameters['Content-Type'] = 'application/json; charset=utf-8'
167
168 super(AzureRMApiManagementService, self).__init__(derived_arg_spec=self.module_arg_spec,
169 supports_check_mode=True,
170 supports_tags=True)
171
172 def exec_module(self, **kwargs):
173 for key in list(self.module_arg_spec.keys()):
174 if hasattr(self, key):
175 setattr(self, key, kwargs[key])
176 elif kwargs[key] is not None:
177 if key == 'publisher_name':
178 self.body['properties']['publisherName'] = kwargs[key]
179 elif key == 'publisher_email':
180 self.body['properties']['publisherEmail'] = kwargs[key]
181 elif key == 'sku_name':
182 self.body['sku']['name'] = kwargs[key]
183 elif key == 'sku_capacity':
184 self.body['sku']['capacity'] = kwargs[key]
185 else:
186 self.body[key] = kwargs[key]
187
188 old_response = None
189 response = None
190
191 self.mgmt_client = self.get_mgmt_svc_client(GenericRestClient,
192 base_url=self._cloud_environment.endpoints.resource_manager)
193
194 resource_group = self.get_resource_group(self.resource_group)
195
196 if self.location is None:
197 self.location = resource_group.location
198
199 self.url = ('/subscriptions' +
200 '/{{ subscription_id }}' +
201 '/resourceGroups' +
202 '/{{ resource_group }}' +
203 '/providers' +
204 '/Microsoft.ApiManagement' +
205 '/service' +
206 '/{{ service_name }}')
207 self.url = self.url.replace('{{ subscription_id }}', self.subscription_id)
208 self.url = self.url.replace('{{ resource_group }}', self.resource_group)
209 self.url = self.url.replace('{{ service_name }}', self.name)
210
211 old_response = self.get_resource()
212
213 if not old_response:
214 self.log("ApiManagementService instance doesn't exist")
215
216 if self.state == 'absent':
217 self.log("Old instance didn't exist")
218 else:
219 self.to_do = Actions.Create
220 else:
221 self.log('ApiManagementService instance already exists')
222
223 if self.state == 'absent':
224 self.to_do = Actions.Delete
225 else:
226 for key in self.body.keys():
227 if key == 'properties':
228 for key in self.body['properties'].keys():
229 if self.body['properties'][key] != old_response['properties'].get(key):
230 self.to_do = Actions.Update
231 elif key == 'sku':
232 for key in self.body['sku'].keys():
233 if self.body['sku'][key] != old_response['sku'].get(key):
234 self.to_do = Actions.Update
235
236 self.body['location'] = self.location
237 if (self.to_do == Actions.Create) or (self.to_do == Actions.Update):
238 self.log('Need to Create / Update the ApiManagementService instance')
239
240 if self.check_mode:
241 self.results['changed'] = True
242 return self.results
243
244 response = self.create_update_resource()
245
246 # if not old_response:
247 self.results['changed'] = True
248 # else:
249 # self.results['changed'] = old_response.__ne__(response)
250 self.log('Creation / Update done')
251 elif self.to_do == Actions.Delete:
252 self.log('To delete ApiManagementService instance')
253 self.results['changed'] = True
254
255 if self.check_mode:
256 return self.results
257
258 self.delete_resource()
259
260 # make sure instance is actually deleted, for some Azure resources, instance is hanging around.
261 while self.get_resource():
262 time.sleep(20)
263 else:
264 self.log('ApiManagementService instance unchanged')
265 self.results['changed'] = False
266 response = old_response
267
268 if response:
269 self.results["id"] = response["id"]
270
271 return self.results
272
273 def create_update_resource(self):
274 # Creating / Updating the ApiManagementService instance.
275 try:
276 if self.to_do == Actions.Create:
277 response = self.mgmt_client.query(self.url,
278 'PUT',
279 self.query_parameters,
280 self.header_parameters,
281 self.body,
282 self.status_code,
283 600,
284 30)
285 else:
286 response = self.mgmt_client.query(self.url,
287 'PATCH',
288 self.query_parameters,
289 self.header_parameters,
290 self.body,
291 self.status_code,
292 600,
293 30)
294 except Exception as exc:
295 self.log('Error attempting to create the ApiManagementService instance.')
296 self.fail('Error creating the ApiManagementService instance: {0}'.format(str(exc)))
297
298 if hasattr(response, 'body'):
299 response = json.loads(response.body())
300 elif hasattr(response, 'context'):
301 response = response.context['deserialized_data']
302 else:
303 self.fail("Create or Updating fail, no match message return, return info as {0}".format(response))
304
305 return response
306
307 def delete_resource(self):
308 # Deleting the ApiManagementService instance.
309 try:
310 response = self.mgmt_client.query(self.url,
311 'DELETE',
312 self.query_parameters,
313 self.header_parameters,
314 None,
315 self.status_code,
316 600,
317 30)
318 except Exception as e:
319 self.log('Error attempting to delete the ApiManagementService instance.')
320 self.fail('Error deleting the ApiManagementService instance: {0}'.format(str(e)))
321
322 return True
323
324 def get_resource(self):
325 # Checking if the ApiManagementService instance is present
326 found = False
327 try:
328 response = self.mgmt_client.query(self.url,
329 'GET',
330 self.query_parameters,
331 self.header_parameters,
332 None,
333 self.status_code,
334 600,
335 30)
336 found = True
337 self.log("Response : {0}".format(response))
338 except Exception as e:
339 self.log('Did not find the ApiManagementService instance.')
340 if found is True:
341 return json.loads(response.body())
342
343 return False
344
345
346 def main():
347 AzureRMApiManagementService()
348
349
350 if __name__ == '__main__':
351 main()