Debian Codegraph @

ansible_collections/vmware/vmware_rest/plugins/modules/appliance_localaccounts_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: appliance_localaccounts_info
12 short_description: Get the local user account information.
13 description: Get the local user account information.
14 options:
15 session_timeout:
16 description:
17 - 'Timeout settings for client session. '
18 - 'The maximal number of seconds for the whole operation including connection
19 establishment, request sending and response. '
20 - The default value is 300s.
21 type: float
22 version_added: 2.1.0
23 username:
24 description:
25 - User login name Required with I(state=['get'])
26 type: str
27 vcenter_hostname:
28 description:
29 - The hostname or IP address of the vSphere vCenter
30 - If the value is not specified in the task, the value of environment variable
31 C(VMWARE_HOST) will be used instead.
32 required: true
33 type: str
34 vcenter_password:
35 description:
36 - The vSphere vCenter password
37 - If the value is not specified in the task, the value of environment variable
38 C(VMWARE_PASSWORD) will be used instead.
39 required: true
40 type: str
41 vcenter_rest_log_file:
42 description:
43 - 'You can use this optional parameter to set the location of a log file. '
44 - 'This file will be used to record the HTTP REST interaction. '
45 - 'The file will be stored on the host that runs the module. '
46 - 'If the value is not specified in the task, the value of '
47 - environment variable C(VMWARE_REST_LOG_FILE) will be used instead.
48 type: str
49 vcenter_username:
50 description:
51 - The vSphere vCenter username
52 - If the value is not specified in the task, the value of environment variable
53 C(VMWARE_USER) will be used instead.
54 required: true
55 type: str
56 vcenter_validate_certs:
57 default: true
58 description:
59 - Allows connection when SSL certificates are not valid. Set to C(false) when
60 certificates are not trusted.
61 - If the value is not specified in the task, the value of environment variable
62 C(VMWARE_VALIDATE_CERTS) will be used instead.
63 type: bool
64 author:
65 - Ansible Cloud Team (@ansible-collections)
66 version_added: 2.0.0
67 requirements:
68 - vSphere 7.0.3 or greater
69 - python >= 3.6
70 - aiohttp
71 notes:
72 - Tested on vSphere 7.0.3
73 """
74
75 EXAMPLES = r"""
76 - name: List the local accounts
77 vmware.vmware_rest.appliance_localaccounts_info:
78 register: result
79 """
80 RETURN = r"""
81 # content generated by the update_return_section callback# task: List the local accounts
82 value:
83 description: List the local accounts
84 returned: On success
85 sample:
86 - enabled: 1
87 fullname: root
88 has_password: 1
89 last_password_change: '2022-11-23T00:00:00.000Z'
90 max_days_between_password_change: 90
91 min_days_between_password_change: 0
92 password_expires_at: '2023-02-21T00:00:00.000Z'
93 roles:
94 - superAdmin
95 warn_days_before_password_expiration: 7
96 - enabled: 0
97 has_password: 0
98 inactive_at: '2022-12-25T00:00:00.000Z'
99 last_password_change: '2022-09-26T00:00:00.000Z'
100 max_days_between_password_change: 90
101 min_days_between_password_change: 1
102 password_expires_at: '2022-12-25T00:00:00.000Z'
103 roles:
104 - ''
105 warn_days_before_password_expiration: 7
106 - enabled: 0
107 has_password: 0
108 last_password_change: '2022-09-26T00:00:00.000Z'
109 max_days_between_password_change: -1
110 min_days_between_password_change: -1
111 roles:
112 - ''
113 warn_days_before_password_expiration: -1
114 type: list
115 """
116
117
118 # This structure describes the format of the data expected by the end-points
119 PAYLOAD_FORMAT = {
120 "get": {"query": {}, "body": {}, "path": {"username": "username"}},
121 "list": {"query": {}, "body": {}, "path": {}},
122 } # pylint: disable=line-too-long
123
124 from ansible.module_utils.basic import env_fallback
125 import os
126
127 if os.getenv("VMWARE_ENABLE_TURBO", False):
128 try:
129 from ansible_collections.cloud.common.plugins.module_utils.turbo.module import (
130 AnsibleTurboModule as AnsibleModule,
131 )
132
133 AnsibleModule.collection_name = "vmware.vmware_rest"
134 except ImportError:
135 from ansible.module_utils.basic import AnsibleModule
136 else:
137 from ansible.module_utils.basic import AnsibleModule
138
139 from ansible_collections.vmware.vmware_rest.plugins.module_utils.vmware_rest import (
140 build_full_device_list,
141 exists,
142 gen_args,
143 open_session,
144 session_timeout,
145 update_changed_flag,
146 )
147
148
149 def prepare_argument_spec():
150 argument_spec = {
151 "vcenter_hostname": dict(
152 type="str",
153 required=True,
154 fallback=(env_fallback, ["VMWARE_HOST"]),
155 ),
156 "vcenter_username": dict(
157 type="str",
158 required=True,
159 fallback=(env_fallback, ["VMWARE_USER"]),
160 ),
161 "vcenter_password": dict(
162 type="str",
163 required=True,
164 no_log=True,
165 fallback=(env_fallback, ["VMWARE_PASSWORD"]),
166 ),
167 "vcenter_validate_certs": dict(
168 type="bool",
169 required=False,
170 default=True,
171 fallback=(env_fallback, ["VMWARE_VALIDATE_CERTS"]),
172 ),
173 "vcenter_rest_log_file": dict(
174 type="str",
175 required=False,
176 fallback=(env_fallback, ["VMWARE_REST_LOG_FILE"]),
177 ),
178 "session_timeout": dict(
179 type="float",
180 required=False,
181 fallback=(env_fallback, ["VMWARE_SESSION_TIMEOUT"]),
182 ),
183 }
184
185 argument_spec["username"] = {"no_log": True, "type": "str"}
186
187 return argument_spec
188
189
190 async def main():
191 required_if = list([])
192
193 module_args = prepare_argument_spec()
194 module = AnsibleModule(
195 argument_spec=module_args, required_if=required_if, supports_check_mode=True
196 )
197 if not module.params["vcenter_hostname"]:
198 module.fail_json("vcenter_hostname cannot be empty")
199 if not module.params["vcenter_username"]:
200 module.fail_json("vcenter_username cannot be empty")
201 if not module.params["vcenter_password"]:
202 module.fail_json("vcenter_password cannot be empty")
203 try:
204 session = await open_session(
205 vcenter_hostname=module.params["vcenter_hostname"],
206 vcenter_username=module.params["vcenter_username"],
207 vcenter_password=module.params["vcenter_password"],
208 validate_certs=module.params["vcenter_validate_certs"],
209 log_file=module.params["vcenter_rest_log_file"],
210 )
211 except Exception as err:
212 if hasattr(err, "get_message"):
213 module.fail_json(err.get_message())
214 else:
215 module.fail_json(str(err))
216 result = await entry_point(module, session)
217 module.exit_json(**result)
218
219
220 # template: info_list_and_get_module.j2
221 def build_url(params):
222 import yarl
223
224 if params.get("username"):
225 _in_query_parameters = PAYLOAD_FORMAT["get"]["query"].keys()
226 return yarl.URL(
227 ("https://{vcenter_hostname}" "/api/appliance/local-accounts/").format(
228 **params
229 )
230 + params["username"]
231 + gen_args(params, _in_query_parameters),
232 encoded=True,
233 )
234 _in_query_parameters = PAYLOAD_FORMAT["list"]["query"].keys()
235 return yarl.URL(
236 ("https://{vcenter_hostname}" "/api/appliance/local-accounts").format(**params)
237 + gen_args(params, _in_query_parameters),
238 encoded=True,
239 )
240
241
242 async def entry_point(module, session):
243 url = build_url(module.params)
244 async with session.get(url, **session_timeout(module.params)) as resp:
245 _json = await resp.json()
246
247 if "value" not in _json: # 7.0.2+
248 _json = {"value": _json}
249
250 if module.params.get("username"):
251 _json["id"] = module.params.get("username")
252 elif module.params.get("label"): # TODO extend the list of filter
253 _json = await exists(module.params, session, str(url))
254 elif (
255 isinstance(_json["value"], list)
256 and len(_json["value"]) > 0
257 and isinstance(_json["value"][0], str)
258 ):
259 # this is a list of id, we fetch the details
260 full_device_list = await build_full_device_list(session, str(url), _json)
261 _json = {"value": [i["value"] for i in full_device_list]}
262
263 return await update_changed_flag(_json, resp.status, "get")
264
265
266 if __name__ == "__main__":
267 import asyncio
268
269 current_loop = asyncio.new_event_loop()
270 try:
271 asyncio.set_event_loop(current_loop)
272 current_loop.run_until_complete(main())
273 finally:
274 current_loop.close()