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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
|
#!/usr/bin/python
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
#
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: ce_rollback
version_added: "2.4"
short_description: Set a checkpoint or rollback to a checkpoint on HUAWEI CloudEngine switches.
description:
- This module offers the ability to set a configuration checkpoint
file or rollback to a configuration checkpoint file on HUAWEI CloudEngine switches.
author:
- Li Yanfeng (@QijunPan)
notes:
- Recommended connection is C(network_cli).
- This module also works with C(local) connections for legacy playbooks.
options:
commit_id:
description:
- Specifies the label of the configuration rollback point to which system configurations are
expected to roll back.
The value is an integer that the system generates automatically.
label:
description:
- Specifies a user label for a configuration rollback point.
The value is a string of 1 to 256 case-sensitive ASCII characters, spaces not supported.
The value must start with a letter and cannot be presented in a single hyphen (-).
filename:
description:
- Specifies a configuration file for configuration rollback.
The value is a string of 5 to 64 case-sensitive characters in the format of *.zip, *.cfg, or *.dat,
spaces not supported.
last:
description:
- Specifies the number of configuration rollback points.
The value is an integer that ranges from 1 to 80.
oldest:
description:
- Specifies the number of configuration rollback points.
The value is an integer that ranges from 1 to 80.
action:
description:
- The operation of configuration rollback.
required: true
choices: ['rollback','clear','set','display','commit']
'''
EXAMPLES = '''
- name: rollback module test
hosts: cloudengine
connection: local
gather_facts: no
vars:
cli:
host: "{{ inventory_hostname }}"
port: "{{ ansible_ssh_port }}"
username: "{{ username }}"
password: "{{ password }}"
transport: cli
tasks:
- name: Ensure commit_id is exist, and specifies the label of the configuration rollback point to
which system configurations are expected to roll back.
ce_rollback:
commit_id: 1000000748
action: rollback
provider: "{{ cli }}"
'''
RETURN = '''
proposed:
description: k/v pairs of parameters passed into module
returned: sometimes
type: dict
sample: {"commit_id": "1000000748", "action": "rollback"}
existing:
description: k/v pairs of existing rollback
returned: sometimes
type: dict
sample: {"commitId": "1000000748", "userLabel": "abc"}
updates:
description: command sent to the device
returned: always
type: list
sample: ["rollback configuration to file a.cfg",
"set configuration commit 1000000783 label ddd",
"clear configuration commit 1000000783 label",
"display configuration commit list"]
changed:
description: check to see if a change was made on the device
returned: always
type: bool
sample: true
end_state:
description: k/v pairs of configuration after module execution
returned: always
type: dict
sample: {"commitId": "1000000748", "userLabel": "abc"}
'''
import re
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.network.cloudengine.ce import ce_argument_spec, exec_command, run_commands
from ansible.module_utils.network.common.utils import ComplexList
class RollBack(object):
"""
Manages rolls back the system from the current configuration state to a historical configuration state.
"""
def __init__(self, argument_spec):
self.spec = argument_spec
self.module = AnsibleModule(argument_spec=self.spec, supports_check_mode=True)
self.commands = list()
# module input info
self.commit_id = self.module.params['commit_id']
self.label = self.module.params['label']
self.filename = self.module.params['filename']
self.last = self.module.params['last']
self.oldest = self.module.params['oldest']
self.action = self.module.params['action']
# state
self.changed = False
self.updates_cmd = list()
self.results = dict()
self.existing = dict()
self.proposed = dict()
self.end_state = dict()
# configuration rollback points info
self.rollback_info = None
self.init_module()
def init_module(self):
""" init module """
required_if = [('action', 'set', ['commit_id', 'label']), ('action', 'commit', ['label'])]
mutually_exclusive = None
required_one_of = None
if self.action == "rollback":
required_one_of = [['commit_id', 'label', 'filename', 'last']]
elif self.action == "clear":
required_one_of = [['commit_id', 'oldest']]
self.module = AnsibleModule(
argument_spec=self.spec, supports_check_mode=True, required_if=required_if, mutually_exclusive=mutually_exclusive, required_one_of=required_one_of)
def check_response(self, xml_str, xml_name):
"""Check if response message is already succeed."""
if "<ok/>" not in xml_str:
self.module.fail_json(msg='Error: %s failed.' % xml_name)
def cli_add_command(self, command, undo=False):
"""add command to self.update_cmd and self.commands"""
self.commands.append("return")
self.commands.append("mmi-mode enable")
if self.action == "commit":
self.commands.append("sys")
self.commands.append(command)
self.updates_cmd.append(command)
def cli_load_config(self, commands):
"""load config by cli"""
if not self.module.check_mode:
run_commands(self.module, commands)
def get_config(self, flags=None):
"""Retrieves the current config from the device or cache
"""
flags = [] if flags is None else flags
cmd = 'display configuration '
cmd += ' '.join(flags)
cmd = cmd.strip()
rc, out, err = exec_command(self.module, cmd)
if rc != 0:
self.module.fail_json(msg=err)
cfg = str(out).strip()
return cfg
def get_rollback_dict(self):
""" get rollback attributes dict."""
rollback_info = dict()
rollback_info["RollBackInfos"] = list()
flags = list()
exp = "commit list"
flags.append(exp)
cfg_info = self.get_config(flags)
if not cfg_info:
return rollback_info
cfg_line = cfg_info.split("\n")
for cfg in cfg_line:
if re.findall(r'^\d', cfg):
pre_rollback_info = cfg.split()
rollback_info["RollBackInfos"].append(dict(commitId=pre_rollback_info[1], userLabel=pre_rollback_info[2]))
return rollback_info
def get_filename_type(self, filename):
"""Gets the type of filename, such as cfg, zip, dat..."""
if filename is None:
return None
if ' ' in filename:
self.module.fail_json(
msg='Error: Configuration file name include spaces.')
iftype = None
if filename.endswith('.cfg'):
iftype = 'cfg'
elif filename.endswith('.zip'):
iftype = 'zip'
elif filename.endswith('.dat'):
iftype = 'dat'
else:
return None
return iftype.lower()
def set_config(self):
if self.action == "rollback":
if self.commit_id:
cmd = "rollback configuration to commit-id %s" % self.commit_id
self.cli_add_command(cmd)
if self.label:
cmd = "rollback configuration to label %s" % self.label
self.cli_add_command(cmd)
if self.filename:
cmd = "rollback configuration to file %s" % self.filename
self.cli_add_command(cmd)
if self.last:
cmd = "rollback configuration last %s" % self.last
self.cli_add_command(cmd)
elif self.action == "set":
if self.commit_id and self.label:
cmd = "set configuration commit %s label %s" % (self.commit_id, self.label)
self.cli_add_command(cmd)
elif self.action == "clear":
if self.commit_id:
cmd = "clear configuration commit %s label" % self.commit_id
self.cli_add_command(cmd)
if self.oldest:
cmd = "clear configuration commit oldest %s" % self.oldest
self.cli_add_command(cmd)
elif self.action == "commit":
if self.label:
cmd = "commit label %s" % self.label
self.cli_add_command(cmd)
elif self.action == "display":
self.rollback_info = self.get_rollback_dict()
if self.commands:
self.commands.append('return')
self.commands.append('undo mmi-mode enable')
self.cli_load_config(self.commands)
self.changed = True
def check_params(self):
"""Check all input params"""
# commit_id check
rollback_info = self.rollback_info["RollBackInfos"]
if self.commit_id:
if not self.commit_id.isdigit():
self.module.fail_json(
msg='Error: The parameter of commit_id is invalid.')
info_bool = False
for info in rollback_info:
if info.get("commitId") == self.commit_id:
info_bool = True
if not info_bool:
self.module.fail_json(
msg='Error: The parameter of commit_id is not exist.')
if self.action == "clear":
info_bool = False
for info in rollback_info:
if info.get("commitId") == self.commit_id:
if info.get("userLabel") == "-":
info_bool = True
if info_bool:
self.module.fail_json(
msg='Error: This commit_id does not have a label.')
# filename check
if self.filename:
if not self.get_filename_type(self.filename):
self.module.fail_json(
msg='Error: Invalid file name or file name extension ( *.cfg, *.zip, *.dat ).')
# last check
if self.last:
if not self.last.isdigit():
self.module.fail_json(
msg='Error: Number of configuration checkpoints is not digit.')
if int(self.last) <= 0 or int(self.last) > 80:
self.module.fail_json(
msg='Error: Number of configuration checkpoints is not in the range from 1 to 80.')
# oldest check
if self.oldest:
if not self.oldest.isdigit():
self.module.fail_json(
msg='Error: Number of configuration checkpoints is not digit.')
if int(self.oldest) <= 0 or int(self.oldest) > 80:
self.module.fail_json(
msg='Error: Number of configuration checkpoints is not in the range from 1 to 80.')
# label check
if self.label:
if self.label[0].isdigit():
self.module.fail_json(
msg='Error: Commit label which should not start with a number.')
if len(self.label.replace(' ', '')) == 1:
if self.label == '-':
self.module.fail_json(
msg='Error: Commit label which should not be "-"')
if len(self.label.replace(' ', '')) < 1 or len(self.label) > 256:
self.module.fail_json(
msg='Error: Label of configuration checkpoints is a string of 1 to 256 characters.')
if self.action == "rollback":
info_bool = False
for info in rollback_info:
if info.get("userLabel") == self.label:
info_bool = True
if not info_bool:
self.module.fail_json(
msg='Error: The parameter of userLabel is not exist.')
if self.action == "commit":
info_bool = False
for info in rollback_info:
if info.get("userLabel") == self.label:
info_bool = True
if info_bool:
self.module.fail_json(
msg='Error: The parameter of userLabel is existing.')
if self.action == "set":
info_bool = False
for info in rollback_info:
if info.get("commitId") == self.commit_id:
if info.get("userLabel") != "-":
info_bool = True
if info_bool:
self.module.fail_json(
msg='Error: The userLabel of this commitid is present and can be reset after deletion.')
def get_proposed(self):
"""get proposed info"""
if self.commit_id:
self.proposed["commit_id"] = self.commit_id
if self.label:
self.proposed["label"] = self.label
if self.filename:
self.proposed["filename"] = self.filename
if self.last:
self.proposed["last"] = self.last
if self.oldest:
self.proposed["oldest"] = self.oldest
def get_existing(self):
"""get existing info"""
if not self.rollback_info:
self.existing["RollBackInfos"] = None
else:
self.existing["RollBackInfos"] = self.rollback_info["RollBackInfos"]
def get_end_state(self):
"""get end state info"""
rollback_info = self.get_rollback_dict()
if not rollback_info:
self.end_state["RollBackInfos"] = None
else:
self.end_state["RollBackInfos"] = rollback_info["RollBackInfos"]
def work(self):
"""worker"""
self.rollback_info = self.get_rollback_dict()
self.check_params()
self.get_proposed()
self.set_config()
self.get_existing()
self.get_end_state()
self.results['changed'] = self.changed
self.results['proposed'] = self.proposed
self.results['existing'] = self.existing
self.results['end_state'] = self.end_state
if self.changed:
self.results['updates'] = self.updates_cmd
else:
self.results['updates'] = list()
self.module.exit_json(**self.results)
def main():
"""Module main"""
argument_spec = dict(
commit_id=dict(required=False),
label=dict(required=False, type='str'),
filename=dict(required=False, type='str'),
last=dict(required=False, type='str'),
oldest=dict(required=False, type='str'),
action=dict(required=False, type='str', choices=[
'rollback', 'clear', 'set', 'commit', 'display']),
)
argument_spec.update(ce_argument_spec)
module = RollBack(argument_spec)
module.work()
if __name__ == '__main__':
main()
|