| 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_host |
| 12 |
short_description: Add a new standalone host in the vCenter inventory |
| 13 |
description: Add a new standalone host in the vCenter inventory. The newly connected |
| 14 |
host will be in connected state. The vCenter Server will verify the SSL certificate |
| 15 |
before adding the host to its inventory. In the case where the SSL certificate |
| 16 |
cannot be verified because the Certificate Authority is not recognized or the |
| 17 |
certificate is self signed, the vCenter Server will fall back to thumbprint verification |
| 18 |
mode as defined by Host.CreateSpec.ThumbprintVerification. |
| 19 |
deprecated: |
| 20 |
removed_in: 5.0.0 |
| 21 |
why: This module has been moved to the L(new vmware.vmware collection,https://forum.ansible.com/t/5880) |
| 22 |
alternative: Use M(vmware.vmware.esxi_host) instead. |
| 23 |
options: |
| 24 |
folder: |
| 25 |
description: |
| 26 |
- Host and cluster folder in which the new standalone host should be created. |
| 27 |
- This field is currently required. In the future, if this field is unset, |
| 28 |
the system will attempt to choose a suitable folder for the host; if a |
| 29 |
folder cannot be chosen, the host creation operation will fail. |
| 30 |
- 'When clients pass a value of this structure as a parameter, the field must |
| 31 |
be the id of a resource returned by M(vmware.vmware_rest.vcenter_folder_info). ' |
| 32 |
type: str |
| 33 |
force_add: |
| 34 |
description: |
| 35 |
- Whether host should be added to the vCenter Server even if it is being managed |
| 36 |
by another vCenter Server. The original vCenterServer loses connection |
| 37 |
to the host. |
| 38 |
- If unset, forceAdd is default to false. |
| 39 |
type: bool |
| 40 |
host: |
| 41 |
description: |
| 42 |
- Identifier of the host to be disconnected. |
| 43 |
- The parameter must be the id of a resource returned by M(vmware.vmware_rest.vcenter_host_info). |
| 44 |
Required with I(state=['absent', 'connect', 'disconnect']) |
| 45 |
type: str |
| 46 |
hostname: |
| 47 |
description: |
| 48 |
- The IP address or DNS resolvable name of the host. Required with I(state=['present']) |
| 49 |
type: str |
| 50 |
password: |
| 51 |
description: |
| 52 |
- The password for the administrator account on the host. Required with I(state=['present']) |
| 53 |
type: str |
| 54 |
port: |
| 55 |
description: |
| 56 |
- The port of the host. |
| 57 |
- If unset, port 443 will be used. |
| 58 |
type: int |
| 59 |
session_timeout: |
| 60 |
description: |
| 61 |
- 'Timeout settings for client session. ' |
| 62 |
- 'The maximal number of seconds for the whole operation including connection |
| 63 |
establishment, request sending and response. ' |
| 64 |
- The default value is 300s. |
| 65 |
type: float |
| 66 |
version_added: 2.1.0 |
| 67 |
state: |
| 68 |
choices: |
| 69 |
- absent |
| 70 |
- connect |
| 71 |
- disconnect |
| 72 |
- present |
| 73 |
default: present |
| 74 |
description: [] |
| 75 |
type: str |
| 76 |
thumbprint: |
| 77 |
description: |
| 78 |
- 'The thumbprint of the SSL certificate, which the host is expected to have. |
| 79 |
The thumbprint is always computed using the SHA1 hash and is the string |
| 80 |
representation of that hash in the format: xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx |
| 81 |
where, ''x'' represents a hexadecimal digit.' |
| 82 |
- This field is optional and it is only relevant when the value of I(thumbprint_verification) |
| 83 |
is THUMBPRINT. |
| 84 |
type: str |
| 85 |
thumbprint_verification: |
| 86 |
choices: |
| 87 |
- NONE |
| 88 |
- THUMBPRINT |
| 89 |
description: |
| 90 |
- The I(thumbprint_verification) enumerated type defines the thumbprint verification |
| 91 |
schemes for a host's SSL certificate. Required with I(state=['present']) |
| 92 |
type: str |
| 93 |
user_name: |
| 94 |
description: |
| 95 |
- The administrator account on the host. Required with I(state=['present']) |
| 96 |
type: str |
| 97 |
vcenter_hostname: |
| 98 |
description: |
| 99 |
- The hostname or IP address of the vSphere vCenter |
| 100 |
- If the value is not specified in the task, the value of environment variable |
| 101 |
C(VMWARE_HOST) will be used instead. |
| 102 |
required: true |
| 103 |
type: str |
| 104 |
vcenter_password: |
| 105 |
description: |
| 106 |
- The vSphere vCenter password |
| 107 |
- If the value is not specified in the task, the value of environment variable |
| 108 |
C(VMWARE_PASSWORD) will be used instead. |
| 109 |
required: true |
| 110 |
type: str |
| 111 |
vcenter_rest_log_file: |
| 112 |
description: |
| 113 |
- 'You can use this optional parameter to set the location of a log file. ' |
| 114 |
- 'This file will be used to record the HTTP REST interaction. ' |
| 115 |
- 'The file will be stored on the host that runs the module. ' |
| 116 |
- 'If the value is not specified in the task, the value of ' |
| 117 |
- environment variable C(VMWARE_REST_LOG_FILE) will be used instead. |
| 118 |
type: str |
| 119 |
vcenter_username: |
| 120 |
description: |
| 121 |
- The vSphere vCenter username |
| 122 |
- If the value is not specified in the task, the value of environment variable |
| 123 |
C(VMWARE_USER) will be used instead. |
| 124 |
required: true |
| 125 |
type: str |
| 126 |
vcenter_validate_certs: |
| 127 |
default: true |
| 128 |
description: |
| 129 |
- Allows connection when SSL certificates are not valid. Set to C(false) when |
| 130 |
certificates are not trusted. |
| 131 |
- If the value is not specified in the task, the value of environment variable |
| 132 |
C(VMWARE_VALIDATE_CERTS) will be used instead. |
| 133 |
type: bool |
| 134 |
author: |
| 135 |
- Ansible Cloud Team (@ansible-collections) |
| 136 |
version_added: 0.1.0 |
| 137 |
requirements: |
| 138 |
- vSphere 7.0.3 or greater |
| 139 |
- python >= 3.6 |
| 140 |
- aiohttp |
| 141 |
notes: |
| 142 |
- Tested on vSphere 7.0.3 |
| 143 |
""" |
| 144 |
|
| 145 |
EXAMPLES = r""" |
| 146 |
- name: Connect the host(s) |
| 147 |
vmware.vmware_rest.vcenter_host: |
| 148 |
hostname: "{{ lookup('env', 'ESXI1_HOSTNAME') }}" |
| 149 |
user_name: "{{ lookup('env', 'ESXI1_USERNAME') }}" |
| 150 |
password: "{{ lookup('env', 'ESXI1_PASSWORD') }}" |
| 151 |
thumbprint_verification: NONE |
| 152 |
folder: '{{ my_host_folder.folder }}' |
| 153 |
""" |
| 154 |
RETURN = r""" |
| 155 |
# content generated by the update_return_section callback# task: Connect the host(s) |
| 156 |
value: |
| 157 |
description: Connect the host(s) |
| 158 |
returned: On success |
| 159 |
sample: host-1013 |
| 160 |
type: str |
| 161 |
""" |
| 162 |
|
| 163 |
|
| 164 |
# This structure describes the format of the data expected by the end-points |
| 165 |
PAYLOAD_FORMAT = { |
| 166 |
"connect": {"query": {}, "body": {}, "path": {"host": "host"}}, |
| 167 |
"disconnect": {"query": {}, "body": {}, "path": {"host": "host"}}, |
| 168 |
"create": { |
| 169 |
"query": {}, |
| 170 |
"body": { |
| 171 |
"folder": "folder", |
| 172 |
"force_add": "force_add", |
| 173 |
"hostname": "hostname", |
| 174 |
"password": "password", |
| 175 |
"port": "port", |
| 176 |
"thumbprint": "thumbprint", |
| 177 |
"thumbprint_verification": "thumbprint_verification", |
| 178 |
"user_name": "user_name", |
| 179 |
}, |
| 180 |
"path": {}, |
| 181 |
}, |
| 182 |
"delete": {"query": {}, "body": {}, "path": {"host": "host"}}, |
| 183 |
} # pylint: disable=line-too-long |
| 184 |
|
| 185 |
from ansible.module_utils.basic import env_fallback |
| 186 |
import os |
| 187 |
|
| 188 |
if os.getenv("VMWARE_ENABLE_TURBO", False): |
| 189 |
try: |
| 190 |
from ansible_collections.cloud.common.plugins.module_utils.turbo.module import ( |
| 191 |
AnsibleTurboModule as AnsibleModule, |
| 192 |
) |
| 193 |
|
| 194 |
AnsibleModule.collection_name = "vmware.vmware_rest" |
| 195 |
except ImportError: |
| 196 |
from ansible.module_utils.basic import AnsibleModule |
| 197 |
else: |
| 198 |
from ansible.module_utils.basic import AnsibleModule |
| 199 |
|
| 200 |
from ansible_collections.vmware.vmware_rest.plugins.module_utils.vmware_rest import ( |
| 201 |
exists, |
| 202 |
gen_args, |
| 203 |
get_device_info, |
| 204 |
get_subdevice_type, |
| 205 |
open_session, |
| 206 |
prepare_payload, |
| 207 |
session_timeout, |
| 208 |
update_changed_flag, |
| 209 |
) |
| 210 |
|
| 211 |
|
| 212 |
def prepare_argument_spec(): |
| 213 |
argument_spec = { |
| 214 |
"vcenter_hostname": dict( |
| 215 |
type="str", |
| 216 |
required=True, |
| 217 |
fallback=(env_fallback, ["VMWARE_HOST"]), |
| 218 |
), |
| 219 |
"vcenter_username": dict( |
| 220 |
type="str", |
| 221 |
required=True, |
| 222 |
fallback=(env_fallback, ["VMWARE_USER"]), |
| 223 |
), |
| 224 |
"vcenter_password": dict( |
| 225 |
type="str", |
| 226 |
required=True, |
| 227 |
no_log=True, |
| 228 |
fallback=(env_fallback, ["VMWARE_PASSWORD"]), |
| 229 |
), |
| 230 |
"vcenter_validate_certs": dict( |
| 231 |
type="bool", |
| 232 |
required=False, |
| 233 |
default=True, |
| 234 |
fallback=(env_fallback, ["VMWARE_VALIDATE_CERTS"]), |
| 235 |
), |
| 236 |
"vcenter_rest_log_file": dict( |
| 237 |
type="str", |
| 238 |
required=False, |
| 239 |
fallback=(env_fallback, ["VMWARE_REST_LOG_FILE"]), |
| 240 |
), |
| 241 |
"session_timeout": dict( |
| 242 |
type="float", |
| 243 |
required=False, |
| 244 |
fallback=(env_fallback, ["VMWARE_SESSION_TIMEOUT"]), |
| 245 |
), |
| 246 |
} |
| 247 |
|
| 248 |
argument_spec["folder"] = {"type": "str"} |
| 249 |
argument_spec["force_add"] = {"type": "bool"} |
| 250 |
argument_spec["host"] = {"type": "str"} |
| 251 |
argument_spec["hostname"] = {"type": "str"} |
| 252 |
argument_spec["password"] = {"no_log": True, "type": "str"} |
| 253 |
argument_spec["port"] = {"type": "int"} |
| 254 |
argument_spec["state"] = { |
| 255 |
"type": "str", |
| 256 |
"choices": ["absent", "connect", "disconnect", "present"], |
| 257 |
"default": "present", |
| 258 |
} |
| 259 |
argument_spec["thumbprint"] = {"type": "str"} |
| 260 |
argument_spec["thumbprint_verification"] = { |
| 261 |
"type": "str", |
| 262 |
"choices": ["NONE", "THUMBPRINT"], |
| 263 |
} |
| 264 |
argument_spec["user_name"] = {"no_log": True, "type": "str"} |
| 265 |
|
| 266 |
return argument_spec |
| 267 |
|
| 268 |
|
| 269 |
async def main(): |
| 270 |
required_if = list([]) |
| 271 |
|
| 272 |
module_args = prepare_argument_spec() |
| 273 |
module = AnsibleModule( |
| 274 |
argument_spec=module_args, required_if=required_if, supports_check_mode=False |
| 275 |
) |
| 276 |
if not module.params["vcenter_hostname"]: |
| 277 |
module.fail_json("vcenter_hostname cannot be empty") |
| 278 |
if not module.params["vcenter_username"]: |
| 279 |
module.fail_json("vcenter_username cannot be empty") |
| 280 |
if not module.params["vcenter_password"]: |
| 281 |
module.fail_json("vcenter_password cannot be empty") |
| 282 |
try: |
| 283 |
session = await open_session( |
| 284 |
vcenter_hostname=module.params["vcenter_hostname"], |
| 285 |
vcenter_username=module.params["vcenter_username"], |
| 286 |
vcenter_password=module.params["vcenter_password"], |
| 287 |
validate_certs=module.params["vcenter_validate_certs"], |
| 288 |
log_file=module.params["vcenter_rest_log_file"], |
| 289 |
) |
| 290 |
except Exception as err: |
| 291 |
if hasattr(err, "get_message"): |
| 292 |
module.fail_json(err.get_message()) |
| 293 |
else: |
| 294 |
module.fail_json(str(err)) |
| 295 |
result = await entry_point(module, session) |
| 296 |
module.exit_json(**result) |
| 297 |
|
| 298 |
|
| 299 |
# template: default_module.j2 |
| 300 |
def build_url(params): |
| 301 |
return ("https://{vcenter_hostname}" "/api/vcenter/host").format(**params) |
| 302 |
|
| 303 |
|
| 304 |
async def entry_point(module, session): |
| 305 |
|
| 306 |
if module.params["state"] == "present": |
| 307 |
if "_create" in globals(): |
| 308 |
operation = "create" |
| 309 |
else: |
| 310 |
operation = "update" |
| 311 |
elif module.params["state"] == "absent": |
| 312 |
operation = "delete" |
| 313 |
else: |
| 314 |
operation = module.params["state"] |
| 315 |
|
| 316 |
func = globals()["_" + operation] |
| 317 |
|
| 318 |
return await func(module.params, session) |
| 319 |
|
| 320 |
|
| 321 |
async def _connect(params, session): |
| 322 |
_in_query_parameters = PAYLOAD_FORMAT["connect"]["query"].keys() |
| 323 |
payload = prepare_payload(params, PAYLOAD_FORMAT["connect"]) |
| 324 |
subdevice_type = get_subdevice_type("/api/vcenter/host/{host}?action=connect") |
| 325 |
if subdevice_type and not params[subdevice_type]: |
| 326 |
_json = await exists(params, session, build_url(params)) |
| 327 |
if _json: |
| 328 |
params[subdevice_type] = _json["id"] |
| 329 |
_url = ( |
| 330 |
"https://{vcenter_hostname}" |
| 331 |
# aa |
| 332 |
"/api/vcenter/host/{host}?action=connect" |
| 333 |
).format(**params) + gen_args(params, _in_query_parameters) |
| 334 |
async with session.post(_url, json=payload, **session_timeout(params)) as resp: |
| 335 |
try: |
| 336 |
if resp.headers["Content-Type"] == "application/json": |
| 337 |
_json = await resp.json() |
| 338 |
except KeyError: |
| 339 |
_json = {} |
| 340 |
if "value" not in _json: # 7.0.2 |
| 341 |
_json = {"value": _json} |
| 342 |
|
| 343 |
return await update_changed_flag(_json, resp.status, "connect") |
| 344 |
|
| 345 |
|
| 346 |
async def _create(params, session): |
| 347 |
|
| 348 |
lookup_url = per_id_url = build_url(params) |
| 349 |
uniquity_keys = ["host"] |
| 350 |
comp_func = None |
| 351 |
|
| 352 |
async def lookup_with_filters(params, session, url): |
| 353 |
search_filter = "" |
| 354 |
|
| 355 |
if "folder" not in params: |
| 356 |
return |
| 357 |
search_filter = f"&folders={params.get('folder')}" |
| 358 |
|
| 359 |
if "name" not in params: |
| 360 |
return |
| 361 |
async with session.get(f"{url}?names={params['name']}{search_filter}") as resp: |
| 362 |
_json = await resp.json() |
| 363 |
if isinstance(_json, list) and len(_json) == 1: |
| 364 |
return await get_device_info(session, url, _json[0]["host"]) |
| 365 |
|
| 366 |
_json = None |
| 367 |
|
| 368 |
if params["host"]: |
| 369 |
_json = await get_device_info(session, build_url(params), params["host"]) |
| 370 |
|
| 371 |
if not _json and (uniquity_keys or comp_func): |
| 372 |
_json = await exists( |
| 373 |
params, |
| 374 |
session, |
| 375 |
url=lookup_url, |
| 376 |
uniquity_keys=uniquity_keys, |
| 377 |
per_id_url=per_id_url, |
| 378 |
comp_func=comp_func, |
| 379 |
) |
| 380 |
|
| 381 |
if not _json: |
| 382 |
_json = await lookup_with_filters(params, session, build_url(params)) |
| 383 |
|
| 384 |
if _json: |
| 385 |
if "value" not in _json: # 7.0.2+ |
| 386 |
_json = {"value": _json} |
| 387 |
if "_update" in globals(): |
| 388 |
params["host"] = _json["id"] |
| 389 |
return await globals()["_update"](params, session) |
| 390 |
|
| 391 |
return await update_changed_flag(_json, 200, "get") |
| 392 |
|
| 393 |
payload = prepare_payload(params, PAYLOAD_FORMAT["create"]) |
| 394 |
_url = ("https://{vcenter_hostname}" "/api/vcenter/host").format(**params) |
| 395 |
async with session.post(_url, json=payload, **session_timeout(params)) as resp: |
| 396 |
if resp.status == 500: |
| 397 |
text = await resp.text() |
| 398 |
raise Exception(f"Request has failed: status={resp.status}, {text}") |
| 399 |
try: |
| 400 |
if resp.headers["Content-Type"] == "application/json": |
| 401 |
_json = await resp.json() |
| 402 |
except KeyError: |
| 403 |
_json = {} |
| 404 |
|
| 405 |
if (resp.status in [200, 201]) and "error" not in _json: |
| 406 |
if isinstance(_json, str): # 7.0.2 and greater |
| 407 |
_id = _json # TODO: fetch the object |
| 408 |
elif isinstance(_json, dict) and "value" not in _json: |
| 409 |
_id = list(_json["value"].values())[0] |
| 410 |
elif isinstance(_json, dict) and "value" in _json: |
| 411 |
_id = _json["value"] |
| 412 |
_json_device_info = await get_device_info(session, _url, _id) |
| 413 |
if _json_device_info: |
| 414 |
_json = _json_device_info |
| 415 |
|
| 416 |
return await update_changed_flag(_json, resp.status, "create") |
| 417 |
|
| 418 |
|
| 419 |
async def _delete(params, session): |
| 420 |
_in_query_parameters = PAYLOAD_FORMAT["delete"]["query"].keys() |
| 421 |
payload = prepare_payload(params, PAYLOAD_FORMAT["delete"]) |
| 422 |
subdevice_type = get_subdevice_type("/api/vcenter/host/{host}") |
| 423 |
if subdevice_type and not params[subdevice_type]: |
| 424 |
_json = await exists(params, session, build_url(params)) |
| 425 |
if _json: |
| 426 |
params[subdevice_type] = _json["id"] |
| 427 |
_url = ("https://{vcenter_hostname}" "/api/vcenter/host/{host}").format( |
| 428 |
**params |
| 429 |
) + gen_args(params, _in_query_parameters) |
| 430 |
async with session.delete(_url, json=payload, **session_timeout(params)) as resp: |
| 431 |
try: |
| 432 |
if resp.headers["Content-Type"] == "application/json": |
| 433 |
_json = await resp.json() |
| 434 |
except KeyError: |
| 435 |
_json = {} |
| 436 |
return await update_changed_flag(_json, resp.status, "delete") |
| 437 |
|
| 438 |
|
| 439 |
async def _disconnect(params, session): |
| 440 |
_in_query_parameters = PAYLOAD_FORMAT["disconnect"]["query"].keys() |
| 441 |
payload = prepare_payload(params, PAYLOAD_FORMAT["disconnect"]) |
| 442 |
subdevice_type = get_subdevice_type("/api/vcenter/host/{host}?action=disconnect") |
| 443 |
if subdevice_type and not params[subdevice_type]: |
| 444 |
_json = await exists(params, session, build_url(params)) |
| 445 |
if _json: |
| 446 |
params[subdevice_type] = _json["id"] |
| 447 |
_url = ( |
| 448 |
"https://{vcenter_hostname}" |
| 449 |
# aa |
| 450 |
"/api/vcenter/host/{host}?action=disconnect" |
| 451 |
).format(**params) + gen_args(params, _in_query_parameters) |
| 452 |
async with session.post(_url, json=payload, **session_timeout(params)) as resp: |
| 453 |
try: |
| 454 |
if resp.headers["Content-Type"] == "application/json": |
| 455 |
_json = await resp.json() |
| 456 |
except KeyError: |
| 457 |
_json = {} |
| 458 |
if "value" not in _json: # 7.0.2 |
| 459 |
_json = {"value": _json} |
| 460 |
|
| 461 |
return await update_changed_flag(_json, resp.status, "disconnect") |
| 462 |
|
| 463 |
|
| 464 |
if __name__ == "__main__": |
| 465 |
import asyncio |
| 466 |
|
| 467 |
current_loop = asyncio.new_event_loop() |
| 468 |
try: |
| 469 |
asyncio.set_event_loop(current_loop) |
| 470 |
current_loop.run_until_complete(main()) |
| 471 |
finally: |
| 472 |
current_loop.close() |