Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2020 Sakar Mehra (@sakar97), Nikhil Patne (@nikhilpatne)
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
9 __metaclass__ = type
10
11
12 DOCUMENTATION = '''
13 ---
14 module: azure_rm_apimanagement
15 version_added: "1.6.0"
16 short_description: Manage Azure api instances
17 description:
18 - Create azure api instance.
19 - Update the existing azure api instance.
20 - Delete azure api instance.
21
22 options:
23 resource_group:
24 description:
25 - The name of the resource group.
26 required: true
27 type: str
28 service_name:
29 description:
30 - The name of the API Management service.
31 required: true
32 type: str
33 api_id:
34 description:
35 - API revision identifier. It must be unique in the current API Management service instance.
36 required: true
37 type: str
38 description:
39 description:
40 - Description of the API.
41 type: str
42 authentication_settings:
43 description:
44 - Collection of authentication settings included into this API.
45 type: dict
46 suboptions:
47 o_auth2:
48 description:
49 - OAuth2 Authentication settings
50 type: dict
51 suboptions:
52 authorization_server_id:
53 description:
54 - OAuth authorization server identifier.
55 type: str
56 scope:
57 description:
58 - operations scope.
59 type: str
60 openid:
61 description:
62 - OpenID Connect Authentication Settings
63 type: dict
64 suboptions:
65 openid_provider_id:
66 description:
67 - OAuth authorization server identifier.
68 type: str
69 bearer_token_sending_methods:
70 description:
71 - How to send token to the server.
72 type: list
73 elements: str
74 choices:
75 - authorizationHeader
76 - query
77 subscription_key_parameter_names:
78 description:
79 - Protocols over which API is made available.
80 type: dict
81 suboptions:
82 header:
83 description:
84 - Subscription key header name.
85 type: str
86 query:
87 description:
88 - Subscription key query string parameter name.
89 type: str
90 type:
91 description:
92 - Type of API
93 type: str
94 choices:
95 - http
96 - soap
97 api_revision:
98 description:
99 - Describes the Revision of the Api.
100 - If no value is provided, default revision 1 is created
101 type: str
102 api_version:
103 description:
104 - Indicates the Version identifier of the API if the API is versioned
105 type: str
106 is_current:
107 description:
108 - Indicates if API revision is current api revision.
109 type: bool
110 api_revision_description:
111 description:
112 - Description of the Api Revision.
113 type: str
114 api_version_description:
115 description:
116 - Description of the Api Version.
117 type: str
118 api_version_set_id:
119 description:
120 - A resource identifier for the related ApiVersionSet.
121 type: str
122 subscription_required:
123 description:
124 - Specifies whether an API or Product subscription is required for accessing the API.
125 type: bool
126 source_api_id:
127 description:
128 - API identifier of the source API.
129 type: str
130 display_name:
131 description:
132 - API Name to be displayed. It must be 1 to 300 characters long.
133 type: str
134 service_url:
135 description:
136 - Absolute URL of the backend service implementing this API
137 - Cannot be more than 2000 characters long.
138 type: str
139 path:
140 description:
141 - Relative URL uniquely identifying this API.
142 type: str
143 protocols:
144 description:
145 - Describes on which protocols the operations in this API can be invoked.
146 type: list
147 elements: str
148 choices:
149 - http
150 - https
151 api_version_set:
152 description:
153 - Version set details
154 type: dict
155 suboptions:
156 id:
157 description:
158 - Identifier for existing API Version Set
159 - Omit this value to create a new Version Set.
160 type: str
161 name:
162 description:
163 - The display Name of the API Version Set.
164 type: str
165 description:
166 description:
167 - Description of API Version Set.
168 type: str
169 versioning_scheme:
170 description:
171 - An value that determines where the API Version identifer will be located in a HTTP request.
172 type: str
173 choices:
174 - Segment
175 - Query
176 - Header
177 version_query_name:
178 description:
179 - Name of query parameter that indicates the API Version if versioningScheme is set to `query`.
180 type: str
181 version_header_name:
182 description:
183 - Name of HTTP header parameter that indicates the API Version if versioningScheme is set to `header`.
184 type: str
185 value:
186 description:
187 - Content value when Importing an API.
188 type: str
189 format:
190 description:
191 - Format of the Content in which the API is getting imported.
192 type: str
193 choices:
194 - wadl-xml
195 - wadl-link-json
196 - swagger-json
197 - swagger-link-json
198 - wsdl
199 - wsdl-link
200 - openapi
201 - openapi+json
202 - openapi-link
203 wsdl_selector:
204 description:
205 - Criteria to limit import of WSDL to a subset of the document.
206 type: dict
207 suboptions:
208 wsdl_service_name:
209 description:
210 - Name of service to import from WSDL.
211 type: str
212 wsdl_endpoint_name:
213 description:
214 - Name of endpoint(port) to import from WSDL.
215 type: str
216 api_type:
217 description:
218 - Type of Api to create.
219 - C(http) creates a SOAP to REST API.
220 - C(soap) creates a SOAP pass-through API.
221 type: str
222 choices:
223 - soap
224 - http
225 state:
226 description:
227 - State of the Api.
228 - Use C(present) to create or update an Api and C(absent) to delete it.
229 type: str
230 default: present
231 choices:
232 - absent
233 - present
234
235 extends_documentation_fragment:
236 - azure.azcollection.azure
237 - azure.azcollection.azure_tags
238
239 author:
240 - Sakar Mehra (@sakar97)
241 - Nikhil Patne (@nikhilpatne)
242
243 '''
244
245 EXAMPLES = '''
246 - name: Create a new API instance
247 azure_rm_apimanagement:
248 resource_group: 'myResourceGroup'
249 service_name: myService
250 api_id: testApi
251 description: testDescription
252 display_name: TestAPI
253 service_url: 'http://testapi.example.net/api'
254 path: myapiPath
255 protocols:
256 - https
257 - name: Update an existing API instance.
258 azure_rm_apimanagement:
259 resource_group: myResourceGroup
260 service_name: myService
261 api_id: testApi
262 display_name: newTestAPI
263 service_url: 'http://testapi.example.net/api'
264 path: myapiPath
265 protocols:
266 - https
267 - name: ApiManagementDeleteApi
268 azure_rm_apimanagement:
269 resource_group: myResourceGroup
270 service_name: myService
271 api_id: testApi
272 state: absent
273 '''
274
275 RETURN = \
276 '''
277 id:
278 description:
279 - Resource ID.
280 returned: always
281 type: str
282 sample: null
283 '''
284
285 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common_rest import GenericRestClient
286 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common_ext import AzureRMModuleBaseExt
287 import json
288
289
290 class Actions:
291 NoAction, Create, Update, Delete = range(4)
292
293
294 class AzureApiManagement(AzureRMModuleBaseExt):
295 def __init__(self):
296 self.module_arg_spec = dict(
297 resource_group=dict(
298 type='str',
299 required=True
300 ),
301 service_name=dict(
302 type='str',
303 required=True
304 ),
305 api_id=dict(
306 type='str',
307 required=True
308 ),
309 description=dict(
310 type='str',
311 ),
312 authentication_settings=dict(
313 type='dict',
314 options=dict(
315 o_auth2=dict(
316 type='dict',
317 options=dict(
318 authorization_server_id=dict(
319 type='str',
320 ),
321 scope=dict(
322 type='str',
323 )
324 )
325 ),
326 openid=dict(
327 type='dict',
328 options=dict(
329 openid_provider_id=dict(
330 type='str',
331 ),
332 bearer_token_sending_methods=dict(
333 type='list',
334 elements='str',
335 choices=['authorizationHeader', 'query']
336 )
337 )
338 )
339 )
340 ),
341 subscription_key_parameter_names=dict(
342 type='dict',
343 no_log=True,
344 options=dict(
345 header=dict(
346 type='str',
347 required=False
348 ),
349 query=dict(
350 type='str',
351 required=False
352 )
353 )
354 ),
355 type=dict(
356 type='str',
357 choices=['http', 'soap']
358 ),
359 api_revision=dict(
360 type='str',
361 ),
362 api_version=dict(
363 type='str',
364 ),
365 is_current=dict(
366 type='bool',
367 ),
368 api_revision_description=dict(
369 type='str',
370 ),
371 api_version_description=dict(
372 type='str',
373 ),
374 api_version_set_id=dict(
375 type='str',
376 ),
377 subscription_required=dict(
378 type='bool',
379 ),
380 source_api_id=dict(
381 type='str',
382 ),
383 display_name=dict(
384 type='str',
385 ),
386 service_url=dict(
387 type='str',
388 ),
389 path=dict(
390 type='str',
391 ),
392 protocols=dict(
393 type='list',
394 elements='str',
395 choices=['http',
396 'https']
397 ),
398 api_version_set=dict(
399 type='dict',
400 options=dict(
401 id=dict(
402 type='str'
403 ),
404 name=dict(
405 type='str'
406 ),
407 description=dict(
408 type='str'
409 ),
410 versioning_scheme=dict(
411 type='str',
412 choices=['Segment',
413 'Query',
414 'Header']
415 ),
416 version_query_name=dict(
417 type='str',
418 ),
419 version_header_name=dict(
420 type='str',
421 )
422 )
423 ),
424 value=dict(
425 type='str',
426 ),
427 format=dict(
428 type='str',
429 choices=['wadl-xml',
430 'wadl-link-json',
431 'swagger-json',
432 'swagger-link-json',
433 'wsdl',
434 'wsdl-link',
435 'openapi',
436 'openapi+json',
437 'openapi-link']
438 ),
439 wsdl_selector=dict(
440 type='dict',
441 options=dict(
442 wsdl_service_name=dict(
443 type='str',
444 ),
445 wsdl_endpoint_name=dict(
446 type='str',
447 )
448 )
449 ),
450 api_type=dict(
451 type='str',
452 choices=['http', 'soap']
453 ),
454 state=dict(
455 type='str',
456 default='present',
457 choices=['present', 'absent']
458 )
459 )
460
461 self.resource_group = None
462 self.service_name = None
463 self.api_id = None
464
465 self.results = dict(changed=False)
466 self.mgmt_client = None
467 self.state = None
468 self.url = None
469 self.status_code = [200, 201, 202]
470 self.to_do = Actions.NoAction
471
472 self.body = {}
473 self.body['properties'] = {}
474 self.query_parameters = {}
475 self.query_parameters['api-version'] = '2022-08-01'
476 self.header_parameters = {}
477 self.header_parameters['Content-Type'] = 'application/json; charset=utf-8'
478
479 super(AzureApiManagement, self).__init__(derived_arg_spec=self.module_arg_spec,
480 supports_check_mode=True,
481 supports_tags=True)
482
483 def get_url(self):
484 return '/subscriptions' + '/' + self.subscription_id \
485 + '/resourceGroups' + '/' + self.resource_group \
486 + '/providers' + '/Microsoft.ApiManagement' + '/service' \
487 + '/' + self.service_name + '/apis' + '/' + self.api_id
488
489 def exec_module(self, **kwargs):
490 for key in list(self.module_arg_spec.keys()):
491 if hasattr(self, key):
492 setattr(self, key, kwargs[key])
493 elif kwargs[key] is not None:
494 if key == 'description':
495 self.body['properties']['description'] = kwargs[key]
496 elif key == 'authentication_settings':
497 self.body['properties']['authenticationSettings'] = {}
498 if kwargs[key].get('o_auth2') is not None:
499 self.body['properties']['authenticationSettings']['oAuth2'] = {}
500 for item in kwargs[key]['o_auth2'].keys():
501 if item == 'authorization_server_id':
502 authorization_id = kwargs[key]['o_auth2']['authorization_server_id']
503 self.body['properties']['authenticationSettings']['oAuth2']['authorizationServerId'] = authorization_id
504 elif item == 'scope':
505 self.body['properties']['authenticationSettings']['oAuth2']['scope'] = kwargs[key]['o_auth2']['scope']
506 elif kwargs[key].get('openid') is not None:
507 self.body['properties']['authenticationSettings']['openid'] = {}
508 for item in kwargs[key]['openid'].keys():
509 if item == 'openid_provider_id' and kwargs[key]['openid'].get('openid_provider_id') is not None:
510 openid_pro = kwargs[key]['openid'].get('openid_provider_id')
511 self.body['properties']['authenticationSettings']['openid']['openidProviderId'] = openid_pro
512 elif item == 'bearer_token_sending_methods' and kwargs[key]['openid'].get('bearer_token_sending_methods') is not None:
513 bearer_token = kwargs[key]['openid']['bearer_token_sending_methods']
514 self.body['properties']['authenticationSettings']['openid']['bearerTokenSendingMethods'] = bearer_token
515 elif key == 'subscription_key_parameter_names':
516 self.body['properties']['subscriptionKeyParameterNames'] = kwargs[key]
517 elif key == 'type':
518 self.body['properties']['type'] = kwargs[key]
519 elif key == 'api_revision':
520 self.body['properties']['apiRevision'] = kwargs[key]
521 elif key == 'api_version':
522 self.body['properties']['apiVersion'] = kwargs[key]
523 elif key == 'is_current':
524 self.body['properties']['isCurrent'] = kwargs[key]
525 elif key == 'api_revision_description':
526 self.body['properties']['apiRevisionDescription'] = kwargs[key]
527 elif key == 'api_version_description':
528 self.body['properties']['apiVersionDescription'] = kwargs[key]
529 elif key == 'api_version_set_id':
530 self.body['properties']['apiVersionSetId'] = kwargs[key]
531 elif key == 'subscription_required':
532 self.body['properties']['subscriptionRequired'] = kwargs[key]
533 elif key == 'source_api_id':
534 self.body['properties']['sourceApiId'] = kwargs[key]
535 elif key == 'display_name':
536 self.body['properties']['displayName'] = kwargs[key]
537 elif key == 'service_url':
538 self.body['properties']['serviceUrl'] = kwargs[key]
539 elif key == 'protocols':
540 self.body['properties']['protocols'] = kwargs[key]
541 elif key == 'api_version_set':
542 self.body['properties']['apiVersionSet'] = {}
543 for item in kwargs[key].keys():
544 if item == 'versioning_scheme':
545 self.body['properties']['apiVersionSet'] = kwargs[key].get('versioning_scheme')
546 elif item == 'version_query_name':
547 self.body['properties']['versionQueryName'] = kwargs[key].get('version_query_name')
548 elif item == 'version_header_name':
549 self.body['properties']['versionHeaderName'] = kwargs[key].get('version_header_name')
550 else:
551 self.body['properties'][item] = kwargs[key].get(item)
552 elif key == 'wsdl_selector':
553 self.body['properties']['wsdlSelector'] = {}
554 for item in kwargs[key].keys():
555 if item == 'wsdl_service_name':
556 self.body['properties']['wsdlSelector']['wsdlServiceName'] = kwargs[key].get(item)
557 if item == 'wsdl_endpoint_name':
558 self.body['properties']['wsdlSelector']['wsdlEndpointName'] = kwargs[key].get(item)
559 elif key == 'api_type':
560 self.body['properties']['apiType'] = kwargs[key]
561 else:
562 self.body['properties'][key] = kwargs[key]
563
564 self.url = self.get_url()
565 old_response = None
566 response = None
567
568 self.mgmt_client = self.get_mgmt_svc_client(GenericRestClient,
569 base_url=self._cloud_environment.endpoints.resource_manager)
570
571 old_response = self.get_resource()
572
573 if not old_response:
574 self.log("Api instance does not exist in the given service.")
575 if self.state == 'present':
576 self.to_do = Actions.Create
577 else:
578 self.log("Old instance didn't exist")
579 else:
580 self.log("Api instance already exists in the given service.")
581 if self.state == 'absent':
582 self.to_do = Actions.Delete
583 else:
584 if self.body['properties'].get('description') is not None and \
585 self.body['properties']['description'] != old_response['properties']['description']:
586 self.to_do = Actions.Update
587 elif self.body['properties'].get('authenticationSettings') is not None:
588 if old_response['properties'].get('authenticationSettings') is None:
589 self.to_do = Actions.Update
590 elif (self.body['properties']['authenticationSettings'].get('oAuth2') is not None and
591 self.body['properties']['authenticationSettings']['oAuth2'] != old_response['properties']['authenticationSettings'].get('oAuth2')):
592 self.to_do = Actions.Update
593 elif (self.body['properties']['authenticationSettings'].get('openid') is not None and
594 self.body['properties']['authenticationSettings']['openid'] != old_response['properties']['authenticationSettings'].get('openid')):
595 self.to_do = Actions.Update
596 elif self.body['properties'].get('subscriptionKeyParameterNames') is not None:
597 tt = old_response['properties']
598 if old_response['properties'].get('subscriptionKeyParameterNames') is None:
599 self.to_do = Actions.Update
600 elif (not all(self.body['properties']['subscriptionKeyParameterNames'].get(item) == tt['subscriptionKeyParameterNames'].get(item)
601 for item in self.body['properties']['subscriptionKeyParameterNames'].keys())):
602 self.to_do = Actions.Update
603 elif (self.body['properties'].get('apiRevision') is not None and
604 self.body['properties']['apiRevision'] != old_response['properties'].get('apiRevision')):
605 self.to_do = Actions.Update
606 elif (self.body['properties'].get('apiVersion') is not None and
607 self.body['properties']['apiVersion'] != old_response['properties'].get('apiVersion')):
608 self.to_do == Actions.Update
609 elif (self.body['properties'].get('isCurrent') is not None and
610 self.body['properties']['isCurrent'] != old_response['properties'].get('isCurrent')):
611 self.to_do = Actions.Update
612 elif (self.body['properties'].get('apiRevisionDescription') is not None and self.body['properties']['apiRevisionDescription'] !=
613 old_response['properties'].get('apiRevisionDescription')):
614 self.to_do = Actions.Update
615 elif (self.body['properties'].get('apiVersionDescription') is not None and
616 self.body['properties']['apiVersionDescription'] != old_response['properties'].get('apiVersionDescription')):
617 self.to_do = Actions.Update
618 elif (self.body['properties'].get('apiVersionSetId') is not None and
619 self.body['properties']['apiVersionSetId'] != old_response['properties'].get('apiVersionSetId')):
620 self.to_do = Actions.Update
621 elif (self.body['properties'].get('subscriptionRequired') is not None and
622 self.body['properties']['subscriptionRequired'] != old_response['properties'].get('subscriptionRequired')):
623 self.to_do = Actions.Update
624 elif (self.body['properties'].get('sourceApiId') is not None and
625 self.body['properties']['sourceApiId'] != old_response['properties'].get('sourceApiId')):
626 self.to_do = Actions.Update
627 elif (self.body['properties'].get('displayName') is not None and
628 self.body['properties']['displayName'] != old_response['properties'].get('displayName')):
629 self.to_do = Actions.Update
630 elif (self.body['properties'].get('serviceUrl') is not None and
631 self.body['properties']['serviceUrl'] != old_response['properties'].get('serviceUrl')):
632 self.to_do = Actions.Update
633 elif self.body['properties'].get('path') is not None and self.body['properties']['path'] != old_response['properties'].get('path'):
634 self.to_do = Actions.Update
635 elif (self.body['properties'].get('protocols') is not None and
636 self.body['properties']['protocols'] != old_response['properties'].get('protocols')):
637 self.to_do = Actions.Update
638 elif self.body['properties'].get('type') is not None and self.body['properties']['type'] != old_response['properties'].get('type'):
639 self.to_do = Actions.Update
640 elif self.body['properties'].get('apiType') is not None and self.body['properties']['apiType'] != old_response['properties'].get('apiType'):
641 self.to_do = Actions.Update
642 elif self.body['properties'].get('value') is not None and self.body['properties']['value'] != old_response['properties'].get('value'):
643 self.to_do = Actions.Update
644 elif self.body['properties'].get('format') is not None and self.body['properties']['format'] != old_response['properties'].get('format'):
645 self.to_do = Actions.Update
646 elif (self.body['properties'].get('wsdlSelector') is not None and
647 not all(self.body['properties']['wsdlSelector'][item] == old_response['properties']['wsdlSelector'].get(item)
648 for item in self.body['properties']['wsdlSelector'].keys())):
649 self.to_do = Actions.Update
650 elif (self.body['properties'].get('apiVersionSet') is not None and
651 not all(self.body['properties']['apiVersionSet'][item] == old_response['properties']['apiVersionSet'].get(item)
652 for item in self.body['properties']['apiVersionSet'].keys())):
653 self.to_do = Actions.Update
654
655 if (self.to_do == Actions.Create) or (self.to_do == Actions.Update):
656 self.log('Create and Update the Api instance.')
657
658 if self.check_mode:
659 self.results['changed'] = True
660 return self.results
661
662 response = self.create_and_update_resource()
663 self.results['changed'] = True
664
665 elif self.to_do == Actions.Delete:
666 self.log('Api instance deleted.')
667
668 if self.check_mode:
669 self.results['changed'] = True
670 return self.results
671
672 self.delete_resource()
673 self.results['changed'] = True
674 else:
675 self.log('No change in Api instance.')
676 self.results['changed'] = False
677 response = old_response
678
679 if response:
680 self.results["id"] = response["id"]
681
682 return self.results
683
684 # This function will create and update resource on the api management service.
685 def create_and_update_resource(self):
686
687 try:
688 response = self.mgmt_client.query(
689 self.url,
690 'PUT',
691 self.query_parameters,
692 self.header_parameters,
693 self.body,
694 self.status_code,
695 600,
696 30,
697 )
698 except Exception as exc:
699 self.log('Error while creating/updating the Api instance.')
700 self.fail('Error creating the Api instance: {0}'.format(str(exc)))
701 if hasattr(response, 'body'):
702 response = json.loads(response.body())
703 elif hasattr(response, 'context'):
704 response = response.context['deserialized_data']
705 else:
706 self.fail("Create or Updating fail, no match message return, return info as {0}".format(response))
707
708 return response
709
710 def delete_resource(self):
711 isDeleted = False
712 try:
713 response = self.mgmt_client.query(
714 self.url,
715 'DELETE',
716 self.query_parameters,
717 self.header_parameters,
718 None,
719 self.status_code,
720 600,
721 30,
722 )
723 isDeleted = True
724 except Exception as e:
725 self.log('Error attempting to delete the Api instance.')
726 self.fail('Error deleting the Api instance: {0}'.format(str(e)))
727
728 return isDeleted
729
730 def get_resource(self):
731 isFound = False
732 try:
733 response = self.mgmt_client.query(
734 self.url,
735 'GET',
736 self.query_parameters,
737 self.header_parameters,
738 None,
739 self.status_code,
740 600,
741 30,
742 )
743 isFound = True
744 response = json.loads(response.body())
745 self.log("Response : {0}".format(response))
746 except Exception as e:
747 self.log('Could not find the Api instance from the given parameters.')
748 if isFound is True:
749 return response
750 return False
751
752
753 def main():
754 AzureApiManagement()
755
756
757 if __name__ == '__main__':
758 main()