-
Notifications
You must be signed in to change notification settings - Fork 153
/
juniper_junos_common.py
1917 lines (1744 loc) · 85.5 KB
/
juniper_junos_common.py
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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
#
# Copyright (c) 2017-2020, Juniper Networks Inc. All rights reserved.
#
# License: Apache 2.0
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# * Neither the name of the Juniper Networks nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY Juniper Networks, Inc. ''AS IS'' AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL Juniper Networks, Inc. BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
from __future__ import absolute_import, division, print_function
# Ansible imports
from ansible.module_utils.connection import Connection
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.basic import boolean
from ansible.module_utils._text import to_bytes, to_text
from ansible_collections.juniper.device.plugins.module_utils import configuration as cfg
import jnpr
from jnpr.junos.utils.sw import SW
from jnpr.junos.utils.scp import SCP
from jnpr.junos import exception as pyez_exception
from ncclient.operations.errors import TimeoutExpiredError
from ansible.module_utils.common.validation import check_type_dict
# Standard library imports
from argparse import ArgumentParser
from distutils.version import LooseVersion
import json
import xmltodict
import logging
import os
import hashlib
try:
# Python 2
basestring
except NameError:
# Python 3
basestring = str
class ModuleDocFragment(object):
"""Documentation fragment for connection-related parameters.
All modules share a common set of connection parameters
which are documented in this class.
Attributes:
CONNECTION_DOCUMENTATION: The documentation string defining the
connection-related parameters for the
modules.
LOGGING_DOCUMENTATION: The documentation string defining the
logging-related parameters for the
modules.
"""
# The connection-specific options. Defined here so it can be re-used as
# suboptions in provider.
_CONNECT_DOCUMENTATION = '''
attempts:
description:
- The number of times to try connecting and logging in to the Junos
device. This option is only applicable when using C(mode = 'telnet')
or C(mode = 'serial'). Mutually exclusive with the I(console)
option.
required: false
default: 10
type: int
baud:
description:
- The serial baud rate, in bits per second, used to connect to the
Junos device. This option is only applicable when using
C(mode = 'serial'). Mutually exclusive with the I(console) option.
required: false
default: 9600
type: int
console:
description:
- An alternate method of specifying a NETCONF over serial console
connection to the Junos device using Telnet to a console server.
The value of this option must be a string in the format
C(--telnet <console_hostname>,<console_port_number>).
This option is deprecated. It is present only for backwards
compatibility. The string value of this option is exactly equivalent
to specifying I(host) with a value of C(<console_hostname>),
I(mode) with a value of C(telnet), and I(port) with a value of
C(<console_port_number>). Mutually exclusive with the I(mode),
I(port), I(baud), and I(attempts) options.
required: false
default: none
type: str
host:
description:
- The hostname or IP address of the Junos device to which the
connection should be established. This is normally the Junos device
itself, but is the hostname or IP address of a console server when
connecting to the console of the device by setting the I(mode)
option to the value C(telnet). This option is required, but does not
have to be specified explicitly by the user because it defaults to
C({{ inventory_hostname }}).
required: true
default: C({{ inventory_hostname }})
type: str
aliases:
- hostname
- ip
mode:
description:
- The PyEZ mode used to establish a NETCONF connection to the Junos
device. A value of C(none) uses the default NETCONF over SSH mode.
Depending on the values of the I(host) and I(port) options, a value
of C(telnet) results in either a direct NETCONF over Telnet
connection to the Junos device, or a NETCONF over serial console
connection to the Junos device using Telnet to a console server.
A value of C(serial) results in a NETCONF over serial console
connection to the Junos device. Mutually exclusive with the
I(console) option.
required: false
default: none
type: str
choices:
- none
- telnet
- serial
passwd:
description:
- The password, or ssh key's passphrase, used to authenticate with the
Junos device. If this option is not specified, authentication is
attempted using an empty password, or ssh key passphrase.
required: false
default: The first defined value from the following list
1) The C(ANSIBLE_NET_PASSWORD) environment variable.
(used by Ansible Tower)
2) The value specified using the C(-k) or C(--ask-pass)
command line arguments to the C(ansible) or
C(ansible-playbook) command.
3) none (An empty password/passphrase)
type: str
aliases:
- password
port:
description:
- The TCP port number or serial device port used to establish the
connection. Mutually exclusive with the I(console) option.
required: false
default: C(830) if C(mode = none), C(23) if C(mode = 'telnet'),
C('/dev/ttyUSB0') if (mode = 'serial')
type: int or str
ssh_private_key_file:
description:
- The path to the SSH private key file used to authenticate with the
Junos device. If this option is not specified, and no default value
is found using the algorithm below, then the SSH private key file
specified in the user's SSH configuration, or the
operating-system-specific default is used.
- This must be in the RSA PEM format, and not the newer OPENSSH
format. To check if the private key is in the correct format, issue
the command `head -n1 ~/.ssh/some_private_key` and ensure that
it's RSA and not OPENSSH. To create a key in the RSA PEM format,
issue the command `ssh-keygen -m PEM -t rsa -b 4096`. To convert
an OPENSSH key to an RSA key, issue the command `ssh-keygen -p -m
PEM -f ~/.ssh/some_private_key`
required: false
default: The first defined value from the following list
1) The C(ANSIBLE_NET_SSH_KEYFILE) environment variable.
(used by Ansible Tower)
2) The value specified using the C(--private-key) or
C(--key-file) command line arguments to the C(ansible) or
C(ansible-playbook) command.
3) none (the file specified in the user's SSH configuration,
or the operating-system-specific default)
type: path
aliases:
- ssh_keyfile
ssh_config:
description:
- The path to the SSH client configuration file. If this option is not
specified, then the PyEZ Device instance by default queries file
~/.ssh/config.
required: false
type: path
timeout:
description:
- The maximum number of seconds to wait for RPC responses from the
Junos device. This option does NOT control the initial connection
timeout value.
required: false
default: 30
type: int
user:
description:
- The username used to authenticate with the Junos device. This option
is required, but does not have to be specified explicitly by the
user due to the algorithm for determining the default value.
required: true
default: The first defined value from the following list
1) The C(ANSIBLE_NET_USERNAME) environment variable.
(used by Ansible Tower)
2) The C(remote_user) as defined by Ansible. Ansible sets this
value via several methods including
a) C(-u) or C(--user) command line arguments to the
C(ansible) or C(ansible-playbook) command.
b) C(ANSIBLE_REMOTE_USER) environment variable.
c) C(remote_user) configuration setting.
See the Ansible documentation for the precedence used to set
the C(remote_user) value.
3) The C(USER) environment variable.
type: str
aliases:
- username
cs_user:
description:
- The username used to authenticate with the console server over SSH.
This option is only required if you want to connect to a device over console
using SSH as transport. Mutually exclusive with the I(console) option.
required: false
type: str
aliases:
- console_username
cs_passwd:
description:
- The password used to authenticate with the console server over SSH.
This option is only required if you want to connect to a device over console
using SSH as transport. Mutually exclusive with the I(console) option.
required: false
type: str
aliases:
- console_password
huge_tree:
description:
- Parse XML with very deep trees and long text content.
required: false
type: bool
default: false
'''
LOGGING_DOCUMENTATION = '''
logging_options:
logdir:
description:
- The path to a directory, on the Ansible control machine, where
debugging information for the particular task is logged.
- If this option is specified, debugging information is logged to a
file named C({{ inventory_hostname }}.log) in the directory
specified by the I(logdir) option.
- The log file must be writeable. If the file already exists, it is
appended. It is the users responsibility to delete/rotate log files.
- The level of information logged in this file is controlled by
Ansible's verbosity, debug options and level option in task
- 1) By default, messages at level C(WARNING) or higher are logged.
- 2) If the C(-v) or C(--verbose) command-line options to the
C(ansible-playbook) command are specified, messages at level
C(INFO) or higher are logged.
- 3) If the C(-vv) (or more verbose) command-line option to the
C(ansible-playbook) command is specified, or the C(ANSIBLE_DEBUG)
environment variable is set, then messages at level C(DEBUG) or
higher are logged.
- 4) If C(level) is mentioned then messages at level C(level) or more are
logged.
- The I(logfile) and I(logdir) options are mutually exclusive. The
I(logdir) option is recommended for all new playbooks.
required: false
default: none
type: path
aliases:
- log_dir
logfile:
description:
- The path to a file, on the Ansible control machine, where debugging
information for the particular task is logged.
- The log file must be writeable. If the file already exists, it is
appended. It is the users responsibility to delete/rotate log files.
- The level of information logged in this file is controlled by
Ansible's verbosity, debug options and level option in task
- 1) By default, messages at level C(WARNING) or higher are logged.
- 2) If the C(-v) or C(--verbose) command-line options to the
C(ansible-playbook) command are specified, messages at level
C(INFO) or higher are logged.
- 3) If the C(-vv) (or more verbose) command-line option to the
C(ansible-playbook) command is specified, or the C(ANSIBLE_DEBUG)
environment variable is set, then messages at level C(DEBUG) or
higher are logged.
- 4) If C(level) is mentioned then messages at level C(level) or more are
logged.
- When tasks are executed against more than one target host,
one process is forked for each target host. (Up to the maximum
specified by the forks configuration. See
U(forks|http://docs.ansible.com/ansible/latest/intro_configuration.html#forks)
for details.) This means that the value of this option must be
unique per target host. This is usually accomplished by including
C({{ inventory_hostname }}) in the I(logfile) value. It is the
user's responsibility to ensure this value is unique per target
host.
- For this reason, this option is deprecated. It is maintained for
backwards compatibility. Use the I(logdir) option in new playbooks.
The I(logfile) and I(logdir) options are mutually exclusive.
required: false
default: none
type: path
aliases:
- log_file
level:
description:
- The level of information to be logged can be modified using this option
- 1) By default, messages at level C(WARNING) or higher are logged.
- 2) If the C(-v) or C(--verbose) command-line options to the
C(ansible-playbook) command are specified, messages at level
C(INFO) or higher are logged.
- 3) If the C(-vv) (or more verbose) command-line option to the
C(ansible-playbook) command is specified, or the C(ANSIBLE_DEBUG)
environment variable is set, then messages at level C(DEBUG) or
higher are logged.
- 4) If C(level) is mentioned then messages at level C(level) or more are
logged.
required: false
default: WARNING
type: str
choices:
- INFO
- DEBUG
'''
# _SUB_CONNECT_DOCUMENTATION is just _CONNECT_DOCUMENTATION with each
# line indented.
_SUB_CONNECT_DOCUMENTATION = ''
for line in _CONNECT_DOCUMENTATION.splitlines(True):
_SUB_CONNECT_DOCUMENTATION += ' ' + line
# Build actual DOCUMENTATION string by putting the pieces together.
CONNECTION_DOCUMENTATION = '''
connection_options:''' + _CONNECT_DOCUMENTATION + '''
requirements:
- U(junos-eznc|https://github.com/Juniper/py-junos-eznc) >= ''' + cfg.MIN_PYEZ_VERSION + '''
- Python >= 3.5
notes:
- The NETCONF system service must be enabled on the target Junos device.
'''
# The common argument specification for connecting to Junos devices.
connection_spec = {
'host': dict(type='str',
# Required at top-level.
required=False,
aliases=['hostname', 'ip'],
# See documentation for real default behavior.
# Default behavior coded in JuniperJunosActionModule.run()
default=None),
'user': dict(type='str',
# Required at top-level.
required=False,
aliases=['username'],
# See documentation for real default behavior.
# Default behavior coded in JuniperJunosActionModule.run()
default=None),
'passwd': dict(type='str',
required=False,
aliases=['password'],
# See documentation for real default behavior.
# Default behavior coded in JuniperJunosActionModule.run()
default=None,
no_log=True),
'cs_user': dict(type='str',
aliases=['console_username'],
required=False,
default=None),
'cs_passwd': dict(type='str',
aliases=['console_password'],
required=False,
default=None,
no_log=True),
'ssh_private_key_file': dict(type='path',
required=False,
aliases=['ssh_keyfile'],
# See documentation for real default behavior.
# Default behavior coded in
# JuniperJunosActionModule.run()
default=None),
'ssh_config': dict(type='path',
required=False,
default=None),
'mode': dict(choices=[None, 'telnet', 'serial'],
default=None),
'console': dict(type='str',
required=False,
default=None),
'port': dict(type='str',
required=False,
# See documentation for real default behavior.
# Default behavior coded in JuniperJunosModule.__init__()
default=None),
'baud': dict(type='int',
required=False,
# See documentation for real default behavior.
# Default behavior coded in JuniperJunosModule.__init__()
default=None),
'attempts': dict(type='int',
required=False,
# See documentation for real default behavior.
# Default behavior coded in JuniperJunosModule.__init__()
default=None),
'timeout': dict(type='int',
required=False,
default=30),
'huge_tree': dict(type='bool',
required=False,
default=False),
}
# Connection arguments which are mutually exclusive.
connection_spec_mutually_exclusive = [['mode', 'console'],
['port', 'console'],
['baud', 'console'],
['attempts', 'console'],
['cs_user', 'console'],
['cs_passwd', 'console']]
# Specify the logging spec.
logging_spec = {
'logfile': dict(type='path', required=False, default=None),
'logdir': dict(type='path', required=False, default=None),
'level': dict(choices=[None, 'INFO', 'DEBUG'], required=False, default=None)
}
# The logdir and logfile options are mutually exclusive.
logging_spec_mutually_exclusive = ['logfile', 'logdir']
# Other logging names which should be logged to the logfile
additional_logger_names = ['ncclient', 'paramiko']
# top_spec is connection_spec + logging_spec
top_spec = connection_spec
top_spec.update(logging_spec)
top_spec_mutually_exclusive = connection_spec_mutually_exclusive
top_spec_mutually_exclusive += logging_spec_mutually_exclusive
# "Hidden" arguments which are passed between the action plugin and the
# Junos module, but which should not be visible to users.
internal_spec = {
'_module_utils_path': dict(type='path',
default=None),
'_module_name': dict(type='str',
default=None),
'_inventory_hostname': dict(type='str',
default=None),
'_connection': dict(type='str',
default=None),
}
# Known RPC output formats
RPC_OUTPUT_FORMAT_CHOICES = ['text', 'xml', 'json']
# Known configuration formats
CONFIG_FORMAT_CHOICES = ['xml', 'set', 'text', 'json']
# Known configuration databases
CONFIG_DATABASE_CHOICES = ['candidate', 'committed']
# Known configuration actions
CONFIG_ACTION_CHOICES = ['set', 'merge', 'update',
'replace', 'override', 'overwrite', 'patch']
# Supported configuration modes
CONFIG_MODE_CHOICES = ['exclusive', 'private', 'dynamic', 'batch', 'ephemeral']
# Supported configuration models
CONFIG_MODEL_CHOICES = ['openconfig', 'custom', 'ietf', 'True']
class JuniperJunosModule(AnsibleModule):
"""A subclass of AnsibleModule used by all modules.
All modules share common behavior which is implemented in
this class.
Attributes:
dev: An instance of a PyEZ Device() object.
Public Methods:
exit_json: Close self.dev and call parent's exit_json().
fail_json: Close self.dev and call parent's fail_json().
check_pyez: Verify the PyEZ library is present and functional.
check_jsnapy: Verify the JSNAPy library is present and functional.
check_jxmlease: Verify the Jxmlease library is present and functional.
check_lxml_etree: Verify the lxml Etree library is present and
functional.
check_yaml: Verify the YAML library is present and functional.
parse_arg_to_list_of_dicts: Parses string_val into a list of dicts.
parse_ignore_warning_option: Parses the ignore_warning option.
parse_rollback_option: Parses the rollback option.
open: Open self.dev.
close: Close self.dev.
add_sw: Add an instance of jnp.junos.utils.sw.SW() to self.
open_configuration: Open cand. conf. db in exclusive/private/dynamic/batch/ephemeral mode.
close_configuration: Close candidate configuration database.
get_configuration: Return the device config. in the specified format.
rollback_configuration: Rollback device config. to the specified id.
check_configuration: Check the candidate configuration.
diff_configuration: Diff the candidate and committed configurations.
load_configuration: Load the candidate configuration.
commit_configuration: Commit the candidate configuration.
ping: Execute a ping command from a Junos device.
save_text_output: Save text output into a file.
"""
# Method overrides
def __init__(self,
argument_spec={},
mutually_exclusive=[],
min_pyez_version=cfg.MIN_PYEZ_VERSION,
min_lxml_etree_version=cfg.MIN_LXML_ETREE_VERSION,
min_jsnapy_version=None,
min_jxmlease_version=None,
min_yaml_version=None,
**kwargs):
"""Initialize a new JuniperJunosModule instance.
Combines module-specific parameters with the common parameters shared
by all modules. Performs additional checks on options.
Checks the minimum PyEZ version. Creates and opens the PyEZ Device instance.
Args:
agument_spec: Module-specific argument_spec added to top_spec.
mutually_exclusive: Module-specific mutually exclusive added to
top_spec_mutually_exclusive.
min_pyez_version: The minimum PyEZ version required by the module.
Since all modules require PyEZ this defaults to
MIN_PYEZ_VERSION.
min_lxml_etree_version: The minimum lxml Etree version required by
the module. Since most modules require
lxml Etree this defaults to
MIN_LXML_ETREE_VERSION.
min_jsnapy_version: The minimum JSNAPy version required by the
module. If this is None, the default, it
means the module does not explicitly require
jsnapy.
min_jxmlease_version: The minimum Jxmlease version required by the
module. If this is None, the default, it
means the module does not explicitly require
jxmlease.
min_yanml_version: The minimum YAML version required by the
module. If this is None, the default, it
means the module does not explicitly require
yaml.
**kwargs: All additional keyword arguments are passed to
AnsibleModule.__init__().
Returns:
A JuniperJunosModule instance object.
"""
#initialize default values here for error scenario while super is called
# by default local
self.conn_type = "local"
# Initialize the dev attribute
self.dev = None
# Initialize the config attribute
self.config = None
# Update argument_spec with the internal_spec
argument_spec.update(internal_spec)
# Update argument_spec with the top_spec
argument_spec.update(top_spec)
# Extend mutually_exclusive with connection_mutually_exclusive
mutually_exclusive += top_spec_mutually_exclusive
# Call parent's __init__()
super(JuniperJunosModule, self).__init__(
argument_spec=argument_spec,
mutually_exclusive=mutually_exclusive,
**kwargs)
# initialize the parameters
self.initialize_params()
# Remove any arguments in internal_spec
for arg_name in internal_spec:
self.params.pop(arg_name)
# check software compatibility for various 3rd party tools used
ret_output = cfg.check_sw_compatibility(min_pyez_version,
min_lxml_etree_version,
min_jsnapy_version,
min_jxmlease_version,
min_yaml_version)
if ret_output != 'success':
self.fail_json(msg="%s" % ret_output)
self.pyez_factory_loader = jnpr.junos.factory.factory_loader
self.pyez_factory_table = jnpr.junos.factory.table
self.pyez_op_table = jnpr.junos.op
self.pyez_exception = pyez_exception
self.ncclient_exception = cfg.ncclient_exception
self.etree = cfg.etree
self.jxmlease = cfg.jxmlease
self.yaml = cfg.yaml
if min_jsnapy_version is not None:
self.jsnapy = jnpr.jsnapy
# Setup logging.
self.logger = self._setup_logging()
# Open the PyEZ connection
if self.conn_type == "local":
self.open()
else:
self._pyez_conn = self.get_connection()
def initialize_params(self):
"""
Initalize the parameters in common module
"""
# priority for arguments is inventory < tasks < console
self.module_name = self.params.get('_module_name')
self.inventory_hostname = self.params.get('_inventory_hostname')
self.conn_type = self.params.get('_connection')
# Parse the console option
self._parse_console_options()
# Check that we have a user and host
if not self.params.get('host'):
self.fail_json(msg="missing required arguments: host")
if not self.params.get('user'):
self.fail_json(msg="missing required arguments: user")
# Default port based on mode.
if self.params.get('port') is None:
if self.params.get('mode') == 'telnet':
self.params['port'] = 23
elif self.params.get('mode') == 'serial':
self.params['port'] = '/dev/ttyUSB0'
else:
self.params['port'] = 830
else:
if self.params.get('mode') != 'serial':
try:
self.params['port'] = int(self.params['port'])
except ValueError:
self.fail_json(msg="The port option (%s) must be an "
"integer value." %
(self.params['port']))
else:
self.params['port'] = self.params['port']
if (self.params.get('mode') == 'telnet' or
self.params.get('mode') == 'serial'):
if self.params.get('baud') is None:
# Default baud if serial or telnet mode
self.params['baud'] = 9600
if self.params.get('attempts') is None:
# Default attempts if serial or telnet mode
self.params['attempts'] = 10
else:
if self.params.get('baud') is not None:
self.fail_json(msg="The baud option (%s) is not valid when "
"mode == none." % (self.params.get('baud')))
if self.params.get('attempts') is not None:
self.fail_json(msg="The attempts option (%s) is not valid when "
"mode == none." % (self.params.get('attempts')))
def get_connection(self):
if hasattr(self, "_pyez_connection"):
return self._pyez_connection
try:
capabilities = self.get_capabilities()
except ConnectionError as exc:
self.logger.debug("Connection might be local")
return
# module.fail_json(msg=to_text(exc, errors="surrogate_then_replace"))
network_api = capabilities.get("network_api")
if network_api == "pyez":
self._pyez_connection = Connection(self._socket_path)
else:
self.fail_json(msg="Invalid connection type %s" % network_api)
return self._pyez_connection
def get_capabilities(self):
if hasattr(self, "_pyez_junos_capabilities"):
return self._pyez_junos_capabilities
try:
capabilities = Connection(self._socket_path).get_capabilities()
except ConnectionError as exc:
raise exc
# module.fail_json(msg=to_text(exc, errors="surrogate_then_replace"))
self._pyez_junos_capabilities = json.loads(capabilities)
return self._pyez_junos_capabilities
def exit_json(self, **kwargs):
"""Close self.dev and call parent's exit_json().
Args:
**kwargs: All keyword arguments are passed to
AnsibleModule.exit_json().
"""
# Close the connection.
if self.conn_type == "local":
try:
self.close()
except TimeoutExpiredError:
if hasattr(self, 'logger'):
self.logger.debug("Ignoring dev.close() timeout error")
if hasattr(self, 'logger'):
self.logger.debug("Exit JSON: %s", kwargs)
# Call the parent's exit_json()
super(JuniperJunosModule, self).exit_json(**kwargs)
def fail_json(self, **kwargs):
"""Close self.dev and call parent's fail_json().
Args:
**kwargs: All keyword arguments are passed to
AnsibleModule.fail_json().
"""
# Close the configuration
self.close_configuration()
# Close the connection.
# if self.conn_type == "local":
try:
self.close()
except TimeoutExpiredError:
if hasattr(self, 'logger'):
self.logger.debug("Ignoring dev.close() timeout error")
if hasattr(self, 'logger'):
self.logger.debug("Fail JSON: %s", kwargs)
# Call the parent's fail_json()
super(JuniperJunosModule, self).fail_json(**kwargs)
# JuniperJunosModule-specific methods below this point.
def _parse_console_options(self):
"""Parse the console option value.
Parse the console option value and turn it into the equivalent:
host, mode, baud, attempts, and port options.
"""
if self.params.get('console') is not None:
try:
console_string = self.params.get('console')
# Subclass ArgumentParser to simply raise a ValueError
# rather than printing to stderr and calling sys.exit()
class QuiteArgumentParser(ArgumentParser):
def error(self, message):
raise ValueError(message)
# Parse the console_string.
parser = QuiteArgumentParser(add_help=False)
parser.add_argument('-t', '--telnet', default=None)
parser.add_argument('-p', '--port', default=None)
parser.add_argument('-b', '--baud', default=None)
parser.add_argument('-a', '--attempts', default=None)
parser.add_argument('--timeout', default=None)
con_params = vars(parser.parse_args(console_string.split()))
telnet_params = con_params.get('telnet', None)
# mode == 'telnet'
if telnet_params is not None:
# Split on ,
host_port = telnet_params.split(',', 1)
# Strip any leading/trailing whitespace or equal sign
# from host
host = host_port[0].strip(' ')
# Try to convert port to an int.
port = int(host_port[1])
# Successfully parsed. Set params values
self.params['mode'] = 'telnet'
self.params['host'] = host
self.params['port'] = port
# mode == serial
else:
port = con_params.get('port', None)
baud = con_params.get('baud', None)
attempts = con_params.get('attempts', None)
timeout = con_params.get('timeout', None) # not used
self.params['mode'] = 'serial'
if port is not None:
self.params['port'] = port
if baud is not None:
self.params['baud'] = baud
if attempts is not None:
self.params['attempts'] = attempts
# Remove the console option.
self.params.pop('console')
except ValueError as ex:
self.fail_json(msg="Unable to parse the console value (%s). "
"Error: %s" % (console_string, str(ex)))
except Exception as ex:
self.fail_json(msg="Unable to parse the console value (%s). "
"The value of the console argument is "
"typically in the format '--telnet "
"<console_hostname>,<console_port_number>'."
% (console_string))
def _setup_logging(self):
"""Setup logging for the module.
Performs several tasks to setup logging for the module. This includes:
1) Creating a Logger instance object for the name
jnpr.ansible_module.<mod_name>.
2) Sets the level for the Logger object depending on verbosity and
debug settings specified by the user.
3) Sets the level for other Logger objects specified in
additional_logger_names depending on verbosity and
debug settings specified by the user.
4) If the logfile or logdir option is specified, attach a FileHandler
instance which logs messages from jnpr.ansible_module.<mod_name> or
any of the names in additional_logger_names.
Returns:
Logger instance object for the name jnpr.ansible_module.<mod_name>.
"""
class CustomAdapter(logging.LoggerAdapter):
"""
Prepend the hostname, in brackets, to the log message.
"""
def process(self, msg, kwargs):
return '[%s] %s' % (self.extra['host'], msg), kwargs
# Default level to log.
level = logging.WARNING
# Log more if ANSIBLE_DEBUG or -v[v] is set.
if self._debug is True:
level = logging.DEBUG
elif self._verbosity == 1:
level = logging.INFO
elif self._verbosity > 1:
level = logging.DEBUG
# Set level as mentioned in task
elif self.params.get('level') is not None:
level = self.params.get('level')
# Get the logger object to be used for our logging.
logger = logging.getLogger('jnpr.ansible_module.' + self.module_name)
# Attach the NullHandler to avoid any errors if no logging is needed.
logger.addHandler(logging.NullHandler())
# Set the logging level for the modules logging. This will also control
# the amount of logging which goes into Ansible's log file.
logger.setLevel(level)
# Set the logging level for additional names. This will also control
# the amount of logging which goes into Ansible's log file.
for name in additional_logger_names:
logging.getLogger(name).setLevel(level)
# Get the name of the logfile based on logfile or logdir options.
logfile = None
if self.params.get('logfile') is not None:
logfile = self.params.get('logfile')
elif self.params.get('logdir') is not None:
logfile = os.path.normpath(self.params.get('logdir') + '/' +
self.params.get('host') + '.log')
# Create the FileHandler and attach it.
if logfile is not None:
try:
handler = logging.FileHandler(logfile, mode='a')
handler.setLevel(level)
# Create a custom formatter.
formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# add formatter to handler
handler.setFormatter(formatter)
# Handler should log anything from the 'jnpr.ansible_module.' namespace to
# catch PyEZ, JSNAPY, etc. logs.
logger.addHandler(handler)
for name in additional_logger_names:
logging.getLogger(name).addHandler(handler)
except IOError as ex:
self.fail_json(msg="Unable to open the log file %s. %s" %
(logfile, str(ex)))
# Use the CustomAdapter to add host information.
return CustomAdapter(logger, {'host': self.params.get('host')})
def parse_arg_to_list_of_dicts(self,
option_name,
string_val,
allow_bool_values=False):
"""Parses string_val into a list of dicts with bool and/or str values.
In order to handle all of the different ways that list of dict type
options may be specified, the arg_spec must set the option type to
'str'. This requires us to parse the string_val ourselves into the
required list of dicts. Handles Ansible-style keyword=value format for
specifying dictionaries. Also handles Ansible aliases for boolean
values if allow_bool_values is True.
Args:
option_name - The name of the option being parsed.
string_val - The string to be parse.
allow_bool_values - Whether or not boolean values are allowed.
Returns:
The list of dicts
Fails:
If there is an error parsing
"""
# Nothing to do if no string_val were specified.
if string_val is None:
return None
# Evaluate the string
kwargs = self.safe_eval(string_val)
if isinstance(kwargs, basestring):
# This might be a keyword1=value1 keyword2=value2 type string.
# The _check_type_dict method will parse this into a dict for us.
try:
kwargs = check_type_dict(kwargs)
except TypeError as exc:
self.fail_json(msg="The value of the %s option (%s) is "
"invalid. Unable to translate into "
"a list of dicts." %
(option_name, string_val, str(exc)))
# Now, if it's a dict, let's make it a list of one dict
if isinstance(kwargs, dict):
kwargs = [kwargs]
# Now, if it's not a list, we've got a problem.
if not isinstance(kwargs, list):
self.fail_json(msg="The value of the %s option (%s) is invalid. "
"Unable to translate into a list of dicts." %
(option_name, string_val))
# We've got a list, traverse each element to make sure it's a dict.
return_val = []
for kwarg in kwargs:
# If it's now a string, see if it can be parsed into a dictionary.
if isinstance(kwarg, basestring):
# This might be a keyword1=value1 keyword2=value2 type string.
# The _check_type_dict method will parse this into a dict.
try:
kwarg = check_type_dict(kwarg)
except TypeError as exc:
self.fail_json(msg="The value of the %s option (%s) is "
"invalid. Unable to translate into a "
"list of dicts." %
(option_name, string_val, str(exc)))
# Now if it's not a dict, there's a problem.
if not isinstance(kwarg, dict):
self.fail_json(msg="The value of the kwargs option (%s) is "
"invalid. Unable to translate into a list "
"of dicts." %
(option_name, string_val))
# check if allow_bool_values passed in kwargs
if "allow_bool_values" in kwarg:
allow_bool_values = kwarg.pop("allow_bool_values")
# Now we just need to make sure the key is a string and the value
# is a string or bool.
return_item = {}
for (k, v) in kwarg.items():
if not isinstance(k, basestring):
self.fail_json(msg="The value of the %s option (%s) "
"is invalid. Unable to translate into "
"a list of dicts." %
(option_name, string_val))
if allow_bool_values is True:
# Try to convert it to a boolean value. Will be None if it
# can't be converted.
try:
bool_val = boolean(v)
except TypeError:
bool_val = None
if bool_val is not None:
v = bool_val
return_item[k] = v
return_val.append(return_item)
return return_val
def parse_ignore_warning_option(self):
"""Parses the ignore_warning option.
ignore_warning may be a bool, str, or list of str. The Ansible type