Debian Codegraph @

ansible_collections/community/general/plugins/modules/manageiq_provider.py

raw
1 #!/usr/bin/python
2 # Copyright (c) 2017, Daniel Korn <[email protected]>
3 # Copyright (c) 2017, Yaacov Zamir <[email protected]>
4 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
5 # SPDX-License-Identifier: GPL-3.0-or-later
6
7 from __future__ import annotations
8
9 DOCUMENTATION = r"""
10 module: manageiq_provider
11 short_description: Management of provider in ManageIQ
12 extends_documentation_fragment:
13 - community.general._manageiq
14 - community.general._attributes
15
16 author: Daniel Korn (@dkorn)
17 description:
18 - The manageiq_provider module supports adding, updating, and deleting provider in ManageIQ.
19 attributes:
20 check_mode:
21 support: none
22 diff_mode:
23 support: none
24
25 options:
26 state:
27 type: str
28 description:
29 - V(absent) - provider should not exist,
30 - V(present) - provider should be present,
31 - V(refresh) - provider is refreshed.
32 choices: ['absent', 'present', 'refresh']
33 default: 'present'
34 name:
35 type: str
36 description: The provider's name.
37 required: true
38 type:
39 type: str
40 description: The provider's type.
41 choices: ['Openshift', 'Amazon', 'oVirt', 'VMware', 'Azure', 'Director', 'OpenStack', 'GCE']
42 zone:
43 type: str
44 description: The ManageIQ zone name that manages the provider.
45 default: 'default'
46 provider_region:
47 type: str
48 description: The provider region name to connect to (for example AWS region for Amazon).
49 host_default_vnc_port_start:
50 type: str
51 description: The first port in the host VNC range.
52 host_default_vnc_port_end:
53 type: str
54 description: The last port in the host VNC range.
55 subscription:
56 type: str
57 description: Microsoft Azure subscription ID.
58 project:
59 type: str
60 description: Google Compute Engine Project ID.
61 azure_tenant_id:
62 type: str
63 description: Tenant ID. Defaults to V(null).
64 aliases: [keystone_v3_domain_id]
65 tenant_mapping_enabled:
66 type: bool
67 default: false
68 description: Whether to enable mapping of existing tenants.
69 api_version:
70 type: str
71 description: The OpenStack Keystone API version.
72 choices: ['v2', 'v3']
73
74 provider:
75 description: Default endpoint connection information, required if state is true.
76 type: dict
77 suboptions:
78 hostname:
79 type: str
80 description: The provider's API hostname.
81 required: true
82 port:
83 type: int
84 description: The provider's API port.
85 userid:
86 type: str
87 description: Provider's API endpoint authentication userid.
88 password:
89 type: str
90 description: Provider's API endpoint authentication password.
91 auth_key:
92 type: str
93 description: Provider's API endpoint authentication bearer token.
94 validate_certs:
95 description: Whether SSL certificates should be verified for HTTPS requests (deprecated).
96 type: bool
97 default: true
98 aliases: [verify_ssl]
99 security_protocol:
100 type: str
101 description: How SSL certificates should be used for HTTPS requests.
102 choices: ['ssl-with-validation', 'ssl-with-validation-custom-ca', 'ssl-without-validation', 'non-ssl']
103 certificate_authority:
104 type: str
105 description: The CA bundle string with custom certificates.
106 path:
107 type: str
108 description:
109 - TODO needs documentation.
110 project:
111 type: str
112 description:
113 - TODO needs documentation.
114 role:
115 type: str
116 description:
117 - TODO needs documentation.
118 subscription:
119 type: str
120 description:
121 - TODO needs documentation.
122 uid_ems:
123 type: str
124 description:
125 - TODO needs documentation.
126 metrics:
127 description: Metrics endpoint connection information.
128 type: dict
129 suboptions:
130 hostname:
131 type: str
132 description: The provider's API hostname.
133 required: true
134 port:
135 type: int
136 description: The provider's API port.
137 userid:
138 type: str
139 description: Provider's API endpoint authentication userid.
140 password:
141 type: str
142 description: Provider's API endpoint authentication password.
143 auth_key:
144 type: str
145 description: Provider's API endpoint authentication bearer token.
146 validate_certs:
147 description: Whether SSL certificates should be verified for HTTPS requests (deprecated).
148 type: bool
149 default: true
150 aliases: [verify_ssl]
151 security_protocol:
152 type: str
153 choices: ['ssl-with-validation', 'ssl-with-validation-custom-ca', 'ssl-without-validation', 'non-ssl']
154 description: How SSL certificates should be used for HTTPS requests.
155 certificate_authority:
156 type: str
157 description: The CA bundle string with custom certificates.
158 path:
159 type: str
160 description: Database name for oVirt metrics. Defaults to V(ovirt_engine_history).
161 project:
162 type: str
163 description:
164 - TODO needs documentation.
165 role:
166 type: str
167 description:
168 - TODO needs documentation.
169 subscription:
170 type: str
171 description:
172 - TODO needs documentation.
173 uid_ems:
174 type: str
175 description:
176 - TODO needs documentation.
177 alerts:
178 description: Alerts endpoint connection information.
179 type: dict
180 suboptions:
181 hostname:
182 type: str
183 description: The provider's API hostname.
184 required: true
185 port:
186 type: int
187 description: The provider's API port.
188 userid:
189 type: str
190 description: Provider's API endpoint authentication userid. Defaults to V(null).
191 password:
192 type: str
193 description: Provider's API endpoint authentication password. Defaults to V(null).
194 auth_key:
195 type: str
196 description: Provider's API endpoint authentication bearer token. Defaults to V(null).
197 validate_certs:
198 type: bool
199 description: Whether SSL certificates should be verified for HTTPS requests (deprecated). Defaults to V(true).
200 default: true
201 aliases: [verify_ssl]
202 security_protocol:
203 type: str
204 choices: ['ssl-with-validation', 'ssl-with-validation-custom-ca', 'ssl-without-validation', 'non-ssl']
205 description: How SSL certificates should be used for HTTPS requests. Defaults to V(null).
206 certificate_authority:
207 type: str
208 description: The CA bundle string with custom certificates. Defaults to V(null).
209 path:
210 type: str
211 description:
212 - TODO needs documentation.
213 project:
214 type: str
215 description:
216 - TODO needs documentation.
217 role:
218 type: str
219 description:
220 - TODO needs documentation.
221 subscription:
222 type: str
223 description:
224 - TODO needs documentation.
225 uid_ems:
226 type: str
227 description:
228 - TODO needs documentation.
229 ssh_keypair:
230 description: SSH key pair used for SSH connections to all hosts in this provider.
231 type: dict
232 suboptions:
233 hostname:
234 type: str
235 description: Director hostname.
236 required: true
237 userid:
238 type: str
239 description: SSH username.
240 auth_key:
241 type: str
242 description: SSH private key.
243 validate_certs:
244 description:
245 - Whether certificates should be verified for connections.
246 type: bool
247 default: true
248 aliases: [verify_ssl]
249 security_protocol:
250 type: str
251 choices: ['ssl-with-validation', 'ssl-with-validation-custom-ca', 'ssl-without-validation', 'non-ssl']
252 description:
253 - TODO needs documentation.
254 certificate_authority:
255 type: str
256 description:
257 - TODO needs documentation.
258 password:
259 type: str
260 description:
261 - TODO needs documentation.
262 path:
263 type: str
264 description:
265 - TODO needs documentation.
266 project:
267 type: str
268 description:
269 - TODO needs documentation.
270 role:
271 type: str
272 description:
273 - TODO needs documentation.
274 subscription:
275 type: str
276 description:
277 - TODO needs documentation.
278 uid_ems:
279 type: str
280 description:
281 - TODO needs documentation.
282 port:
283 type: int
284 description:
285 - TODO needs documentation.
286 """
287
288 EXAMPLES = r"""
289 - name: Create a new provider in ManageIQ ('Hawkular' metrics)
290 community.general.manageiq_provider:
291 name: 'EngLab'
292 type: 'OpenShift'
293 state: 'present'
294 provider:
295 auth_key: 'topSecret'
296 hostname: 'example.com'
297 port: 8443
298 validate_certs: true
299 security_protocol: 'ssl-with-validation-custom-ca'
300 certificate_authority: |
301 -----BEGIN CERTIFICATE-----
302 FAKECERTsdKgAwI...
303 -----END CERTIFICATE-----
304 metrics:
305 auth_key: 'topSecret'
306 role: 'hawkular'
307 hostname: 'example.com'
308 port: 443
309 validate_certs: true
310 security_protocol: 'ssl-with-validation-custom-ca'
311 certificate_authority: |
312 -----BEGIN CERTIFICATE-----
313 FAKECERTsdKgAwI...
314 -----END CERTIFICATE-----
315 manageiq_connection:
316 url: 'https://127.0.0.1:80'
317 username: 'admin'
318 password: 'password'
319 validate_certs: true
320
321
322 - name: Update an existing provider named 'EngLab' (defaults to 'Prometheus' metrics)
323 community.general.manageiq_provider:
324 name: 'EngLab'
325 type: 'Openshift'
326 state: 'present'
327 provider:
328 auth_key: 'topSecret'
329 hostname: 'next.example.com'
330 port: 8443
331 validate_certs: true
332 security_protocol: 'ssl-with-validation-custom-ca'
333 certificate_authority: |
334 -----BEGIN CERTIFICATE-----
335 FAKECERTsdKgAwI...
336 -----END CERTIFICATE-----
337 metrics:
338 auth_key: 'topSecret'
339 hostname: 'next.example.com'
340 port: 443
341 validate_certs: true
342 security_protocol: 'ssl-with-validation-custom-ca'
343 certificate_authority: |
344 -----BEGIN CERTIFICATE-----
345 FAKECERTsdKgAwI...
346 -----END CERTIFICATE-----
347 manageiq_connection:
348 url: 'https://127.0.0.1'
349 username: 'admin'
350 password: 'password'
351 validate_certs: true
352
353
354 - name: Delete a provider in ManageIQ
355 community.general.manageiq_provider:
356 name: 'EngLab'
357 type: 'Openshift'
358 state: 'absent'
359 manageiq_connection:
360 url: 'https://127.0.0.1'
361 username: 'admin'
362 password: 'password'
363 validate_certs: true
364
365
366 - name: Create a new Amazon provider in ManageIQ using token authentication
367 community.general.manageiq_provider:
368 name: 'EngAmazon'
369 type: 'Amazon'
370 state: 'present'
371 provider:
372 hostname: 'amazon.example.com'
373 userid: 'hello'
374 password: 'world'
375 manageiq_connection:
376 url: 'https://127.0.0.1'
377 token: 'VeryLongToken'
378 validate_certs: true
379
380
381 - name: Create a new oVirt provider in ManageIQ
382 community.general.manageiq_provider:
383 name: 'RHEV'
384 type: 'oVirt'
385 state: 'present'
386 provider:
387 hostname: 'rhev01.example.com'
388 userid: 'admin@internal'
389 password: 'password'
390 validate_certs: true
391 certificate_authority: |
392 -----BEGIN CERTIFICATE-----
393 FAKECERTsdKgAwI...
394 -----END CERTIFICATE-----
395 metrics:
396 hostname: 'metrics.example.com'
397 path: 'ovirt_engine_history'
398 userid: 'user_id_metrics'
399 password: 'password_metrics'
400 validate_certs: true
401 certificate_authority: |
402 -----BEGIN CERTIFICATE-----
403 FAKECERTsdKgAwI...
404 -----END CERTIFICATE-----
405 manageiq_connection:
406 url: 'https://127.0.0.1'
407 username: 'admin'
408 password: 'password'
409 validate_certs: true
410
411 - name: Create a new VMware provider in ManageIQ
412 community.general.manageiq_provider:
413 name: 'EngVMware'
414 type: 'VMware'
415 state: 'present'
416 provider:
417 hostname: 'vcenter.example.com'
418 host_default_vnc_port_start: 5800
419 host_default_vnc_port_end: 5801
420 userid: 'root'
421 password: 'password'
422 manageiq_connection:
423 url: 'https://127.0.0.1'
424 token: 'VeryLongToken'
425 validate_certs: true
426
427 - name: Create a new Azure provider in ManageIQ
428 community.general.manageiq_provider:
429 name: 'EngAzure'
430 type: 'Azure'
431 provider_region: 'northeurope'
432 subscription: 'e272bd74-f661-484f-b223-88dd128a4049'
433 azure_tenant_id: 'e272bd74-f661-484f-b223-88dd128a4048'
434 state: 'present'
435 provider:
436 hostname: 'azure.example.com'
437 userid: 'e272bd74-f661-484f-b223-88dd128a4049'
438 password: 'password'
439 manageiq_connection:
440 url: 'https://cf-6af0.rhpds.opentlc.com'
441 username: 'admin'
442 password: 'password'
443 validate_certs: true
444
445 - name: Create a new OpenStack Director provider in ManageIQ with rsa keypair
446 community.general.manageiq_provider:
447 name: 'EngDirector'
448 type: 'Director'
449 api_version: 'v3'
450 state: 'present'
451 provider:
452 hostname: 'director.example.com'
453 userid: 'admin'
454 password: 'password'
455 security_protocol: 'ssl-with-validation'
456 validate_certs: 'true'
457 certificate_authority: |
458 -----BEGIN CERTIFICATE-----
459 FAKECERTsdKgAwI...
460 -----END CERTIFICATE-----
461 ssh_keypair:
462 hostname: director.example.com
463 userid: heat-admin
464 auth_key: 'SecretSSHPrivateKey'
465
466 - name: Create a new OpenStack provider in ManageIQ with amqp metrics
467 community.general.manageiq_provider:
468 name: 'EngOpenStack'
469 type: 'OpenStack'
470 api_version: 'v3'
471 state: 'present'
472 provider_region: 'europe'
473 tenant_mapping_enabled: 'False'
474 keystone_v3_domain_id: 'mydomain'
475 provider:
476 hostname: 'openstack.example.com'
477 userid: 'admin'
478 password: 'password'
479 security_protocol: 'ssl-with-validation'
480 validate_certs: 'true'
481 certificate_authority: |
482 -----BEGIN CERTIFICATE-----
483 FAKECERTsdKgAwI...
484 -----END CERTIFICATE-----
485 metrics:
486 role: amqp
487 hostname: 'amqp.example.com'
488 security_protocol: 'non-ssl'
489 port: 5666
490 userid: admin
491 password: password
492
493
494 - name: Create a new GCE provider in ManageIQ
495 community.general.manageiq_provider:
496 name: 'EngGoogle'
497 type: 'GCE'
498 provider_region: 'europe-west1'
499 project: 'project1'
500 state: 'present'
501 provider:
502 hostname: 'gce.example.com'
503 auth_key: 'google_json_key'
504 validate_certs: 'false'
505 """
506
507 RETURN = r"""
508 """
509
510 from ansible.module_utils.basic import AnsibleModule
511
512 from ansible_collections.community.general.plugins.module_utils._manageiq import ManageIQ, manageiq_argument_spec
513
514
515 def supported_providers():
516 return dict(
517 Openshift=dict(
518 class_name="ManageIQ::Providers::Openshift::ContainerManager",
519 authtype="bearer",
520 default_role="default",
521 metrics_role="prometheus",
522 alerts_role="prometheus_alerts",
523 ),
524 Amazon=dict(
525 class_name="ManageIQ::Providers::Amazon::CloudManager",
526 ),
527 oVirt=dict(
528 class_name="ManageIQ::Providers::Redhat::InfraManager",
529 default_role="default",
530 metrics_role="metrics",
531 ),
532 VMware=dict(
533 class_name="ManageIQ::Providers::Vmware::InfraManager",
534 ),
535 Azure=dict(
536 class_name="ManageIQ::Providers::Azure::CloudManager",
537 ),
538 Director=dict(class_name="ManageIQ::Providers::Openstack::InfraManager", ssh_keypair_role="ssh_keypair"),
539 OpenStack=dict(
540 class_name="ManageIQ::Providers::Openstack::CloudManager",
541 ),
542 GCE=dict(
543 class_name="ManageIQ::Providers::Google::CloudManager",
544 ),
545 )
546
547
548 def endpoint_list_spec():
549 return dict(
550 provider=dict(type="dict", options=endpoint_argument_spec()),
551 metrics=dict(type="dict", options=endpoint_argument_spec()),
552 alerts=dict(type="dict", options=endpoint_argument_spec()),
553 ssh_keypair=dict(type="dict", options=endpoint_argument_spec(), no_log=False),
554 )
555
556
557 def endpoint_argument_spec():
558 return dict(
559 role=dict(),
560 hostname=dict(required=True),
561 port=dict(type="int"),
562 validate_certs=dict(default=True, type="bool", aliases=["verify_ssl"]),
563 certificate_authority=dict(),
564 security_protocol=dict(
565 choices=[
566 "ssl-with-validation",
567 "ssl-with-validation-custom-ca",
568 "ssl-without-validation",
569 "non-ssl",
570 ],
571 ),
572 userid=dict(),
573 password=dict(no_log=True),
574 auth_key=dict(no_log=True),
575 subscription=dict(no_log=True),
576 project=dict(),
577 uid_ems=dict(),
578 path=dict(),
579 )
580
581
582 def delete_nulls(h):
583 """Remove null entries from a hash
584
585 Returns:
586 a hash without nulls
587 """
588 if isinstance(h, list):
589 return [delete_nulls(i) for i in h]
590 if isinstance(h, dict):
591 return {k: delete_nulls(v) for k, v in h.items() if v is not None}
592
593 return h
594
595
596 class ManageIQProvider:
597 """
598 Object to execute provider management operations in manageiq.
599 """
600
601 def __init__(self, manageiq):
602 self.manageiq = manageiq
603
604 self.module = self.manageiq.module
605 self.api_url = self.manageiq.api_url
606 self.client = self.manageiq.client
607
608 def class_name_to_type(self, class_name):
609 """Convert class_name to type
610
611 Returns:
612 the type
613 """
614 out = [k for k, v in supported_providers().items() if v["class_name"] == class_name]
615 if len(out) == 1:
616 return out[0]
617
618 return None
619
620 def zone_id(self, name):
621 """Search for zone id by zone name.
622
623 Returns:
624 the zone id, or send a module Fail signal if zone not found.
625 """
626 zone = self.manageiq.find_collection_resource_by("zones", name=name)
627 if not zone: # zone doesn't exist
628 self.module.fail_json(msg=f"zone {name} does not exist in manageiq")
629
630 return zone["id"]
631
632 def provider(self, name):
633 """Search for provider object by name.
634
635 Returns:
636 the provider, or None if provider not found.
637 """
638 return self.manageiq.find_collection_resource_by("providers", name=name)
639
640 def build_connection_configurations(self, provider_type, endpoints):
641 """Build "connection_configurations" objects from
642 requested endpoints provided by user
643
644 Returns:
645 the user requested provider endpoints list
646 """
647 connection_configurations = []
648 endpoint_keys = endpoint_list_spec().keys()
649 provider_defaults = supported_providers().get(provider_type, {})
650
651 # get endpoint defaults
652 endpoint = endpoints.get("provider")
653 default_auth_key = endpoint.get("auth_key")
654
655 # build a connection_configuration object for each endpoint
656 for endpoint_key in endpoint_keys:
657 endpoint = endpoints.get(endpoint_key)
658 if endpoint:
659 # get role and authtype
660 role = endpoint.get("role") or provider_defaults.get(f"{endpoint_key}_role", "default")
661 if role == "default":
662 authtype = provider_defaults.get("authtype") or role
663 else:
664 authtype = role
665
666 # set a connection_configuration
667 connection_configurations.append(
668 {
669 "endpoint": {
670 "role": role,
671 "hostname": endpoint.get("hostname"),
672 "port": endpoint.get("port"),
673 "verify_ssl": [0, 1][endpoint.get("validate_certs", True)],
674 "security_protocol": endpoint.get("security_protocol"),
675 "certificate_authority": endpoint.get("certificate_authority"),
676 "path": endpoint.get("path"),
677 },
678 "authentication": {
679 "authtype": authtype,
680 "userid": endpoint.get("userid"),
681 "password": endpoint.get("password"),
682 "auth_key": endpoint.get("auth_key") or default_auth_key,
683 },
684 }
685 )
686
687 return connection_configurations
688
689 def delete_provider(self, provider):
690 """Deletes a provider from manageiq.
691
692 Returns:
693 a short message describing the operation executed.
694 """
695 try:
696 url = f"{self.api_url}/providers/{provider['id']}"
697 result = self.client.post(url, action="delete")
698 except Exception as e:
699 self.module.fail_json(msg=f"failed to delete provider {provider['name']}: {e}")
700
701 return dict(changed=True, msg=result["message"])
702
703 def edit_provider(
704 self,
705 provider,
706 name,
707 provider_type,
708 endpoints,
709 zone_id,
710 provider_region,
711 host_default_vnc_port_start,
712 host_default_vnc_port_end,
713 subscription,
714 project,
715 uid_ems,
716 tenant_mapping_enabled,
717 api_version,
718 ):
719 """Edit a provider from manageiq.
720
721 Returns:
722 a short message describing the operation executed.
723 """
724 url = f"{self.api_url}/providers/{provider['id']}"
725
726 resource = dict(
727 name=name,
728 zone={"id": zone_id},
729 provider_region=provider_region,
730 connection_configurations=endpoints,
731 host_default_vnc_port_start=host_default_vnc_port_start,
732 host_default_vnc_port_end=host_default_vnc_port_end,
733 subscription=subscription,
734 project=project,
735 uid_ems=uid_ems,
736 tenant_mapping_enabled=tenant_mapping_enabled,
737 api_version=api_version,
738 )
739
740 # NOTE: we do not check for diff's between requested and current
741 # provider, we always submit endpoints with password or auth_keys,
742 # since we can not compare with current password or auth_key,
743 # every edit request is sent to ManageIQ API without comparing
744 # it to current state.
745
746 # clean nulls, we do not send nulls to the api
747 resource = delete_nulls(resource)
748
749 # try to update provider
750 try:
751 result = self.client.post(url, action="edit", resource=resource)
752 except Exception as e:
753 self.module.fail_json(msg=f"failed to update provider {provider['name']}: {e}")
754
755 return dict(changed=True, msg=f"successfully updated the provider {provider['name']}: {result}")
756
757 def create_provider(
758 self,
759 name,
760 provider_type,
761 endpoints,
762 zone_id,
763 provider_region,
764 host_default_vnc_port_start,
765 host_default_vnc_port_end,
766 subscription,
767 project,
768 uid_ems,
769 tenant_mapping_enabled,
770 api_version,
771 ):
772 """Creates the provider in manageiq.
773
774 Returns:
775 a short message describing the operation executed.
776 """
777 resource = dict(
778 name=name,
779 zone={"id": zone_id},
780 provider_region=provider_region,
781 host_default_vnc_port_start=host_default_vnc_port_start,
782 host_default_vnc_port_end=host_default_vnc_port_end,
783 subscription=subscription,
784 project=project,
785 uid_ems=uid_ems,
786 tenant_mapping_enabled=tenant_mapping_enabled,
787 api_version=api_version,
788 connection_configurations=endpoints,
789 )
790
791 # clean nulls, we do not send nulls to the api
792 resource = delete_nulls(resource)
793
794 # try to create a new provider
795 try:
796 url = f"{self.api_url}/providers"
797 result = self.client.post(url, type=supported_providers()[provider_type]["class_name"], **resource)
798 except Exception as e:
799 self.module.fail_json(msg=f"failed to create provider {name}: {e}")
800
801 return dict(changed=True, msg=f"successfully created the provider {name}: {result['results']}")
802
803 def refresh(self, provider, name):
804 """Trigger provider refresh.
805
806 Returns:
807 a short message describing the operation executed.
808 """
809 try:
810 url = f"{self.api_url}/providers/{provider['id']}"
811 self.client.post(url, action="refresh")
812 except Exception as e:
813 self.module.fail_json(msg=f"failed to refresh provider {name}: {e}")
814
815 return dict(changed=True, msg=f"refreshing provider {name}")
816
817
818 def main():
819 zone_id = None
820 endpoints = []
821 argument_spec = dict(
822 state=dict(choices=["absent", "present", "refresh"], default="present"),
823 name=dict(required=True),
824 zone=dict(default="default"),
825 provider_region=dict(),
826 host_default_vnc_port_start=dict(),
827 host_default_vnc_port_end=dict(),
828 subscription=dict(),
829 project=dict(),
830 azure_tenant_id=dict(aliases=["keystone_v3_domain_id"]),
831 tenant_mapping_enabled=dict(default=False, type="bool"),
832 api_version=dict(choices=["v2", "v3"]),
833 type=dict(choices=list(supported_providers().keys())),
834 )
835 # add the manageiq connection arguments to the arguments
836 argument_spec.update(manageiq_argument_spec())
837 # add the endpoint arguments to the arguments
838 argument_spec.update(endpoint_list_spec())
839
840 module = AnsibleModule(
841 argument_spec=argument_spec,
842 required_if=[("state", "present", ["provider"]), ("state", "refresh", ["name"])],
843 required_together=[["host_default_vnc_port_start", "host_default_vnc_port_end"]],
844 )
845
846 name = module.params["name"]
847 zone_name = module.params["zone"]
848 provider_type = module.params["type"]
849 raw_endpoints = module.params
850 provider_region = module.params["provider_region"]
851 host_default_vnc_port_start = module.params["host_default_vnc_port_start"]
852 host_default_vnc_port_end = module.params["host_default_vnc_port_end"]
853 subscription = module.params["subscription"]
854 uid_ems = module.params["azure_tenant_id"]
855 project = module.params["project"]
856 tenant_mapping_enabled = module.params["tenant_mapping_enabled"]
857 api_version = module.params["api_version"]
858 state = module.params["state"]
859
860 manageiq = ManageIQ(module)
861 manageiq_provider = ManageIQProvider(manageiq)
862
863 provider = manageiq_provider.provider(name)
864
865 # provider should not exist
866 if state == "absent":
867 # if we have a provider, delete it
868 if provider:
869 res_args = manageiq_provider.delete_provider(provider)
870 # if we do not have a provider, nothing to do
871 else:
872 res_args = dict(changed=False, msg=f"provider {name}: does not exist in manageiq")
873
874 # provider should exist
875 if state == "present":
876 # get data user did not explicitly give
877 if zone_name:
878 zone_id = manageiq_provider.zone_id(zone_name)
879
880 # if we do not have a provider_type, use the current provider_type
881 if provider and not provider_type:
882 provider_type = manageiq_provider.class_name_to_type(provider["type"])
883
884 # check supported_providers types
885 if not provider_type:
886 manageiq_provider.module.fail_json(msg="missing required argument: provider_type")
887
888 # check supported_providers types
889 if provider_type not in supported_providers().keys():
890 manageiq_provider.module.fail_json(msg=f"provider_type {provider_type} is not supported")
891
892 # build "connection_configurations" objects from user requested endpoints
893 # "provider" is a required endpoint, if we have it, we have endpoints
894 if raw_endpoints.get("provider"):
895 endpoints = manageiq_provider.build_connection_configurations(provider_type, raw_endpoints)
896
897 # if we have a provider, edit it
898 if provider:
899 res_args = manageiq_provider.edit_provider(
900 provider,
901 name,
902 provider_type,
903 endpoints,
904 zone_id,
905 provider_region,
906 host_default_vnc_port_start,
907 host_default_vnc_port_end,
908 subscription,
909 project,
910 uid_ems,
911 tenant_mapping_enabled,
912 api_version,
913 )
914 # if we do not have a provider, create it
915 else:
916 res_args = manageiq_provider.create_provider(
917 name,
918 provider_type,
919 endpoints,
920 zone_id,
921 provider_region,
922 host_default_vnc_port_start,
923 host_default_vnc_port_end,
924 subscription,
925 project,
926 uid_ems,
927 tenant_mapping_enabled,
928 api_version,
929 )
930
931 # refresh provider (trigger sync)
932 if state == "refresh":
933 if provider:
934 res_args = manageiq_provider.refresh(provider, name)
935 else:
936 res_args = dict(changed=False, msg=f"provider {name}: does not exist in manageiq")
937
938 module.exit_json(**res_args)
939
940
941 if __name__ == "__main__":
942 main()