Debian Codegraph @

ansible_collections/vmware/vmware_rest/plugins/modules/vcenter_datacenter.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: vcenter_datacenter
12 short_description: Create a new datacenter in the vCenter inventory
13 description: Create a new datacenter in the vCenter inventory
14 options:
15 datacenter:
16 description:
17 - Identifier of the datacenter to be deleted.
18 - The parameter must be the id of a resource returned by M(vmware.vmware_rest.vcenter_datacenter_info).
19 Required with I(state=['absent'])
20 type: str
21 folder:
22 description:
23 - Datacenter folder in which the new datacenter should be created.
24 - This field is currently required. In the future, if this field is unset,
25 the system will attempt to choose a suitable folder for the datacenter;
26 if a folder cannot be chosen, the datacenter creation operation will fail.
27 - 'When clients pass a value of this structure as a parameter, the field must
28 be the id of a resource returned by M(vmware.vmware_rest.vcenter_folder_info). '
29 type: str
30 force:
31 description:
32 - If true, delete the datacenter even if it is not empty.
33 - If unset a ResourceInUse error will be reported if the datacenter is not
34 empty. This is the equivalent of passing the value false.
35 type: bool
36 name:
37 description:
38 - The name of the datacenter to be created. Required with I(state=['present'])
39 type: str
40 session_timeout:
41 description:
42 - 'Timeout settings for client session. '
43 - 'The maximal number of seconds for the whole operation including connection
44 establishment, request sending and response. '
45 - The default value is 300s.
46 type: float
47 version_added: 2.1.0
48 state:
49 choices:
50 - absent
51 - present
52 default: present
53 description: []
54 type: str
55 vcenter_hostname:
56 description:
57 - The hostname or IP address of the vSphere vCenter
58 - If the value is not specified in the task, the value of environment variable
59 C(VMWARE_HOST) will be used instead.
60 required: true
61 type: str
62 vcenter_password:
63 description:
64 - The vSphere vCenter password
65 - If the value is not specified in the task, the value of environment variable
66 C(VMWARE_PASSWORD) will be used instead.
67 required: true
68 type: str
69 vcenter_rest_log_file:
70 description:
71 - 'You can use this optional parameter to set the location of a log file. '
72 - 'This file will be used to record the HTTP REST interaction. '
73 - 'The file will be stored on the host that runs the module. '
74 - 'If the value is not specified in the task, the value of '
75 - environment variable C(VMWARE_REST_LOG_FILE) will be used instead.
76 type: str
77 vcenter_username:
78 description:
79 - The vSphere vCenter username
80 - If the value is not specified in the task, the value of environment variable
81 C(VMWARE_USER) will be used instead.
82 required: true
83 type: str
84 vcenter_validate_certs:
85 default: true
86 description:
87 - Allows connection when SSL certificates are not valid. Set to C(false) when
88 certificates are not trusted.
89 - If the value is not specified in the task, the value of environment variable
90 C(VMWARE_VALIDATE_CERTS) will be used instead.
91 type: bool
92 author:
93 - Ansible Cloud Team (@ansible-collections)
94 version_added: 0.1.0
95 requirements:
96 - vSphere 7.0.3 or greater
97 - python >= 3.6
98 - aiohttp
99 notes:
100 - Tested on vSphere 7.0.3
101 """
102
103 EXAMPLES = r"""
104 - name: Get a list of all the datacenters
105 register: existing_datacenters
106 vmware.vmware_rest.vcenter_datacenter_info:
107 - name: Force delete the existing DC
108 vmware.vmware_rest.vcenter_datacenter:
109 state: absent
110 datacenter: '{{ item.datacenter }}'
111 force: true
112 with_items: '{{ existing_datacenters.value }}'
113 until:
114 - _result is not failed
115 retries: 7
116 - name: Create datacenter my_dc
117 vmware.vmware_rest.vcenter_datacenter:
118 name: my_dc
119 folder: '{{ my_datacenter_folder.folder }}'
120 """
121 RETURN = r"""
122 # content generated by the update_return_section callback# task: Force delete the existing DC
123 msg:
124 description: Force delete the existing DC
125 returned: On success
126 sample: All items completed
127 type: str
128 results:
129 description: Force delete the existing DC
130 returned: On success
131 sample:
132 - _ansible_item_label:
133 datacenter: datacenter-1001
134 name: my_dc
135 _ansible_no_log: null
136 ansible_loop_var: item
137 attempts: 1
138 changed: 1
139 failed: 0
140 invocation:
141 module_args:
142 datacenter: datacenter-1001
143 folder: null
144 force: 1
145 name: null
146 session_timeout: null
147 state: absent
148 vcenter_hostname: vcenter.test
149 vcenter_password: VALUE_SPECIFIED_IN_NO_LOG_PARAMETER
150 vcenter_rest_log_file: /tmp/vmware_rest.log
151 vcenter_username: [email protected]
152 vcenter_validate_certs: 0
153 item:
154 datacenter: datacenter-1001
155 name: my_dc
156 value: {}
157 type: list
158 """
159
160
161 # This structure describes the format of the data expected by the end-points
162 PAYLOAD_FORMAT = {
163 "delete": {
164 "query": {"force": "force"},
165 "body": {},
166 "path": {"datacenter": "datacenter"},
167 },
168 "create": {"query": {}, "body": {"folder": "folder", "name": "name"}, "path": {}},
169 } # pylint: disable=line-too-long
170
171 from ansible.module_utils.basic import env_fallback
172 import os
173
174 if os.getenv("VMWARE_ENABLE_TURBO", False):
175 try:
176 from ansible_collections.cloud.common.plugins.module_utils.turbo.module import (
177 AnsibleTurboModule as AnsibleModule,
178 )
179
180 AnsibleModule.collection_name = "vmware.vmware_rest"
181 except ImportError:
182 from ansible.module_utils.basic import AnsibleModule
183 else:
184 from ansible.module_utils.basic import AnsibleModule
185
186 from ansible_collections.vmware.vmware_rest.plugins.module_utils.vmware_rest import (
187 exists,
188 gen_args,
189 get_device_info,
190 get_subdevice_type,
191 open_session,
192 prepare_payload,
193 session_timeout,
194 update_changed_flag,
195 )
196
197
198 def prepare_argument_spec():
199 argument_spec = {
200 "vcenter_hostname": dict(
201 type="str",
202 required=True,
203 fallback=(env_fallback, ["VMWARE_HOST"]),
204 ),
205 "vcenter_username": dict(
206 type="str",
207 required=True,
208 fallback=(env_fallback, ["VMWARE_USER"]),
209 ),
210 "vcenter_password": dict(
211 type="str",
212 required=True,
213 no_log=True,
214 fallback=(env_fallback, ["VMWARE_PASSWORD"]),
215 ),
216 "vcenter_validate_certs": dict(
217 type="bool",
218 required=False,
219 default=True,
220 fallback=(env_fallback, ["VMWARE_VALIDATE_CERTS"]),
221 ),
222 "vcenter_rest_log_file": dict(
223 type="str",
224 required=False,
225 fallback=(env_fallback, ["VMWARE_REST_LOG_FILE"]),
226 ),
227 "session_timeout": dict(
228 type="float",
229 required=False,
230 fallback=(env_fallback, ["VMWARE_SESSION_TIMEOUT"]),
231 ),
232 }
233
234 argument_spec["datacenter"] = {"type": "str"}
235 argument_spec["folder"] = {"type": "str"}
236 argument_spec["force"] = {"type": "bool"}
237 argument_spec["name"] = {"type": "str"}
238 argument_spec["state"] = {
239 "type": "str",
240 "choices": ["absent", "present"],
241 "default": "present",
242 }
243
244 return argument_spec
245
246
247 async def main():
248 required_if = list([])
249
250 module_args = prepare_argument_spec()
251 module = AnsibleModule(
252 argument_spec=module_args, required_if=required_if, supports_check_mode=False
253 )
254 if not module.params["vcenter_hostname"]:
255 module.fail_json("vcenter_hostname cannot be empty")
256 if not module.params["vcenter_username"]:
257 module.fail_json("vcenter_username cannot be empty")
258 if not module.params["vcenter_password"]:
259 module.fail_json("vcenter_password cannot be empty")
260 try:
261 session = await open_session(
262 vcenter_hostname=module.params["vcenter_hostname"],
263 vcenter_username=module.params["vcenter_username"],
264 vcenter_password=module.params["vcenter_password"],
265 validate_certs=module.params["vcenter_validate_certs"],
266 log_file=module.params["vcenter_rest_log_file"],
267 )
268 except Exception as err:
269 if hasattr(err, "get_message"):
270 module.fail_json(err.get_message())
271 else:
272 module.fail_json(str(err))
273 result = await entry_point(module, session)
274 module.exit_json(**result)
275
276
277 # template: default_module.j2
278 def build_url(params):
279 return ("https://{vcenter_hostname}" "/api/vcenter/datacenter").format(**params)
280
281
282 async def entry_point(module, session):
283
284 if module.params["state"] == "present":
285 if "_create" in globals():
286 operation = "create"
287 else:
288 operation = "update"
289 elif module.params["state"] == "absent":
290 operation = "delete"
291 else:
292 operation = module.params["state"]
293
294 func = globals()["_" + operation]
295
296 return await func(module.params, session)
297
298
299 async def _create(params, session):
300
301 lookup_url = per_id_url = build_url(params)
302 uniquity_keys = ["datacenter"]
303 comp_func = None
304
305 async def lookup_with_filters(params, session, url):
306 search_filter = ""
307
308 if "folder" not in params:
309 return
310 search_filter = f"&folders={params.get('folder')}"
311
312 if "name" not in params:
313 return
314 async with session.get(f"{url}?names={params['name']}{search_filter}") as resp:
315 _json = await resp.json()
316 if isinstance(_json, list) and len(_json) == 1:
317 return await get_device_info(session, url, _json[0]["datacenter"])
318
319 _json = None
320
321 if params["datacenter"]:
322 _json = await get_device_info(session, build_url(params), params["datacenter"])
323
324 if not _json and (uniquity_keys or comp_func):
325 _json = await exists(
326 params,
327 session,
328 url=lookup_url,
329 uniquity_keys=uniquity_keys,
330 per_id_url=per_id_url,
331 comp_func=comp_func,
332 )
333
334 if not _json:
335 _json = await lookup_with_filters(params, session, build_url(params))
336
337 if _json:
338 if "value" not in _json: # 7.0.2+
339 _json = {"value": _json}
340 if "_update" in globals():
341 params["datacenter"] = _json["id"]
342 return await globals()["_update"](params, session)
343
344 return await update_changed_flag(_json, 200, "get")
345
346 payload = prepare_payload(params, PAYLOAD_FORMAT["create"])
347 _url = ("https://{vcenter_hostname}" "/api/vcenter/datacenter").format(**params)
348 async with session.post(_url, json=payload, **session_timeout(params)) as resp:
349 if resp.status == 500:
350 text = await resp.text()
351 raise Exception(f"Request has failed: status={resp.status}, {text}")
352 try:
353 if resp.headers["Content-Type"] == "application/json":
354 _json = await resp.json()
355 except KeyError:
356 _json = {}
357
358 if (resp.status in [200, 201]) and "error" not in _json:
359 if isinstance(_json, str): # 7.0.2 and greater
360 _id = _json # TODO: fetch the object
361 elif isinstance(_json, dict) and "value" not in _json:
362 _id = list(_json["value"].values())[0]
363 elif isinstance(_json, dict) and "value" in _json:
364 _id = _json["value"]
365 _json_device_info = await get_device_info(session, _url, _id)
366 if _json_device_info:
367 _json = _json_device_info
368
369 return await update_changed_flag(_json, resp.status, "create")
370
371
372 async def _delete(params, session):
373 _in_query_parameters = PAYLOAD_FORMAT["delete"]["query"].keys()
374 payload = prepare_payload(params, PAYLOAD_FORMAT["delete"])
375 subdevice_type = get_subdevice_type("/api/vcenter/datacenter/{datacenter}")
376 if subdevice_type and not params[subdevice_type]:
377 _json = await exists(params, session, build_url(params))
378 if _json:
379 params[subdevice_type] = _json["id"]
380 _url = ("https://{vcenter_hostname}" "/api/vcenter/datacenter/{datacenter}").format(
381 **params
382 ) + gen_args(params, _in_query_parameters)
383 async with session.delete(_url, json=payload, **session_timeout(params)) as resp:
384 try:
385 if resp.headers["Content-Type"] == "application/json":
386 _json = await resp.json()
387 except KeyError:
388 _json = {}
389 return await update_changed_flag(_json, resp.status, "delete")
390
391
392 if __name__ == "__main__":
393 import asyncio
394
395 current_loop = asyncio.new_event_loop()
396 try:
397 asyncio.set_event_loop(current_loop)
398 current_loop.run_until_complete(main())
399 finally:
400 current_loop.close()