1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# GNU General Public License v3.0+
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = r"""
---
module: vyos_user
short_description: Manage user accounts on VyOS devices using REST API
description:
- Manages local user accounts on VyOS devices via the REST API.
- Uses REST API (C(connection=httpapi)) instead of CLI.
- Passwords are write-only. Once set, they cannot be read back in plaintext.
- Use C(update_password=on_create) to avoid resetting passwords on every run.
version_added: "1.0.0"
author:
- VyOS Community (@vyos)
options:
users:
description: List of user definitions.
type: list
elements: dict
suboptions:
name:
description: Username.
type: str
required: true
full_name:
description: Full name of the user.
type: str
password:
description: Plaintext password. Write-only — hashed on device immediately.
type: str
update_password:
description:
- Control when password is updated.
- C(always) updates the password on every run (default).
- C(on_create) only sets the password when the user is first created.
type: str
choices: [always, on_create]
default: always
public_keys:
description: SSH public keys for the user.
type: list
elements: dict
suboptions:
name:
description: Key identifier/name.
type: str
required: true
key:
description: Base64-encoded public key.
type: str
required: true
type:
description: Key type.
type: str
choices: [ssh-dss, ssh-rsa, ecdsa-sha2-nistp256, ecdsa-sha2-nistp384,
ecdsa-sha2-nistp521, ssh-ed25519]
required: true
state:
description:
- C(present) ensures users exist with the specified configuration.
- C(absent) removes specified users.
- C(gathered) returns current user configuration as structured data.
type: str
choices: [present, absent, gathered]
default: present
notes:
- Requires C(ansible_connection=httpapi) with the VyOS httpapi plugin.
- C(ansible_network_os) must be set to C(vyos.rest.vyos).
- The C(vyos) user cannot be deleted as it is required for API access.
- Passwords are hashed immediately by VyOS and cannot be read back.
"""
EXAMPLES = r"""
- name: Create user
vyos.rest.vyos_user:
users:
- name: alice
full_name: Alice Smith
password: securepassword
update_password: on_create
state: present
- name: Add SSH public key
vyos.rest.vyos_user:
users:
- name: alice
public_keys:
- name: alice-laptop
type: ssh-rsa
key: AAAAB3NzaC1yc2EAAAADAQABAAAB...
state: present
- name: Delete user
vyos.rest.vyos_user:
users:
- name: alice
state: absent
- name: Gather all users
vyos.rest.vyos_user:
state: gathered
"""
RETURN = r"""
before:
description: User configuration before this module ran.
returned: always
type: list
after:
description: User configuration after this module ran.
returned: when changed
type: list
commands:
description: List of API command tuples sent to the device.
returned: always
type: list
gathered:
description: Current user configuration as structured data.
returned: when state is gathered
type: list
saved:
description: Whether the config was saved after changes.
returned: when changed
type: bool
response:
description: Raw API response.
returned: always
type: dict
"""
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.vyos.rest.plugins.module_utils.vyos import (
VyOSModule,
autoclean,
dict_op,
from_device,
normalize_have,
)
_BASE = ["system", "login", "user"]
# "public-keys" is a tag node (keyed by key identifier) that could in
# principle collapse to a bare value for a single entry; defensive only
# -- "key" is required by the argspec so a real collapse is unlikely,
# but the guard costs nothing and matches the pattern used everywhere
# else a tag node is involved.
_TAG_KEYS = {"public-keys"}
# Users this module will never delete under state=absent, no matter what
# the playbook asks for -- "vyos" is required for REST API access itself,
# so deleting it would lock out every subsequent module call.
_PROTECTED_USERS = {"vyos"}
def _public_keys_to_device(keys):
return {
k["name"]: autoclean({kk: vv for kk, vv in k.items() if kk != "name"}) for k in keys or []
}
def _public_keys_from_device(raw):
return [{"name": name, **from_device(data or {})} for name, data in sorted((raw or {}).items())]
def _user_to_device(user):
"""password/update_password are deliberately excluded here and
handled entirely outside dict_op in build_commands() -- "password"
(plaintext, write-only) and have's "encrypted-password" are
structurally different data with no valid equality comparison
between them, so whether to set it is a policy decision
(update_password), never a diff. public_keys nests under a literal
"authentication" wrapper the argspec doesn't have.
"""
entry = autoclean(
{
k: v
for k, v in user.items()
if k not in ("name", "password", "update_password", "public_keys")
},
)
if user.get("public_keys"):
entry["authentication"] = {"public_keys": _public_keys_to_device(user["public_keys"])}
return entry
def _user_from_device(name, data):
data = dict(data or {})
auth = data.pop("authentication", None) or {}
entry = {"name": name, **from_device(data)}
if auth.get("encrypted-password"):
entry["encrypted_password"] = auth["encrypted-password"]
pub_keys_raw = auth.get("public-keys")
if pub_keys_raw:
entry["public_keys"] = _public_keys_from_device(pub_keys_raw)
return entry
def get_running_config(vyos):
raw = vyos.get_config(_BASE) or {}
if isinstance(raw, dict):
raw = raw.get("user", raw)
return raw if isinstance(raw, dict) else {}
def _device_to_argspec(raw):
if not raw or not isinstance(raw, dict):
return []
return [_user_from_device(name, data) for name, data in sorted(raw.items())]
def build_commands(users, raw_have, state):
raw_have = raw_have or {}
users = users or []
if state == "absent":
commands = []
for user in users:
name = user["name"]
if name in _PROTECTED_USERS:
continue
if name in raw_have:
commands.append(("delete", _BASE + [name]))
return commands
# state == "present": additive-only, matches the original module's
# scope exactly -- existing fields/keys not mentioned in a user's
# config are left alone, never removed (there's no "replaced" state
# here to make a full-model rewrite meaningful).
commands = []
norm_have = normalize_have(raw_have, _TAG_KEYS)
for user in users:
name = user["name"]
is_new = name not in raw_have
ubase = _BASE + [name]
have_user = norm_have.get(name) or {}
commands += dict_op(_user_to_device(user), have_user, ubase, op="set")
if user.get("password"):
update_policy = user.get("update_password", "always")
if update_policy == "always" or is_new:
commands.append(
("set", ubase + ["authentication", "plaintext-password", user["password"]]),
)
return commands
ARGUMENT_SPEC = dict(
users=dict(
type="list",
elements="dict",
options=dict(
name=dict(type="str", required=True),
full_name=dict(type="str"),
password=dict(type="str", no_log=True),
update_password=dict(
type="str",
choices=["always", "on_create"],
default="always",
),
public_keys=dict(
type="list",
elements="dict",
options=dict(
name=dict(type="str", required=True),
key=dict(type="str", required=True, no_log=True),
type=dict(
type="str",
required=True,
choices=[
"ssh-dss",
"ssh-rsa",
"ecdsa-sha2-nistp256",
"ecdsa-sha2-nistp384",
"ecdsa-sha2-nistp521",
"ssh-ed25519",
],
),
),
),
),
),
state=dict(
default="present",
choices=["present", "absent", "gathered"],
),
)
def main():
module = AnsibleModule(ARGUMENT_SPEC, supports_check_mode=True)
vyos = VyOSModule(module)
state = module.params["state"]
users = module.params.get("users") or []
raw_have = get_running_config(vyos)
have = _device_to_argspec(raw_have)
if state == "gathered":
module.exit_json(changed=False, gathered=have)
commands = build_commands(users, raw_have, state)
if module.check_mode:
module.exit_json(changed=bool(commands), commands=commands, before=have)
if commands:
response = vyos.apply_commands(commands)
saved = vyos.save_config()
module.exit_json(
changed=True,
before=have,
after=_device_to_argspec(get_running_config(vyos)),
commands=commands,
saved=saved,
response=response,
)
module.exit_json(changed=False, before=have, after=have, commands=[])
if __name__ == "__main__":
main()
|