├── .gitignore ├── LICENSE ├── README.md ├── experimental_donotuse ├── cisco_config_merge.py └── cisco_config_replace.py └── library ├── cisco_file_transfer.py ├── netmiko_connect └── netmiko_install_config /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | *.swp 3 | build 4 | dist 5 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # netmiko-ansible 2 | Ansible modules that use Netmiko 3 | 4 | Under construction -- work in progress. 5 | -------------------------------------------------------------------------------- /experimental_donotuse/cisco_config_merge.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | ''' 3 | Ansible module to perform config merge on Cisco IOS devices. 4 | 5 | This module presupposes that the relevant file has been transferred to the device 6 | 7 | The module is not idempotent and does not support check_mode 8 | ''' 9 | 10 | from ansible.module_utils.basic import * 11 | from netmiko import ConnectHandler 12 | 13 | def main(): 14 | ''' 15 | Ansible module to perform config merge on Cisco IOS devices. 16 | ''' 17 | 18 | module = AnsibleModule( 19 | argument_spec=dict( 20 | host=dict(required=True), 21 | port=dict(default=22, required=False), 22 | username=dict(required=True), 23 | password=dict(required=True), 24 | merge_file=dict(required=True), 25 | dest_file_system=dict(default='flash:', required=False), 26 | ), 27 | supports_check_mode=False 28 | ) 29 | 30 | net_device = { 31 | 'device_type': 'cisco_ios', 32 | 'ip': module.params['host'], 33 | 'username': module.params['username'], 34 | 'password': module.params['password'], 35 | 'port': int(module.params['port']), 36 | 'verbose': False, 37 | } 38 | 39 | ssh_conn = ConnectHandler(**net_device) 40 | ssh_conn.enable() 41 | merge_file = module.params['merge_file'] 42 | dest_file_system = module.params['dest_file_system'] 43 | 44 | # Disable file copy confirmation 45 | ssh_conn.send_config_set(['file prompt quiet']) 46 | 47 | # Perform config merge 48 | cmd = "copy {0}{1} running-config".format(dest_file_system, merge_file) 49 | output = ssh_conn.send_command(cmd) 50 | 51 | # Enable file copy confirmation 52 | ssh_conn.send_config_set(['file prompt alert']) 53 | 54 | if ' bytes copied in ' in output: 55 | module.exit_json(msg="File merged on remote device", 56 | changed=True) 57 | else: 58 | module.fail_json(msg="Unexpected failure during attempted config merge. " 59 | "Please verify the current configuration on the network device.") 60 | 61 | 62 | if __name__ == "__main__": 63 | main() 64 | -------------------------------------------------------------------------------- /experimental_donotuse/cisco_config_replace.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | ''' 3 | Ansible module to perform config replace on Cisco IOS devices. 4 | 5 | This module presupposes that the relevant file has been transferred to the device 6 | 7 | The module is not idempotent and does not support check_mode 8 | ''' 9 | 10 | from ansible.module_utils.basic import * 11 | from netmiko import ConnectHandler 12 | 13 | def main(): 14 | ''' 15 | Ansible module to perform config merge on Cisco IOS devices. 16 | ''' 17 | 18 | module = AnsibleModule( 19 | argument_spec=dict( 20 | host=dict(required=True), 21 | port=dict(default=22, required=False), 22 | username=dict(required=True), 23 | password=dict(required=True), 24 | merge_file=dict(required=True), 25 | dest_file_system=dict(default='flash:', required=False), 26 | ), 27 | supports_check_mode=False 28 | ) 29 | 30 | net_device = { 31 | 'device_type': 'cisco_ios', 32 | 'ip': module.params['host'], 33 | 'username': module.params['username'], 34 | 'password': module.params['password'], 35 | 'port': int(module.params['port']), 36 | 'verbose': False, 37 | } 38 | 39 | ssh_conn = ConnectHandler(**net_device) 40 | ssh_conn.enable() 41 | 42 | merge_file = module.params['merge_file'] 43 | dest_file_system = module.params['dest_file_system'] 44 | 45 | # Disable file copy confirmation 46 | ssh_conn.send_config_set(['file prompt quiet']) 47 | 48 | # Perform configure replace 49 | cmd = "configure replace {0}{1}".format(dest_file_system, merge_file) 50 | output = ssh_conn.send_command(cmd, delay_factor=8) 51 | 52 | # Enable file copy confirmation 53 | ssh_conn.send_config_set(['file prompt alert']) 54 | 55 | if 'The rollback configlet from the last pass is listed below' in output: 56 | module.exit_json(msg="The new configuration has been loaded successfully", 57 | changed=True) 58 | else: 59 | module.fail_json(msg="Unexpected failure during attempted configure replace. " 60 | "Please verify the current configuration of the network device.") 61 | 62 | 63 | if __name__ == "__main__": 64 | main() 65 | -------------------------------------------------------------------------------- /library/cisco_file_transfer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | ''' 3 | Ansible module to transfer files to Cisco IOS devices. 4 | ''' 5 | 6 | from ansible.module_utils.basic import * 7 | from netmiko import ConnectHandler, FileTransfer 8 | 9 | def main(): 10 | ''' 11 | Ansible module to transfer files to Cisco IOS devices. 12 | ''' 13 | 14 | module = AnsibleModule( 15 | argument_spec=dict( 16 | host=dict(required=True), 17 | port=dict(default=22, required=False), 18 | username=dict(required=True), 19 | password=dict(required=True), 20 | source_file=dict(required=True), 21 | dest_file=dict(required=True), 22 | dest_file_system=dict(required=False), 23 | enable_scp=dict(required=False, default=False, choices=BOOLEANS), 24 | overwrite=dict(required=False, default=True, choices=BOOLEANS), 25 | ), 26 | supports_check_mode=True 27 | ) 28 | 29 | net_device = { 30 | 'device_type': 'cisco_ios', 31 | 'ip': module.params['host'], 32 | 'username': module.params['username'], 33 | 'password': module.params['password'], 34 | 'port': int(module.params['port']), 35 | 'verbose': False, 36 | } 37 | 38 | ssh_conn = ConnectHandler(**net_device) 39 | source_file = module.params['source_file'] 40 | dest_file = module.params['dest_file'] 41 | enable_scp = module.boolean(module.params['enable_scp']) 42 | overwrite = module.boolean(module.params['overwrite']) 43 | check_mode = module.check_mode 44 | scp_changed = False 45 | 46 | with FileTransfer(ssh_conn, source_file, dest_file) as scp_transfer: 47 | 48 | # Check if file already exists and has correct MD5 49 | if scp_transfer.check_file_exists() and scp_transfer.compare_md5(): 50 | module.exit_json(msg="File exists and has correct MD5", changed=False) 51 | 52 | if not overwrite and scp_transfer.check_file_exists(): 53 | module.fail_json(msg="File already exists and overwrite set to false") 54 | 55 | if check_mode: 56 | if not scp_transfer.verify_space_available(): 57 | module.fail_json(msg="Insufficient space available on remote device") 58 | 59 | module.exit_json(msg="Check mode: file would be changed on the remote device", 60 | changed=True) 61 | 62 | # Verify space available on remote file system 63 | if not scp_transfer.verify_space_available(): 64 | module.fail_json(msg="Insufficient space available on remote device") 65 | 66 | # Transfer file 67 | if enable_scp: 68 | scp_transfer.enable_scp() 69 | scp_changed = True 70 | 71 | scp_transfer.transfer_file() 72 | if scp_transfer.verify_file(): 73 | if scp_changed: 74 | scp_transfer.disable_scp() 75 | module.exit_json(msg="File successfully transferred to remote device", 76 | changed=True) 77 | 78 | module.fail_json(msg="File transfer to remote device failed") 79 | 80 | 81 | if __name__ == "__main__": 82 | main() 83 | -------------------------------------------------------------------------------- /library/netmiko_connect: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | ''' 3 | Ansible module to test that Netmiko SSH connection to remote device is successful 4 | 5 | By default, verifies that '#' exists in the remote device prompt. 6 | ''' 7 | 8 | from ansible.module_utils.basic import * 9 | from netmiko import ConnectHandler 10 | 11 | try: 12 | # require netmiko >= 0.2.5 13 | import netmiko 14 | version = netmiko.__version__ 15 | major_ver, minor_ver, revision = version.split('.') 16 | if major_ver >= 0 and minor_ver >= 2 and revision >= 5: 17 | MEETS_REQUIREMENTS = True 18 | else: 19 | MEETS_REQUIREMENTS = False 20 | except ImportError: 21 | MEETS_REQUIREMENTS = False 22 | 23 | 24 | def main(): 25 | ''' 26 | Ansible module to test that Netmiko SSH connection to remote device is successful 27 | 28 | By default, verifies that '#' exists in the remote device prompt. 29 | ''' 30 | 31 | module = AnsibleModule( 32 | argument_spec=dict( 33 | device_type=dict(required=False, default='cisco_ios'), 34 | host=dict(required=True), 35 | port=dict(required=False, default=22), 36 | username=dict(required=True), 37 | password=dict(required=True), 38 | secret=dict(required=False, default=''), 39 | enable_mode=dict(required=False, default=False), 40 | check_string=dict(required=False, default='#'), 41 | ), 42 | supports_check_mode=False) 43 | 44 | if not MEETS_REQUIREMENTS: 45 | module.fail_json(msg='netmiko >= 0.2.5 is required for this module') 46 | 47 | net_device = { 48 | 'device_type': module.params['device_type'], 49 | 'ip': module.params['host'], 50 | 'port': int(module.params['port']), 51 | 'username': module.params['username'], 52 | 'password': module.params['password'], 53 | 'secret': module.params['secret'], 54 | 'verbose': False, 55 | } 56 | 57 | ssh_conn = ConnectHandler(**net_device) 58 | if module.params['enable_mode']: 59 | ssh_conn.enable() 60 | output = ssh_conn.find_prompt() 61 | if module.params['check_string'] in output: 62 | module.exit_json(msg="SSH connection completed successfully") 63 | else: 64 | module.fail_json(msg="Failed to detect check_string in output", output=output) 65 | 66 | 67 | if __name__ == "__main__": 68 | main() 69 | -------------------------------------------------------------------------------- /library/netmiko_install_config: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python2.7 2 | """This module uses Ansible to deploy device configurations and provide diffs 3 | across many vendors. 4 | """ 5 | 6 | DOCUMENTATION = ''' 7 | --- 8 | module: netmiko_install_config 9 | author: Tyler Christiansen 10 | version_added: "0.0.1" 11 | short_description: Load configuration onto a device running IOS-like software. 12 | description: 13 | - Load a snippets of Cisco IOS-style configuration. Despite the misleading 14 | name, this module is compatible with many different vendors. Although 15 | it is compatible with Juniper, it is strongly recommended that you use 16 | Juniper's ansible-junos-stdlib modules. 17 | You provide the configuration data in a file. The configuration can be 18 | a complete configuration or snippets. The file is iterated through and 19 | executed in order of the lines. Because IOS and IOS-like devices do 20 | not have syntax validation prior to configuration, this module cannot 21 | guarantee a file you supply is valid for that device. 22 | requirements: 23 | - netmiko >= 0.1.3 24 | options: 25 | host: 26 | description: 27 | - Set to {{ inventory_hostname }} 28 | required: true 29 | user: 30 | description: 31 | - Login username 32 | required: false 33 | default: $USER 34 | passwd: 35 | description: 36 | - Login password 37 | required: false 38 | default: key-based authentication 39 | file: 40 | description: 41 | - Path to the file containing the configuration data. 42 | required: true 43 | device_type: 44 | description: 45 | - OS type. See the NetMiko documentation for details. 46 | required: false 47 | default: cisco_ios 48 | log_file: 49 | description: 50 | - Path on the local server where the output is logged for 51 | debugging purposes 52 | required: false 53 | default: None 54 | diff_file: 55 | description: 56 | - Path to the file where any diffs will be written 57 | required: false 58 | default: None 59 | ''' 60 | 61 | EXAMPLES = ''' 62 | # load a cisco-style configuration file 63 | - netmiko_install_config: 64 | host={{ inventory_hostname }} 65 | file=ospf.conf 66 | # specify a user 67 | - netmiko_install_config: 68 | host={{ inventory_hostname }} 69 | file=bgp.conf 70 | user=unicorn 71 | # log output and diff file 72 | - netmiko_install_config: 73 | host={{ inventory_hostname }} 74 | file=vstp.conf 75 | log_file=output.log 76 | diff_file=config.diff 77 | # specify a different device type 78 | - netmiko_install_config: 79 | host={{ inventory_hostname }} 80 | file=ldp.conf 81 | device_type=brocade_vdx 82 | ''' 83 | 84 | import logging 85 | import os 86 | import difflib 87 | 88 | try: 89 | import netmiko 90 | MEETS_REQUIREMENTS = True 91 | except ImportError: 92 | MEETS_REQUIREMENTS = False 93 | 94 | def get_config(dev): 95 | """Returns the current configuration of an IOS-like device that supports 96 | `show running-config` 97 | """ 98 | return dev.send_command("show running-config") 99 | 100 | def install_config(module, dev): 101 | """Installs a complete or partial configuration on an IOS-like device by 102 | sending commands one at a time to the remote device. 103 | """ 104 | args = module.params 105 | results = {} 106 | config_file = os.path.abspath(args['file']) 107 | results['file'] = config_file 108 | results['changed'] = False 109 | 110 | logging.info("loading %s", config_file) 111 | 112 | try: 113 | if not dev.check_enable_mode(): 114 | dev.enable() 115 | # NetMiko automatically enters config mode, but not enable mode 116 | dev.send_config_from_file(config_file=config_file) 117 | results['changed'] = True 118 | except Exception as err: 119 | logging.error("Exception: %s", err.message) 120 | raise err 121 | 122 | dev.exit_config_mode() 123 | return results 124 | 125 | def diff_config(cfg_old, cfg_new): 126 | """performs a diff on `cfg_old` and `cfg_new`, returning the resulting 127 | diff. 128 | """ 129 | return difflib.unified_diff(cfg_old.strip().splitlines(), 130 | cfg_new.strip().splitlines(), 131 | fromfile='old config', 132 | tofile='new config', 133 | lineterm='') 134 | 135 | def load(module): 136 | """Kicks off the process of installing a configuration on an IOS-like device 137 | and determining if that device's previous and new configurations should be 138 | diffed. 139 | """ 140 | args = module.params 141 | logfile = args['log_file'] 142 | 143 | if logfile is not None: 144 | logging.basicConfig(filename=logfile, level=logging.INFO, 145 | format='%(asctime)s:%(name)s:%(message)s') 146 | logging.getLogger().name = 'CONFIG:' + args['host'] 147 | 148 | logging.info("connecting to %s", args['host']) 149 | dev_params = {"device_type": args['device_type'], 150 | "ip": args['host'], 151 | "username": args['user'], 152 | "password": args['passwd'], 153 | "verbose": False} 154 | 155 | try: 156 | dispatcher = netmiko.ssh_dispatcher(device_type=args['device_type']) 157 | dev = dispatcher(**dev_params) 158 | except Exception as err: 159 | logging.error("Exception: %s", err.message) 160 | raise err 161 | 162 | if args['diff_file']: 163 | original_config = get_config(dev) 164 | 165 | results = install_config(module, dev) 166 | if args['diff_file']: 167 | new_config = get_config(dev) 168 | diff = diff_config(original_config, new_config) 169 | if diff is not None: 170 | diff_file = module.params['diff_file'] 171 | if diff_file is not None: 172 | try: 173 | with open(diff_file, "w") as file_handle: 174 | file_handle.write('\n'.join(diff)) 175 | except Exception as err: 176 | logging.error("Exception: %s", err.message) 177 | raise err 178 | 179 | module.exit_json(**results) 180 | 181 | 182 | def main(): 183 | """Kicks off the Ansible bootstrapping. 184 | """ 185 | module = AnsibleModule( 186 | argument_spec=dict( 187 | host=dict(required=True), 188 | user=dict(required=False, default=os.getenv('USER')), 189 | passwd=dict(required=False, default=None), 190 | file=dict(required=True), 191 | device_type=dict(required=False, default='cisco_ios'), 192 | log_file=dict(required=False, default=None), 193 | diff_file=dict(required=False, default=None) 194 | ), 195 | supports_check_mode=False) 196 | 197 | if not MEETS_REQUIREMENTS: 198 | module.fail_json(msg='netmiko >= 0.1.3 is required for this module') 199 | return 200 | 201 | load(module) 202 | 203 | from ansible.module_utils.basic import * 204 | main() 205 | --------------------------------------------------------------------------------