Debian Codegraph @

ansible_collections/vmware/vmware_rest/plugins/modules/appliance_localaccounts_globalpolicy.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_globalpolicy
12 short_description: Set the global password policy.
13 description: Set the global password policy.
14 options:
15 max_days:
16 description:
17 - Maximum number of days a password may be used. If the password is older
18 than this, a password change will be forced.
19 - If unset then the restriction will be ignored.
20 type: int
21 min_days:
22 description:
23 - Minimum number of days allowed between password changes. Any password changes
24 attempted sooner than this will be rejected.
25 - If unset then the restriction will be ignored.
26 type: int
27 session_timeout:
28 description:
29 - 'Timeout settings for client session. '
30 - 'The maximal number of seconds for the whole operation including connection
31 establishment, request sending and response. '
32 - The default value is 300s.
33 type: float
34 version_added: 2.1.0
35 state:
36 choices:
37 - set
38 default: set
39 description: []
40 type: str
41 vcenter_hostname:
42 description:
43 - The hostname or IP address of the vSphere vCenter
44 - If the value is not specified in the task, the value of environment variable
45 C(VMWARE_HOST) will be used instead.
46 required: true
47 type: str
48 vcenter_password:
49 description:
50 - The vSphere vCenter password
51 - If the value is not specified in the task, the value of environment variable
52 C(VMWARE_PASSWORD) will be used instead.
53 required: true
54 type: str
55 vcenter_rest_log_file:
56 description:
57 - 'You can use this optional parameter to set the location of a log file. '
58 - 'This file will be used to record the HTTP REST interaction. '
59 - 'The file will be stored on the host that runs the module. '
60 - 'If the value is not specified in the task, the value of '
61 - environment variable C(VMWARE_REST_LOG_FILE) will be used instead.
62 type: str
63 vcenter_username:
64 description:
65 - The vSphere vCenter username
66 - If the value is not specified in the task, the value of environment variable
67 C(VMWARE_USER) will be used instead.
68 required: true
69 type: str
70 vcenter_validate_certs:
71 default: true
72 description:
73 - Allows connection when SSL certificates are not valid. Set to C(false) when
74 certificates are not trusted.
75 - If the value is not specified in the task, the value of environment variable
76 C(VMWARE_VALIDATE_CERTS) will be used instead.
77 type: bool
78 warn_days:
79 description:
80 - Number of days warning given before a password expires. A zero means warning
81 is given only upon the day of expiration.
82 - If unset then no warning will be provided.
83 type: int
84 author:
85 - Ansible Cloud Team (@ansible-collections)
86 version_added: 2.0.0
87 requirements:
88 - vSphere 7.0.3 or greater
89 - python >= 3.6
90 - aiohttp
91 notes:
92 - Tested on vSphere 7.0.3
93 """
94
95 EXAMPLES = r"""
96 - name: Update the global policy of the local accounts
97 vmware.vmware_rest.appliance_localaccounts_globalpolicy:
98 warn_days: 5
99 """
100 RETURN = r"""
101 # content generated by the update_return_section callback# task: Update the global policy of the local accounts
102 value:
103 description: Update the global policy of the local accounts
104 returned: On success
105 sample: {}
106 type: dict
107 """
108
109
110 # This structure describes the format of the data expected by the end-points
111 PAYLOAD_FORMAT = {
112 "set": {
113 "query": {},
114 "body": {
115 "max_days": "max_days",
116 "min_days": "min_days",
117 "warn_days": "warn_days",
118 },
119 "path": {},
120 }
121 } # pylint: disable=line-too-long
122
123 from ansible.module_utils.basic import env_fallback
124 import os
125
126 if os.getenv("VMWARE_ENABLE_TURBO", False):
127 try:
128 from ansible_collections.cloud.common.plugins.module_utils.turbo.module import (
129 AnsibleTurboModule as AnsibleModule,
130 )
131
132 AnsibleModule.collection_name = "vmware.vmware_rest"
133 except ImportError:
134 from ansible.module_utils.basic import AnsibleModule
135 else:
136 from ansible.module_utils.basic import AnsibleModule
137
138 from ansible_collections.vmware.vmware_rest.plugins.module_utils.vmware_rest import (
139 exists,
140 gen_args,
141 get_subdevice_type,
142 open_session,
143 prepare_payload,
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["max_days"] = {"type": "int"}
186 argument_spec["min_days"] = {"type": "int"}
187 argument_spec["state"] = {"type": "str", "choices": ["set"], "default": "set"}
188 argument_spec["warn_days"] = {"type": "int"}
189
190 return argument_spec
191
192
193 async def main():
194 required_if = list([])
195
196 module_args = prepare_argument_spec()
197 module = AnsibleModule(
198 argument_spec=module_args, required_if=required_if, supports_check_mode=False
199 )
200 if not module.params["vcenter_hostname"]:
201 module.fail_json("vcenter_hostname cannot be empty")
202 if not module.params["vcenter_username"]:
203 module.fail_json("vcenter_username cannot be empty")
204 if not module.params["vcenter_password"]:
205 module.fail_json("vcenter_password cannot be empty")
206 try:
207 session = await open_session(
208 vcenter_hostname=module.params["vcenter_hostname"],
209 vcenter_username=module.params["vcenter_username"],
210 vcenter_password=module.params["vcenter_password"],
211 validate_certs=module.params["vcenter_validate_certs"],
212 log_file=module.params["vcenter_rest_log_file"],
213 )
214 except Exception as err:
215 if hasattr(err, "get_message"):
216 module.fail_json(err.get_message())
217 else:
218 module.fail_json(str(err))
219 result = await entry_point(module, session)
220 module.exit_json(**result)
221
222
223 # template: default_module.j2
224 def build_url(params):
225 return (
226 "https://{vcenter_hostname}" "/api/appliance/local-accounts/global-policy"
227 ).format(**params)
228
229
230 async def entry_point(module, session):
231
232 if module.params["state"] == "present":
233 if "_create" in globals():
234 operation = "create"
235 else:
236 operation = "update"
237 elif module.params["state"] == "absent":
238 operation = "delete"
239 else:
240 operation = module.params["state"]
241
242 func = globals()["_" + operation]
243
244 return await func(module.params, session)
245
246
247 async def _set(params, session):
248 _in_query_parameters = PAYLOAD_FORMAT["set"]["query"].keys()
249 payload = prepare_payload(params, PAYLOAD_FORMAT["set"])
250 subdevice_type = get_subdevice_type("/api/appliance/local-accounts/global-policy")
251 if subdevice_type and not params[subdevice_type]:
252 _json = await exists(params, session, build_url(params))
253 if _json:
254 params[subdevice_type] = _json["id"]
255 _url = (
256 "https://{vcenter_hostname}" "/api/appliance/local-accounts/global-policy"
257 ).format(**params) + gen_args(params, _in_query_parameters)
258 async with session.get(_url, json=payload, **session_timeout(params)) as resp:
259 before = await resp.json()
260
261 async with session.put(_url, json=payload, **session_timeout(params)) as resp:
262 try:
263 if resp.headers["Content-Type"] == "application/json":
264 _json = await resp.json()
265 except KeyError:
266 _json = {}
267 if "value" not in _json: # 7.0.2
268 _json = {"value": _json}
269
270 # The PUT answer does not let us know if the resource has actually been
271 # modified
272 if resp.status < 300:
273 async with session.get(
274 _url, json=payload, **session_timeout(params)
275 ) as resp_get:
276 after = await resp_get.json()
277 if before == after:
278 return await update_changed_flag(after, resp_get.status, "get")
279 return await update_changed_flag(_json, resp.status, "set")
280
281
282 if __name__ == "__main__":
283 import asyncio
284
285 current_loop = asyncio.new_event_loop()
286 try:
287 asyncio.set_event_loop(current_loop)
288 current_loop.run_until_complete(main())
289 finally:
290 current_loop.close()