Debian Codegraph @

ansible_collections/vmware/vmware_rest/plugins/modules/content_library_info.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 # Copyright: (c) 2021, Ansible Project
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5 # template: header.j2
6 # This module is autogenerated using the ansible.content_builder.
7 # See: https://github.com/ansible-community/ansible.content_builder
8
9
10 DOCUMENTATION = r"""
11 module: content_library_info
12 short_description: Returns a given LibraryModel.
13 description: Returns a given LibraryModel.
14 options:
15 library_id:
16 description:
17 - Identifier of the library to return.
18 - The parameter must be the id of a resource returned by M(vmware.vmware_rest.content_library_info).
19 Required with I(state=['get'])
20 type: str
21 session_timeout:
22 description:
23 - 'Timeout settings for client session. '
24 - 'The maximal number of seconds for the whole operation including connection
25 establishment, request sending and response. '
26 - The default value is 300s.
27 type: float
28 version_added: 2.1.0
29 vcenter_hostname:
30 description:
31 - The hostname or IP address of the vSphere vCenter
32 - If the value is not specified in the task, the value of environment variable
33 C(VMWARE_HOST) will be used instead.
34 required: true
35 type: str
36 vcenter_password:
37 description:
38 - The vSphere vCenter password
39 - If the value is not specified in the task, the value of environment variable
40 C(VMWARE_PASSWORD) will be used instead.
41 required: true
42 type: str
43 vcenter_rest_log_file:
44 description:
45 - 'You can use this optional parameter to set the location of a log file. '
46 - 'This file will be used to record the HTTP REST interaction. '
47 - 'The file will be stored on the host that runs the module. '
48 - 'If the value is not specified in the task, the value of '
49 - environment variable C(VMWARE_REST_LOG_FILE) will be used instead.
50 type: str
51 vcenter_username:
52 description:
53 - The vSphere vCenter username
54 - If the value is not specified in the task, the value of environment variable
55 C(VMWARE_USER) will be used instead.
56 required: true
57 type: str
58 vcenter_validate_certs:
59 default: true
60 description:
61 - Allows connection when SSL certificates are not valid. Set to C(false) when
62 certificates are not trusted.
63 - If the value is not specified in the task, the value of environment variable
64 C(VMWARE_VALIDATE_CERTS) will be used instead.
65 type: bool
66 author:
67 - Ansible Cloud Team (@ansible-collections)
68 version_added: 4.0.0
69 requirements:
70 - vSphere 7.0.3 or greater
71 - python >= 3.6
72 - aiohttp
73 notes:
74 - Tested on vSphere 7.0.3
75 """
76
77 EXAMPLES = r"""
78 """
79
80 RETURN = r"""
81 """
82
83 # This structure describes the format of the data expected by the end-points
84 PAYLOAD_FORMAT = {
85 "get": {"query": {}, "body": {}, "path": {"library_id": "library_id"}},
86 "list": {"query": {}, "body": {}, "path": {}},
87 } # pylint: disable=line-too-long
88
89 from ansible.module_utils.basic import env_fallback
90 import os
91
92 if os.getenv("VMWARE_ENABLE_TURBO", False):
93 try:
94 from ansible_collections.cloud.common.plugins.module_utils.turbo.module import (
95 AnsibleTurboModule as AnsibleModule,
96 )
97
98 AnsibleModule.collection_name = "vmware.vmware_rest"
99 except ImportError:
100 from ansible.module_utils.basic import AnsibleModule
101 else:
102 from ansible.module_utils.basic import AnsibleModule
103
104 from ansible_collections.vmware.vmware_rest.plugins.module_utils.vmware_rest import (
105 build_full_device_list,
106 exists,
107 gen_args,
108 open_session,
109 session_timeout,
110 update_changed_flag,
111 )
112
113
114 def prepare_argument_spec():
115 argument_spec = {
116 "vcenter_hostname": dict(
117 type="str",
118 required=True,
119 fallback=(env_fallback, ["VMWARE_HOST"]),
120 ),
121 "vcenter_username": dict(
122 type="str",
123 required=True,
124 fallback=(env_fallback, ["VMWARE_USER"]),
125 ),
126 "vcenter_password": dict(
127 type="str",
128 required=True,
129 no_log=True,
130 fallback=(env_fallback, ["VMWARE_PASSWORD"]),
131 ),
132 "vcenter_validate_certs": dict(
133 type="bool",
134 required=False,
135 default=True,
136 fallback=(env_fallback, ["VMWARE_VALIDATE_CERTS"]),
137 ),
138 "vcenter_rest_log_file": dict(
139 type="str",
140 required=False,
141 fallback=(env_fallback, ["VMWARE_REST_LOG_FILE"]),
142 ),
143 "session_timeout": dict(
144 type="float",
145 required=False,
146 fallback=(env_fallback, ["VMWARE_SESSION_TIMEOUT"]),
147 ),
148 }
149
150 argument_spec["library_id"] = {"type": "str"}
151
152 return argument_spec
153
154
155 async def main():
156 required_if = list([])
157
158 module_args = prepare_argument_spec()
159 module = AnsibleModule(
160 argument_spec=module_args, required_if=required_if, supports_check_mode=True
161 )
162 if not module.params["vcenter_hostname"]:
163 module.fail_json("vcenter_hostname cannot be empty")
164 if not module.params["vcenter_username"]:
165 module.fail_json("vcenter_username cannot be empty")
166 if not module.params["vcenter_password"]:
167 module.fail_json("vcenter_password cannot be empty")
168 try:
169 session = await open_session(
170 vcenter_hostname=module.params["vcenter_hostname"],
171 vcenter_username=module.params["vcenter_username"],
172 vcenter_password=module.params["vcenter_password"],
173 validate_certs=module.params["vcenter_validate_certs"],
174 log_file=module.params["vcenter_rest_log_file"],
175 )
176 except Exception as err:
177 if hasattr(err, "get_message"):
178 module.fail_json(err.get_message())
179 else:
180 module.fail_json(str(err))
181 result = await entry_point(module, session)
182 module.exit_json(**result)
183
184
185 # template: info_list_and_get_module.j2
186 def build_url(params):
187 import yarl
188
189 if params.get("library_id"):
190 _in_query_parameters = PAYLOAD_FORMAT["get"]["query"].keys()
191 return yarl.URL(
192 ("https://{vcenter_hostname}" "/api/content/library/").format(**params)
193 + params["library_id"]
194 + gen_args(params, _in_query_parameters),
195 encoded=True,
196 )
197 _in_query_parameters = PAYLOAD_FORMAT["list"]["query"].keys()
198 return yarl.URL(
199 ("https://{vcenter_hostname}" "/api/content/library").format(**params)
200 + gen_args(params, _in_query_parameters),
201 encoded=True,
202 )
203
204
205 async def entry_point(module, session):
206 url = build_url(module.params)
207 async with session.get(url, **session_timeout(module.params)) as resp:
208 _json = await resp.json()
209
210 if "value" not in _json: # 7.0.2+
211 _json = {"value": _json}
212
213 if module.params.get("library_id"):
214 _json["id"] = module.params.get("library_id")
215 elif module.params.get("label"): # TODO extend the list of filter
216 _json = await exists(module.params, session, str(url))
217 elif (
218 isinstance(_json["value"], list)
219 and len(_json["value"]) > 0
220 and isinstance(_json["value"][0], str)
221 ):
222 # this is a list of id, we fetch the details
223 full_device_list = await build_full_device_list(session, str(url), _json)
224 _json = {"value": [i["value"] for i in full_device_list]}
225
226 return await update_changed_flag(_json, resp.status, "get")
227
228
229 if __name__ == "__main__":
230 import asyncio
231
232 current_loop = asyncio.new_event_loop()
233 try:
234 asyncio.set_event_loop(current_loop)
235 current_loop.run_until_complete(main())
236 finally:
237 current_loop.close()