Debian Codegraph @

ansible_collections/vmware/vmware_rest/plugins/modules/content_subscribedlibrary_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_subscribedlibrary_info
12 short_description: Returns a given subscribed library.
13 description: Returns a given subscribed library.
14 options:
15 library_id:
16 description:
17 - Identifier of the subscribed 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: 2.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 - name: List Subscribed Content Library
79 vmware.vmware_rest.content_subscribedlibrary_info:
80 register: my_content_library
81 """
82 RETURN = r"""
83 # content generated by the update_return_section callback# task: List Subscribed Content Library
84 value:
85 description: List Subscribed Content Library
86 returned: On success
87 sample:
88 - creation_time: '2022-11-23T20:06:05.189Z'
89 description: ''
90 id: 8b4e355e-a463-44f1-9b04-d0786a49cc7d
91 last_modified_time: '2022-11-23T20:06:05.189Z'
92 last_sync_time: '2022-11-23T20:06:07.717Z'
93 name: sub_lib
94 server_guid: 52fb0b5e-ffc3-465b-bf4f-e4e6d5423cf5
95 storage_backings:
96 - datastore_id: datastore-1065
97 type: DATASTORE
98 subscription_info:
99 authentication_method: NONE
100 automatic_sync_enabled: 0
101 on_demand: 1
102 subscription_url: https://vcenter.test:443/cls/vcsp/lib/a66d5c73-57f8-4a3a-9361-292a55f68516/lib.json
103 type: SUBSCRIBED
104 version: '4'
105 type: list
106 """
107
108
109 # This structure describes the format of the data expected by the end-points
110 PAYLOAD_FORMAT = {
111 "get": {"query": {}, "body": {}, "path": {"library_id": "library_id"}},
112 "list": {"query": {}, "body": {}, "path": {}},
113 } # pylint: disable=line-too-long
114
115 from ansible.module_utils.basic import env_fallback
116 import os
117
118 if os.getenv("VMWARE_ENABLE_TURBO", False):
119 try:
120 from ansible_collections.cloud.common.plugins.module_utils.turbo.module import (
121 AnsibleTurboModule as AnsibleModule,
122 )
123
124 AnsibleModule.collection_name = "vmware.vmware_rest"
125 except ImportError:
126 from ansible.module_utils.basic import AnsibleModule
127 else:
128 from ansible.module_utils.basic import AnsibleModule
129
130 from ansible_collections.vmware.vmware_rest.plugins.module_utils.vmware_rest import (
131 build_full_device_list,
132 exists,
133 gen_args,
134 open_session,
135 session_timeout,
136 update_changed_flag,
137 )
138
139
140 def prepare_argument_spec():
141 argument_spec = {
142 "vcenter_hostname": dict(
143 type="str",
144 required=True,
145 fallback=(env_fallback, ["VMWARE_HOST"]),
146 ),
147 "vcenter_username": dict(
148 type="str",
149 required=True,
150 fallback=(env_fallback, ["VMWARE_USER"]),
151 ),
152 "vcenter_password": dict(
153 type="str",
154 required=True,
155 no_log=True,
156 fallback=(env_fallback, ["VMWARE_PASSWORD"]),
157 ),
158 "vcenter_validate_certs": dict(
159 type="bool",
160 required=False,
161 default=True,
162 fallback=(env_fallback, ["VMWARE_VALIDATE_CERTS"]),
163 ),
164 "vcenter_rest_log_file": dict(
165 type="str",
166 required=False,
167 fallback=(env_fallback, ["VMWARE_REST_LOG_FILE"]),
168 ),
169 "session_timeout": dict(
170 type="float",
171 required=False,
172 fallback=(env_fallback, ["VMWARE_SESSION_TIMEOUT"]),
173 ),
174 }
175
176 argument_spec["library_id"] = {"type": "str"}
177
178 return argument_spec
179
180
181 async def main():
182 required_if = list([])
183
184 module_args = prepare_argument_spec()
185 module = AnsibleModule(
186 argument_spec=module_args, required_if=required_if, supports_check_mode=True
187 )
188 if not module.params["vcenter_hostname"]:
189 module.fail_json("vcenter_hostname cannot be empty")
190 if not module.params["vcenter_username"]:
191 module.fail_json("vcenter_username cannot be empty")
192 if not module.params["vcenter_password"]:
193 module.fail_json("vcenter_password cannot be empty")
194 try:
195 session = await open_session(
196 vcenter_hostname=module.params["vcenter_hostname"],
197 vcenter_username=module.params["vcenter_username"],
198 vcenter_password=module.params["vcenter_password"],
199 validate_certs=module.params["vcenter_validate_certs"],
200 log_file=module.params["vcenter_rest_log_file"],
201 )
202 except Exception as err:
203 if hasattr(err, "get_message"):
204 module.fail_json(err.get_message())
205 else:
206 module.fail_json(str(err))
207 result = await entry_point(module, session)
208 module.exit_json(**result)
209
210
211 # template: info_list_and_get_module.j2
212 def build_url(params):
213 import yarl
214
215 if params.get("library_id"):
216 _in_query_parameters = PAYLOAD_FORMAT["get"]["query"].keys()
217 return yarl.URL(
218 ("https://{vcenter_hostname}" "/api/content/subscribed-library/").format(
219 **params
220 )
221 + params["library_id"]
222 + gen_args(params, _in_query_parameters),
223 encoded=True,
224 )
225 _in_query_parameters = PAYLOAD_FORMAT["list"]["query"].keys()
226 return yarl.URL(
227 ("https://{vcenter_hostname}" "/api/content/subscribed-library").format(
228 **params
229 )
230 + gen_args(params, _in_query_parameters),
231 encoded=True,
232 )
233
234
235 async def entry_point(module, session):
236 url = build_url(module.params)
237 async with session.get(url, **session_timeout(module.params)) as resp:
238 _json = await resp.json()
239
240 if "value" not in _json: # 7.0.2+
241 _json = {"value": _json}
242
243 if module.params.get("library_id"):
244 _json["id"] = module.params.get("library_id")
245 elif module.params.get("label"): # TODO extend the list of filter
246 _json = await exists(module.params, session, str(url))
247 elif (
248 isinstance(_json["value"], list)
249 and len(_json["value"]) > 0
250 and isinstance(_json["value"][0], str)
251 ):
252 # this is a list of id, we fetch the details
253 full_device_list = await build_full_device_list(session, str(url), _json)
254 _json = {"value": [i["value"] for i in full_device_list]}
255
256 return await update_changed_flag(_json, resp.status, "get")
257
258
259 if __name__ == "__main__":
260 import asyncio
261
262 current_loop = asyncio.new_event_loop()
263 try:
264 asyncio.set_event_loop(current_loop)
265 current_loop.run_until_complete(main())
266 finally:
267 current_loop.close()