├── .gitignore ├── .yamllint ├── CHANGELOG.rst ├── LICENSE ├── README.md ├── action_plugins ├── extract_banners.py ├── ios_user_manager.py └── parse_validate_acl.py ├── bindep.txt ├── defaults ├── cloud_vpn │ └── providers │ │ └── csr │ │ └── initiator.yaml └── main.yml ├── docs ├── cloud_vpn │ ├── configure_routing_initiator.md │ └── configure_vpn_initiator.md ├── config_manager │ ├── get.md │ └── load.md └── get_facts.md ├── filter_plugins └── ios.py ├── handlers └── main.yml ├── includes ├── args_adapter.yaml ├── checkpoint │ ├── create.yaml │ ├── remove.yaml │ └── restore.yaml ├── configure │ ├── merge.yaml │ ├── replace.yaml │ └── terminal.yaml ├── init.yaml ├── run_cli.yaml └── wrapper.yaml ├── library ├── ios_capabilities.py ├── ios_command.py └── ios_user_manager.py ├── meta └── main.yml ├── parser_templates ├── cli │ ├── show_cdp_neighbors_detail.yaml │ ├── show_interfaces.yaml │ ├── show_interfaces_transceiver.yaml │ ├── show_ip_bgp_summary.yaml │ ├── show_ip_vrf_detail.yaml │ ├── show_lldp_neighbors_detail.yaml │ └── show_version.yaml ├── config │ ├── show_ip_prefix_list.yaml │ └── show_run_interface.yaml ├── config_manager │ └── global.yaml └── net_operations │ ├── show_ip_access_list.yaml │ └── show_logs_acl_logs.yaml ├── requirements.txt ├── tasks ├── cloud_vpn │ ├── add_host_initiator.yaml │ ├── add_host_responder.yaml │ ├── configure_routing_initiator.yaml │ ├── configure_routing_responder.yaml │ ├── configure_vpn_initiator.yaml │ ├── configure_vpn_responder.yaml │ ├── noop.yaml │ ├── providers │ │ └── csr │ │ │ └── initiator │ │ │ ├── add_host.yaml │ │ │ ├── configure_routing.yaml │ │ │ ├── configure_vpn.yaml │ │ │ └── show_login_info.yaml │ ├── show_login_info_initiator.yaml │ ├── show_login_info_responder.yaml │ ├── unconfigure_initiator.yaml │ └── unconfigure_responder.yaml ├── config_manager │ ├── get.yaml │ ├── load.yaml │ └── save.yaml ├── configure_user.yaml ├── get_facts.yaml ├── main.yml ├── net_operations │ ├── parse_validate_acl.yaml │ ├── pre_config_sink_device.yaml │ └── sink_packet_capture_logs.yaml └── noop.yaml ├── templates ├── cloud_vpn │ └── providers │ │ └── csr │ │ └── initiator │ │ ├── aws_vpn │ │ ├── configure_routing_bgp.j2 │ │ ├── configure_routing_static.j2 │ │ └── configure_vpn.j2 │ │ ├── configure_routing_bgp.j2 │ │ ├── configure_routing_static.j2 │ │ └── configure_vpn.j2 └── configure_user.j2 ├── test-requirements.txt ├── tests ├── config_manager │ ├── config_manager │ │ ├── tasks │ │ │ ├── get.yml │ │ │ ├── load.yml │ │ │ └── main.yml │ │ ├── templates │ │ │ ├── csr01_config_error.j2 │ │ │ └── csr01_config_valid.j2 │ │ └── vars │ │ │ ├── default.yml │ │ │ └── load.yml │ └── test.yml ├── inventory ├── parser_templates │ └── cli │ │ ├── show_interfaces │ │ ├── 03.16.08.S.txt │ │ └── main.yaml │ │ ├── show_ip_bgp_summary │ │ ├── 03.14.00.S.txt │ │ ├── 12.2(33)SXH5.txt │ │ ├── 15.1(2)T5.txt │ │ ├── bgp_not_active.txt │ │ └── main.yaml │ │ ├── show_ip_vrf_detail │ │ ├── 03.14.00.S.txt │ │ ├── 12.2(33)SXH5.txt │ │ └── main.yaml │ │ └── show_version │ │ ├── 15.1.4.txt │ │ ├── 15.5.1.txt │ │ ├── 16.6.4.txt │ │ └── main.yaml ├── test.yaml ├── test_config_manager.yaml └── test_parser_templates.yaml ├── tools └── test-setup.sh ├── tox.ini └── vars ├── get_facts_command_map.yaml └── main.yml /.gitignore: -------------------------------------------------------------------------------- 1 | # IDE 2 | .vscode/ 3 | 4 | # Ansible 5 | *.log 6 | *.retry 7 | *.swp 8 | !*.gitkeep 9 | ansible.cfg 10 | 11 | # Byte-compiled / optimized / DLL files 12 | __pycache__/ 13 | *.py[cod] 14 | *$py.class 15 | 16 | # C extensions 17 | *.so 18 | 19 | # Distribution / packaging 20 | .Python 21 | build/ 22 | develop-eggs/ 23 | dist/ 24 | downloads/ 25 | eggs/ 26 | .eggs/ 27 | lib64/ 28 | parts/ 29 | sdist/ 30 | var/ 31 | wheels/ 32 | *.egg-info/ 33 | .installed.cfg 34 | *.egg 35 | MANIFEST 36 | 37 | # PyInstaller 38 | # Usually these files are written by a python script from a template 39 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 40 | *.manifest 41 | *.spec 42 | 43 | # Installer logs 44 | pip-log.txt 45 | pip-delete-this-directory.txt 46 | 47 | # Unit test / coverage reports 48 | htmlcov/ 49 | .tox/ 50 | .coverage 51 | .coverage.* 52 | .cache 53 | nosetests.xml 54 | coverage.xml 55 | *.cover 56 | .hypothesis/ 57 | .pytest_cache/ 58 | 59 | # Translations 60 | *.mo 61 | *.pot 62 | 63 | # Django stuff: 64 | *.log 65 | local_settings.py 66 | db.sqlite3 67 | 68 | # Flask stuff: 69 | instance/ 70 | .webassets-cache 71 | 72 | # Scrapy stuff: 73 | .scrapy 74 | 75 | # Sphinx documentation 76 | docs/_build/ 77 | 78 | # PyBuilder 79 | target/ 80 | 81 | # Jupyter Notebook 82 | .ipynb_checkpoints 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # celery beat schedule file 88 | celerybeat-schedule 89 | 90 | # SageMath parsed files 91 | *.sage.py 92 | 93 | # Environments 94 | .env 95 | .venv 96 | env/ 97 | venv/ 98 | ENV/ 99 | env.bak/ 100 | venv.bak/ 101 | 102 | # Spyder project settings 103 | .spyderproject 104 | .spyproject 105 | 106 | # Rope project settings 107 | .ropeproject 108 | 109 | # mkdocs documentation 110 | /site 111 | 112 | # mypy 113 | .mypy_cache/ 114 | -------------------------------------------------------------------------------- /.yamllint: -------------------------------------------------------------------------------- 1 | extends: default 2 | 3 | ignore: | 4 | .tox 5 | 6 | rules: 7 | braces: 8 | max-spaces-inside: 1 9 | level: error 10 | brackets: 11 | max-spaces-inside: 1 12 | level: error 13 | line-length: disable 14 | -------------------------------------------------------------------------------- /CHANGELOG.rst: -------------------------------------------------------------------------------- 1 | ========================= 2 | Ansible Network cisco_ios 3 | ========================= 4 | .. _cisco_ios_v2.7.1: 5 | 6 | v2.7.1 7 | ====== 8 | 9 | .. _cisco_ios_v2.7.1_Minor Changes: 10 | 11 | Minor Changes 12 | ------------- 13 | 14 | - Adds parser for reload reason. `ios-#87 `_. 15 | - Fixed message ``missing required arg: config_manager_text``. `ios-#88 `_. 16 | - Remove set defaults task files. `ios-#89 `_. 17 | - Use default template if no specific peer provider folder is present. `ios-#90 `_. 18 | - Add unconfigure task hooks. `ios-#92 `_. 19 | 20 | .. _cisco_ios_v2.7.0: 21 | 22 | v2.7.0 23 | ====== 24 | 25 | .. _cisco_ios_v2.7.0_Major Changes: 26 | 27 | Major Changes 28 | ------------- 29 | 30 | - Initial release of 2.7.0 ``cisco_ios`` Ansible role that is supported with Ansible 2.7.0 31 | - Dependant role ``ansible-network.network-engine`` should be upgraded with version >= 2.7.2 32 | 33 | .. _cisco_ios_v2.7.0_Bugfixes: 34 | 35 | Bugfixes 36 | -------- 37 | 38 | - multiline banner processing (cli_config issue) (#69) 39 | - Ensure that subset is a list. Align docs with fact map (#47) 40 | - Created test for show_interfaces parser (#58) 41 | - fix for 'interfaces' facts (#55) 42 | - fix for handling config text with lines containing only whitespace chars (#64) 43 | 44 | .. _cisco_ios_v2.6.3: 45 | 46 | v2.6.3 47 | ====== 48 | 49 | .. _cisco_ios_v2.6.3_New Features 50 | 51 | New Features 52 | ------------ 53 | 54 | - NEW provider tasks and parsers for net_operations role 55 | 56 | .. _cisco_ios_v2.6.3_Bugfixes: 57 | 58 | Bugfixes 59 | -------- 60 | 61 | - configure_user task should use config_manager_file instead of config_manager_text 62 | - uptime facts from cisco IOS has separate keys for year, week, days hours and time 63 | 64 | .. _cisco_ios_v2.6.2: 65 | 66 | v2.6.2 67 | ====== 68 | 69 | .. _cisco_ios_v2.6.2_New Features 70 | 71 | New Features 72 | ------------ 73 | 74 | - NEW Added CPF and Fiber Optic DOM parser 75 | - NEW Added dependency role plugin check 76 | 77 | .. _cisco_ios_v2.6.1: 78 | 79 | v2.6.1 80 | ====== 81 | 82 | .. _cisco_ios_v2.6.1_New Action Plugins: 83 | 84 | New Action Plugins 85 | ------------------ 86 | 87 | - NEW ``ios_user_manager`` action plugin 88 | 89 | .. _cisco_ios_v2.6.1_New Tasks: 90 | 91 | New Tasks 92 | --------- 93 | 94 | - NEW ``configure_user`` task 95 | 96 | .. _cisco_ios_v2.6.1_Bugfixes: 97 | 98 | Bugfixes 99 | -------- 100 | 101 | - Refactor vrf and bgp output and improve reliability (#29) 102 | - better support for working with config_manager tasks 103 | 104 | devel 105 | ===== 106 | 107 | New Functions 108 | ------------- 109 | 110 | - NEW `get_facts` retrive and parse facts from cisco ios devices 111 | - NEW `config_manager/get` support for config_manager get function 112 | - NEW `config_manager/load` support for config_manager load function 113 | - NEW `config_manager/save` support for config_manager save function 114 | - NEW `configure_user` support for configuring users on cisco ios devices 115 | 116 | 117 | Major Changes 118 | ------------- 119 | 120 | - Initial release of the `cisco_ios` role. 121 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # cisco_ios 2 | 3 | This Ansible Network role provides a set of platform dependent fuctions that 4 | are designed to work with Cisco IOS network devices. The functions included 5 | int his role inlcuding both configuration and fact collection. 6 | 7 | ## Requirements 8 | 9 | * Ansible 2.6 or later 10 | * Ansible Network Engine Role 2.6.0 or later 11 | 12 | ## Functions 13 | 14 | This section provides a list of the availabe functions that are including 15 | in this role. Any of the provided functions can be implemented in Ansible 16 | playbooks to perform automation activities on Cisco IOS devices. 17 | 18 | Please see the documentation link for each function for details on how to use 19 | the function in an Ansible playbook. 20 | 21 | * get_facts [[source]](https://github.com/ansible-network/cisco_ios/blob/devel/tasks/get_facts.yaml) [[docs]](https://github.com/ansible-network/cisco_ios/blob/devel/docs/get_facts.md) 22 | 23 | ### Config Manager 24 | * config_manager/get [[source]](https://github.com/ansible-network/cisco_ios/blob/devel/tasks/config_manager/get.yaml) [[docs]](https://github.com/ansible-network/cisco_ios/blob/devel/docs/config_manager/get.md) 25 | * config_manager/load [[source]](https://github.com/ansible-network/cisco_ios/blob/devel/tasks/config_manager/load.yaml) [[docs]](https://github.com/ansible-network/cisco_ios/blob/devel/docs/config_manager/load.md) 26 | 27 | ### Cloud VPN 28 | * cloud_vpn/configure_vpn_initiator [[source]](https://github.com/ansible-network/cisco_ios/blob/devel/tasks/cloud_vpn/configure_vpn_initiator.yaml) [[docs]](https://github.com/ansible-network/cisco_ios/blob/devel/docs/cloud_vpn/configure_vpn_initiator.md) 29 | * cloud_vpn/configure_routing_initiator [[source]](https://github.com/ansible-network/cisco_ios/blob/devel/tasks/cloud_vpn/configure_routing_initiator.yaml) [[docs]](https://github.com/ansible-network/cisco_ios/blob/devel/docs/cloud_vpn/configure_routing_initiator.md) 30 | 31 | ## License 32 | 33 | GPLv3 34 | 35 | ## Author Information 36 | 37 | Ansible Network Community 38 | -------------------------------------------------------------------------------- /action_plugins/extract_banners.py: -------------------------------------------------------------------------------- 1 | # (c) 2018, Ansible by Red Hat, inc 2 | # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) 3 | # 4 | # You should have received a copy of the GNU General Public License 5 | # along with Ansible. If not, see . 6 | # 7 | from __future__ import (absolute_import, division, print_function) 8 | __metaclass__ = type 9 | 10 | ANSIBLE_METADATA = {'metadata_version': '1.1', 11 | 'status': ['preview'], 12 | 'supported_by': 'network'} 13 | 14 | DOCUMENTATION = """ 15 | --- 16 | module: extract_banners 17 | author: Ansible Network Team 18 | short_description: remove banners from config text 19 | description: 20 | - The config text specified in C(config) will be used to extract banners 21 | from it. Banners need to be executed on device in special manner. It 22 | returns configs with banner removed and a dictionary of banners 23 | version_added: "2.7" 24 | options: 25 | config: 26 | description: 27 | - Config text from which banners need to be extracted. 28 | required: yes 29 | default: null 30 | """ 31 | 32 | EXAMPLES = """ 33 | - name: extract multiline banners 34 | extract_banners: 35 | config: "{{ ios_config_text }}" 36 | 37 | """ 38 | 39 | RETURN = """ 40 | config: 41 | description: returns the config with masked banners 42 | returned: always 43 | type: str 44 | banners: 45 | description: returns the extracted banners 46 | returned: always 47 | type: dict 48 | """ 49 | import re 50 | from ansible.plugins.action import ActionBase 51 | from ansible.module_utils._text import to_text 52 | from ansible.errors import AnsibleError 53 | 54 | try: 55 | from __main__ import display 56 | except ImportError: 57 | from ansible.utils.display import Display 58 | display = Display() 59 | 60 | 61 | class ActionModule(ActionBase): 62 | 63 | def run(self, tmp=None, task_vars=None): 64 | ''' handler for extract_banners ''' 65 | 66 | if task_vars is None: 67 | task_vars = dict() 68 | 69 | result = super(ActionModule, self).run(tmp, task_vars) 70 | del tmp # tmp no longer has any effect 71 | 72 | try: 73 | config = self._task.args['config'] 74 | except KeyError as exc: 75 | raise AnsibleError(to_text(exc)) 76 | 77 | # make config required argument 78 | if not config: 79 | raise AnsibleError('missing required argument `config`') 80 | 81 | banners, masked_config = self._extract_banners(config) 82 | result['config'] = masked_config 83 | result['banners'] = banners 84 | return result 85 | 86 | def _extract_banners(self, config): 87 | config_lines = config.split('\n') 88 | found_banner_start = 0 89 | banner_meta = [] 90 | for linenum, line in enumerate(config_lines): 91 | if not found_banner_start: 92 | banner_start = re.search(r'^banner\s+(\w+)\s+(.*)', line) 93 | if banner_start: 94 | banner_cmd = banner_start.group(1) 95 | try: 96 | banner_delimiter = banner_start.group(2) 97 | banner_delimiter = banner_delimiter.strip() 98 | banner_delimiter_esc = re.escape(banner_delimiter) 99 | except Exception: 100 | continue 101 | banner_start_index = linenum 102 | found_banner_start = 1 103 | continue 104 | 105 | if found_banner_start: 106 | # Search for delimiter found in current banner start 107 | regex = r'%s' % banner_delimiter_esc 108 | banner_end = re.search(regex, line) 109 | if banner_end: 110 | found_banner_start = 0 111 | kwargs = { 112 | 'banner_cmd': banner_cmd, 113 | 'banner_delimiter': banner_delimiter, 114 | 'banner_start_index': banner_start_index, 115 | 'banner_end_index': linenum, 116 | } 117 | banner_meta.append(kwargs) 118 | 119 | # Build banners from extracted data 120 | banner_lines = [] 121 | for banner in banner_meta: 122 | banner_lines.append('banner %s %s' % (banner['banner_cmd'], 123 | banner['banner_delimiter'])) 124 | banner_conf_lines = config_lines[banner['banner_start_index'] + 1: banner['banner_end_index']] 125 | for index, conf_line in enumerate(banner_conf_lines): 126 | banner_lines.append(conf_line) 127 | banner_lines.append('%s' % banner['banner_delimiter']) 128 | 129 | # Delete banner lines from config 130 | for banner in banner_meta: 131 | banner_lines_range = range(banner['banner_start_index'], 132 | banner['banner_end_index'] + 1) 133 | for index in banner_lines_range: 134 | config_lines[index] = '! banner removed' 135 | 136 | configs = '\n'.join(config_lines) 137 | return (banner_lines, configs) 138 | -------------------------------------------------------------------------------- /action_plugins/ios_user_manager.py: -------------------------------------------------------------------------------- 1 | # (c) 2018, Ansible by Red Hat, inc 2 | # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) 3 | # 4 | # You should have received a copy of the GNU General Public License 5 | # along with Ansible. If not, see . 6 | # 7 | from __future__ import (absolute_import, division, print_function) 8 | __metaclass__ = type 9 | 10 | ANSIBLE_METADATA = {'metadata_version': '1.1', 11 | 'status': ['preview'], 12 | 'supported_by': 'network'} 13 | import re 14 | import base64 15 | import hashlib 16 | 17 | from ansible.plugins.action import ActionBase 18 | 19 | 20 | class UserManager: 21 | 22 | def __init__(self, new_users, user_config_data): 23 | self.__new_users = new_users 24 | self.__user_config_data = user_config_data 25 | 26 | @staticmethod 27 | def calculate_fingerprint(sshkey): 28 | if ' ' in sshkey: 29 | keyparts = sshkey.split(' ') 30 | keyparts[1] = hashlib.md5(base64.b64decode(keyparts[1])).hexdigest().upper() 31 | return ' '.join(keyparts) 32 | 33 | else: 34 | return 'ssh-rsa %s' % hashlib.md5(base64.b64decode(sshkey)).hexdigest().upper() 35 | 36 | def _parse_view(self, data): 37 | match = re.search(r'view (\S+)', data, re.M) 38 | if match: 39 | return match.group(1) 40 | 41 | def _parse_sshkey(self, data): 42 | match = re.search(r'key-hash (\S+ \S+(?: .+)?)$', data, re.M) 43 | if match: 44 | return match.group(1) 45 | 46 | def _parse_privilege(self, data): 47 | match = re.search(r'privilege (\S+)', data, re.M) 48 | if match: 49 | return int(match.group(1)) 50 | 51 | def generate_existing_users(self): 52 | match = re.findall(r'(?:^(?:u|\s{2}u))sername (\S+)', self.__user_config_data, re.M) 53 | if not match: 54 | return [] 55 | 56 | existing_users = [] 57 | 58 | for user in set(match): 59 | regex = r'username %s .+$' % user 60 | cfg = re.findall(regex, self.__user_config_data, re.M) 61 | cfg = '\n'.join(cfg) 62 | sshregex = r'username %s\n\s+key-hash .+$' % user 63 | sshcfg = re.findall(sshregex, self.__user_config_data, re.M) 64 | sshcfg = '\n'.join(sshcfg) 65 | 66 | obj = { 67 | 'name': user, 68 | 'sshkey': self._parse_sshkey(sshcfg), 69 | 'privilege': self._parse_privilege(cfg), 70 | 'view': self._parse_view(cfg) 71 | } 72 | 73 | filtered = {k: v for k, v in obj.items() if v is not None} 74 | obj.clear() 75 | obj.update(filtered) 76 | 77 | existing_users.append(obj) 78 | 79 | return existing_users 80 | 81 | def filter_users(self): 82 | want = self.__new_users 83 | for user in want: 84 | if 'sshkey' in user: 85 | user['sshkey'] = self.calculate_fingerprint(user['sshkey']) 86 | 87 | have = self.generate_existing_users() 88 | filtered_users = [x for x in want if x not in have] 89 | 90 | changed = True if len(filtered_users) > 0 else False 91 | 92 | return changed, filtered_users 93 | 94 | 95 | class ActionModule(ActionBase): 96 | 97 | def run(self, tmp=None, task_vars=None): 98 | if task_vars is None: 99 | task_vars = dict() 100 | 101 | result = super(ActionModule, self).run(tmp, task_vars) 102 | 103 | try: 104 | new_users = self._task.args['new_users'] 105 | user_config_data = self._task.args['user_config'] 106 | except KeyError as exc: 107 | return {'failed': True, 'msg': 'missing required argument: %s' % exc} 108 | 109 | result['changed'], result['stdout'] = UserManager(new_users, user_config_data).filter_users() 110 | 111 | return result 112 | -------------------------------------------------------------------------------- /action_plugins/parse_validate_acl.py: -------------------------------------------------------------------------------- 1 | # (c) 2018, Ansible Inc, 2 | # 3 | # This file is part of Ansible 4 | # 5 | # Ansible is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # Ansible is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with Ansible. If not, see . 17 | from __future__ import (absolute_import, division, print_function) 18 | __metaclass__ = type 19 | 20 | import copy 21 | import os 22 | import time 23 | import re 24 | import hashlib 25 | import netaddr 26 | import json 27 | import socket 28 | 29 | from ansible.module_utils._text import to_bytes, to_text 30 | from ansible.module_utils.connection import Connection 31 | from ansible.errors import AnsibleError 32 | from ansible.plugins.action import ActionBase 33 | from ansible.module_utils.six.moves.urllib.parse import urlsplit 34 | from ansible.utils.path import unfrackpath 35 | 36 | try: 37 | from __main__ import display 38 | except ImportError: 39 | from ansible.utils.display import Display 40 | display = Display() 41 | 42 | 43 | class ActionModule(ActionBase): 44 | 45 | def run(self, tmp=None, task_vars=None): 46 | result = super(ActionModule, self).run(task_vars=task_vars) 47 | 48 | try: 49 | show_acl_output_buffer = self._task.args.get('show_acl_output_buffer') 50 | except KeyError as exc: 51 | return {'failed': True, 'msg': 'missing required argument: %s' % exc} 52 | 53 | try: 54 | parser = self._task.args.get('parser') 55 | except KeyError as exc: 56 | return {'failed': True, 'msg': 'missing required argument: %s' % exc} 57 | 58 | try: 59 | generated_flow_file = self._task.args.get('generated_flow_file') 60 | except KeyError as exc: 61 | return {'failed': True, 'msg': 'missing required argument: %s' % exc} 62 | 63 | generated_flow_file = unfrackpath(generated_flow_file) 64 | dest = generated_flow_file 65 | 66 | parser = unfrackpath(parser) 67 | if not os.path.exists(parser): 68 | return {'failed': True, 'msg': 'path: %s does not exist.' % parser} 69 | parser_file = parser 70 | 71 | pd_json = self._parse_acl_with_textfsm( 72 | parser_file, show_acl_output_buffer) 73 | try: 74 | changed = self._write_packet_dict(dest, pd_json) 75 | except IOError as exc: 76 | result['failed'] = True 77 | result['msg'] = ('Exception received : %s' % exc) 78 | 79 | result['changed'] = changed 80 | if changed: 81 | result['destination'] = dest 82 | else: 83 | result['dest_unchanged'] = dest 84 | 85 | return result 86 | 87 | def _create_packet_dict(self, cmd_out): 88 | import warnings 89 | with warnings.catch_warnings(record=True): 90 | warnings.simplefilter("always") 91 | from trigger.acl import parse 92 | import netaddr 93 | import json 94 | import uuid 95 | 96 | # pd is list of dictionary of packets 97 | pd = [] 98 | lines = cmd_out.split('\n') 99 | for index, line in enumerate(lines): 100 | line = to_bytes(line, errors='surrogate_or_strict') 101 | pd_it = {} 102 | try: 103 | p = parse(line) 104 | except Exception: 105 | continue 106 | 107 | if p.terms: 108 | match = p.terms[0].match 109 | for key in match: 110 | if key == 'source-address': 111 | for m in match["source-address"]: 112 | v = netaddr.IPNetwork(str(m)) 113 | # Return the host in middle of subnet 114 | size_subnet = v.size 115 | host_index = int(size_subnet / 2) 116 | pd_it["src"] = str(v[host_index]) 117 | if key == 'destination-address': 118 | for m in match["destination-address"]: 119 | v = netaddr.IPNetwork(str(m)) 120 | # Return the host in middle of subnet 121 | size_subnet = v.size 122 | host_index = int(size_subnet / 2) 123 | pd_it["dst"] = str(v[host_index]) 124 | if key == 'protocol': 125 | for m in match['protocol']: 126 | pd_it["proto"] = str(m) 127 | if key == 'destination-port': 128 | for m in match["destination-port"]: 129 | pd_it['dst_port'] = str(m) 130 | if key == 'source-port': 131 | for m in match["source-port"]: 132 | pd_it['src_port'] = str(m) 133 | 134 | action = p.terms[0].action 135 | for act in action: 136 | pd_it["action"] = act 137 | 138 | if pd_it is not None: 139 | if "dst" not in pd_it: 140 | pd_it["dst"] = "any" 141 | if "src" not in pd_it: 142 | pd_it["src"] = "any" 143 | pd_it["service_line_index"] = str(index) 144 | pd.append(pd_it) 145 | 146 | return json.dumps(pd, indent=4) 147 | 148 | def _write_packet_dict(self, dest, contents): 149 | # Check for Idempotency 150 | if os.path.exists(dest): 151 | try: 152 | with open(dest, 'r') as f: 153 | old_content = f.read() 154 | except IOError as ioexc: 155 | raise IOError(ioexc) 156 | sha1 = hashlib.sha1() 157 | old_content_b = to_bytes(old_content, errors='surrogate_or_strict') 158 | sha1.update(old_content_b) 159 | checksum_old = sha1.digest() 160 | 161 | sha1 = hashlib.sha1() 162 | new_content_b = to_bytes(contents, errors='surrogate_or_strict') 163 | sha1.update(new_content_b) 164 | checksum_new = sha1.digest() 165 | if checksum_old == checksum_new: 166 | return (False) 167 | 168 | try: 169 | with open(dest, 'w') as f: 170 | f.write(contents) 171 | except IOError as ioexc: 172 | raise IOError(ioexc) 173 | 174 | return (True) 175 | 176 | def _parse_acl_with_textfsm(self, parser_file, output): 177 | import textfsm 178 | tmp = open(parser_file) 179 | re_table = textfsm.TextFSM(tmp) 180 | results = re_table.ParseText(output) 181 | fsm_results = [] 182 | for item in results: 183 | facts = {} 184 | facts.update(dict(zip(re_table.header, item))) 185 | fsm_results.append(facts) 186 | 187 | pd = [] 188 | parsed_acl = [] 189 | # Convert dictionary of terms into flows dictionary 190 | for term in fsm_results: 191 | pd_it = {} 192 | original_terms = {} 193 | for k, v in term.items(): 194 | if k == 'LINE_NUM' and v == '': 195 | # Empty line with just name 196 | continue 197 | elif k == 'LINE_NUM' and v != '': 198 | pd_it["service_line_index"] = v 199 | original_terms["service_line_index"] = v 200 | if k == 'PROTOCOL' and v != '': 201 | pd_it["proto"] = v 202 | original_terms['proto'] = v 203 | if k == 'ACTION' and v != '': 204 | pd_it["action"] = v 205 | original_terms['action'] = v 206 | if k == 'SRC_NETWORK' and v != '': 207 | if 'SRC_WILDCARD' in term: 208 | src_mask = term['SRC_WILDCARD'] 209 | src_invert_mask = sum([bin(255 - int(x)).count("1") for x in 210 | src_mask.split(".")]) 211 | else: 212 | src_invert_mask = '32' 213 | cidr = "%s/%s" % (v, src_invert_mask) 214 | src_ip = netaddr.IPNetwork(cidr) 215 | size_subnet = src_ip.size 216 | host_index = int(size_subnet / 2) 217 | pd_it['src'] = str(src_ip[host_index]) 218 | original_terms['src'] = src_ip 219 | if k == 'SRC_ANY' and v != '': 220 | pd_it['src'] = "any" 221 | original_terms['src'] = netaddr.IPNetwork('0.0.0.0/0') 222 | if k == 'SRC_HOST' and v != '': 223 | pd_it['src'] = v 224 | original_terms['src'] = v 225 | if k == 'SRC_PORT' and v != '': 226 | if not v[0].isdigit(): 227 | v = str(socket.getservbyname(v)) 228 | pd_it['src_port'] = v 229 | original_terms['src_port'] = v 230 | if k == 'DST_NETWORK' and v != '': 231 | if 'DST_WILDCARD' in term: 232 | dst_mask = term['DST_WILDCARD'] 233 | dst_invert_mask = sum([bin(255 - int(x)).count("1") for x in 234 | dst_mask.split(".")]) 235 | else: 236 | dst_invert_mask = '32' 237 | d_cidr = "%s/%s" % (v, dst_invert_mask) 238 | dst_ip = netaddr.IPNetwork(d_cidr) 239 | d_size_subnet = dst_ip.size 240 | d_host_index = int(d_size_subnet / 2) 241 | pd_it['dst'] = str(dst_ip[d_host_index]) 242 | original_terms['dst'] = dst_ip 243 | if k == 'DST_ANY' and v != '': 244 | pd_it['dst'] = "any" 245 | original_terms['dst'] = netaddr.IPNetwork('0.0.0.0/0') 246 | if k == 'DST_HOST' and v != '': 247 | pd_it['dst'] = v 248 | original_terms['dst'] = v 249 | if k == 'DST_PORT' and v != '': 250 | if not v[0].isdigit(): 251 | v = str(socket.getservbyname(v)) 252 | pd_it['dst_port'] = v 253 | original_terms['dst_port'] = v 254 | 255 | if pd_it: 256 | pd.append(pd_it) 257 | if original_terms: 258 | parsed_acl.append(original_terms) 259 | 260 | # Store parsed acl on this object for later processing 261 | self._parsed_acl = parsed_acl 262 | return json.dumps(pd, indent=4) 263 | -------------------------------------------------------------------------------- /bindep.txt: -------------------------------------------------------------------------------- 1 | # This is a cross-platform list tracking distribution packages needed by tests; 2 | # see http://docs.openstack.org/infra/bindep/ for additional information. 3 | 4 | gcc-c++ [test platform:rpm] 5 | python3-devel [test !platform:centos-7 platform:rpm] 6 | python3 [test !platform:centos-7 platform:rpm] 7 | python36 [test !platform:centos-7 !platform:fedora-28] 8 | -------------------------------------------------------------------------------- /defaults/cloud_vpn/providers/csr/initiator.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | 3 | cloud_vpn_initiator_user: ec2-user 4 | cloud_vpn_initiator_ansible_connection: network_cli 5 | cloud_vpn_initiator_outside_interface: GigabitEthernet1 6 | -------------------------------------------------------------------------------- /defaults/main.yml: -------------------------------------------------------------------------------- 1 | --- 2 | # defaults file for ansible-network.cisco_ios 3 | # 4 | ios_config_rollback_enabled: true 5 | ios_config_use_terminal: true 6 | ios_config_remove_temp_files: "{{ remove_temp_files | default(True) }}" 7 | ios_config_replace: "{{ config_manager_replace | default(False) }}" 8 | 9 | ios_config_source: 10 | running: show running-config 11 | startup: show startup-config 12 | 13 | ios_get_facts_command_map: "{{ role_path }}/vars/get_facts_command_map.yaml" 14 | ios_get_facts_subset: "{{ subset | default(['default']) }}" 15 | ios_dependent_role_check: true 16 | -------------------------------------------------------------------------------- /docs/cloud_vpn/configure_routing_initiator.md: -------------------------------------------------------------------------------- 1 | # Configure VPN routing as initiator 2 | The `cloud_vpn/configure_routing_initiator` function will configure the routing where 3 | a VPN as initiator has been configured previously on Cisco IOS devices. 4 | It is performed by calling the `cloud_vpn/configure_routing_initiator` task from the role. 5 | The task will process variables needed for routing configuration and apply it to the device. 6 | 7 | Below is an example to configure routing on a CSR device configured as initiator, 8 | where the responder is AWS VPN. 9 | 10 | ``` 11 | - hosts: cisco_ios 12 | 13 | tasks: 14 | - name: Configure initiator routing 15 | include_role: 16 | name: ansible-network.cisco_ios 17 | tasks_from: cloud_vpn/configure_routing_initiator 18 | vars: 19 | cloud_vpn_responder_provider: aws_vpn 20 | cloud_vpn_responder_cidr: 192.168.0.0/24 21 | ``` 22 | 23 | ## Notes 24 | None 25 | -------------------------------------------------------------------------------- /docs/cloud_vpn/configure_vpn_initiator.md: -------------------------------------------------------------------------------- 1 | # Configure VPN as initiator 2 | The `cloud_vpn/configure_vpn_initiator` function will configure IPSEC VPN as initiator 3 | on Cisco IOS devices. 4 | It is performed by calling the `cloud_vpn/configure_vpn_initiator` task from the role. 5 | The task will process variables needed for VPN configuration and apply it to the device. 6 | 7 | Below is an example to configure an IPSEC VPN as initiator on CSR device, where 8 | the responder is AWS VPN: 9 | 10 | ``` 11 | - hosts: cisco_ios 12 | 13 | tasks: 14 | - name: Configure IPSEC VPN as initiator 15 | include_role: 16 | name: ansible-network.cisco_ios 17 | tasks_from: cloud_vpn/configure_vpn_initiator 18 | vars: 19 | cloud_vpn_name: myvpn 20 | cloud_vpn_psk: mypsksecret 21 | cloud_vpn_initiator_provider: csr 22 | cloud_vpn_initiator_outside_interface: GigabitEthernet1 23 | cloud_vpn_initiator_tunnel_ip: 169.254.56.25 24 | cloud_vpn_initiator_tunnel_failover_ip: 169.254.56.29 25 | cloud_vpn_responder_provider: aws_vpn 26 | cloud_vpn_responder_public_ip: 18.191.132.220 27 | cloud_vpn_responder_failover_ip: 18.191.132.221 28 | cloud_vpn_responder_tunnel_ip: 169.254.56.26 29 | cloud_vpn_responder_tunnel_failover_ip: 169.254.56.30 30 | ``` 31 | 32 | ## Notes 33 | None 34 | -------------------------------------------------------------------------------- /docs/config_manager/get.md: -------------------------------------------------------------------------------- 1 | # Get configuration from device 2 | The `config_manager/get` function will return the either the current active or current 3 | saved configuration from an Cisco IOS devices. This function is only 4 | supported over `network_cli` connections. 5 | 6 | The `config_manager/get` function will also parse the device active configuration into 7 | a set of host facts during its execution. All of the parsed facts are stored 8 | in the ``cisco_ios.config`` top level facts key. 9 | 10 | ## How to get the device configuration 11 | Retrieving the configuration from the device involves just calling the 12 | `config_manager/get` function from the role. By default, the `config_manager/get` role will 13 | return the device active (running) configuraiton. The text configuration will 14 | be returned as a fact for the host. The configuration text is stored in the 15 | `configuration` fact. 16 | 17 | Below is an example of calling the `config_manager/get` function from the playbook. 18 | 19 | ``` 20 | - hosts: cisco_ios 21 | 22 | roles: 23 | - name ansible-network.cisco_ios 24 | function: config_manager/get 25 | ``` 26 | 27 | The above playbook will return the current running config from each host listed 28 | in the `cisco_ios` group in inventory. 29 | 30 | ### Get the current startup config 31 | By default the `config_manager/get` function will return the device running 32 | configuration. If you want to retrieve the device startup configuration, set 33 | the value of `source` to `startup`. 34 | 35 | ``` 36 | - hosts: cisco_ios 37 | 38 | roles: 39 | - name ansible-network.cisco_ios 40 | function: config_manager/get 41 | source: startup 42 | ``` 43 | 44 | ### Implement using tasks 45 | The `config_manager/get` function can also be implemented in the `tasks` during the 46 | playbook run using either the `include_role` or `import_role` modules as shown 47 | below. 48 | 49 | ``` 50 | - hosts: cisco_ios 51 | 52 | tasks: 53 | - name: collect facts from cisco ios devices 54 | include_role: 55 | name: ansible-network.cisco_ios 56 | tasks_from: config_manager/get 57 | ``` 58 | 59 | ## How to add additional parsers 60 | 61 | The configuration facts are returned by this function are parsed using the 62 | parsers in the `parser_templates/config` folder. To add a new parser, simply 63 | create a PR and add the new parser to the folder. Once merged, the 64 | `config_manager/get` function will automatically use the new parser. 65 | 66 | ## Arguments 67 | 68 | ### source 69 | 70 | Defines the configuration source to return from the device. This argument 71 | accepts one of `running` or `startup`. When the value is set to `running` 72 | (default), the current active configuration is returned. When the value is set 73 | to `sartup`, the device saved configuration is returned. 74 | 75 | The default value is `running` 76 | 77 | ## Notes 78 | None 79 | -------------------------------------------------------------------------------- /docs/config_manager/load.md: -------------------------------------------------------------------------------- 1 | # Load configuration onto device 2 | The `config_manager/load` function will take a Cisco IOS configuration file and load it 3 | onto the device. This function supports either merging the configuration with 4 | the current active configuration or replacing the current active configuration 5 | with the provided configuration file. 6 | 7 | The `config_manager/load` function will return the full configuration diff in the 8 | `ios_diff` fact. 9 | 10 | NOTE: When performing a configuration replace function be sure to specify the 11 | entire configuration to be loaded otherwise you could end up not being able to 12 | reconnect to your IOS device after the configuration has been loaded. 13 | 14 | ## How to load and merge a configuration 15 | Loading and merging a configuration file is the default operation for the 16 | `config_manager/load` function. It will take the contents of a Cisco IOS configuration 17 | file and merge it with the current device active configurations. 18 | 19 | Below is an example of calling the `config_manager/load` function from the playbook. 20 | 21 | ``` 22 | - hosts: cisco_ios 23 | 24 | roles: 25 | - name ansible_network.cisco_ios 26 | function: config_manager/load 27 | config_manager_text: "{{ lookup('file', 'ios.cfg') }}" 28 | ``` 29 | 30 | The above playbook will load the specified configuration file onto each device 31 | in the `cisco_ios` host group. 32 | 33 | ## How to replace the current active configuration 34 | The `config_manager/load` function also supports replacing the current active 35 | configuration with the configuration file located on the Ansible controller. 36 | In order to replace the device's active configuration, set the value of the 37 | `config_manager_replace` setting to `True`. 38 | 39 | ``` 40 | - hosts: cisco_ios 41 | 42 | roles: 43 | - name ansible_network.cisco_ios 44 | function: config_manager/load 45 | config_manager_text: "{{ lookup('file', 'ios.cfg') }}" 46 | config_manager_replace: true 47 | ``` 48 | 49 | 50 | ## Arguments 51 | 52 | ### config_manager_text 53 | 54 | This value accepts the text form of the configuration to be loaded on to the remote device. 55 | The configuration file should be the native set of commands used to configure the remote device. 56 | 57 | The default value is `null` 58 | 59 | ### config_manager_replace 60 | 61 | Specifies whether or not the source configuration should replace the current 62 | active configuration on the target IOS device. When this value is set to 63 | False, the source configuration is merged with the active configuration. When 64 | this value is set to True, the source configuration will replace the current 65 | active configuration 66 | 67 | The default value is `False` 68 | 69 | ### ios_config_remove_temp_files 70 | 71 | Configures the function to remove or not remove the temp files created when 72 | preparing to load the configuration file. There are two locations for temp 73 | files, one on the Ansible controller and one on the device. This argument 74 | accepts a boolean value. 75 | 76 | The default value is `True` 77 | 78 | ### ios_config_rollback_enabled 79 | 80 | Configures whether or not automatic rollback is enabled during the execution of 81 | the function. When enabled, if an error is enountered, then the configuration 82 | is automatically returned to the original running-config. If disabled, then 83 | the rollback operation is not performed automatically. 84 | 85 | The default value is `True` 86 | 87 | -------------------------------------------------------------------------------- /docs/get_facts.md: -------------------------------------------------------------------------------- 1 | # Get facts from device 2 | 3 | The `get_facts` function can be used to collect facts from an Cisco IOS 4 | devices. This function is only supported over `network_cli` connection 5 | type and requires the `ansible_network_os` value set to `ios`. 6 | 7 | ## How to get facts from the device 8 | 9 | To collect facts from the device, simply include this function in the playbook 10 | using either the `roles` directive or the `tasks` directive. If no other 11 | options are provided, then all of the available facts will be collected for the 12 | device. 13 | 14 | Below is an example of how to use the `roles` directive to collect all facts 15 | from the IOS device. 16 | 17 | ``` 18 | - hosts: cisco_ios 19 | 20 | roles: 21 | - name ansible-network.cisco_ios 22 | function: get_facts 23 | ``` 24 | 25 | The above playbook will return the facts for the host under the `cisco_ios` 26 | top level key. 27 | 28 | ### Filter the subset of facts returned 29 | 30 | By default all available facts will be returned by the `get_facts` function. 31 | If you only want to return a subset of the facts, you can specify the `subset` 32 | variable as a list of keys to return. 33 | 34 | For instance, the below will return only `interfaces` and `system` facts. 35 | 36 | ``` 37 | - hosts: cisco_ios 38 | 39 | roles: 40 | - name ansible-network.cisco_ios 41 | function: get_facts 42 | subset: 43 | - system 44 | ``` 45 | 46 | ### Implement using tasks 47 | 48 | The `get_facts` function can also be implemented using the `tasks` directive 49 | instead of the `roles` directive. By using the `tasks` directive, you can 50 | control when the fact collection is run. 51 | 52 | Below is an example of how to use the `get_facts` function with `tasks`. 53 | 54 | ``` 55 | - hosts: cisco_ios 56 | 57 | tasks: 58 | - name: collect facts from cisco ios devices 59 | import_role: 60 | name: ansible-network.cisco_ios 61 | tasks_from: get_facts 62 | vars: 63 | subset: 64 | - system 65 | - interfaces 66 | ``` 67 | 68 | ## Adding new parsers 69 | 70 | Over time new parsers can be added (or updated) to the role to add additional 71 | or enhanced functionality. To add or update parsers perform the following 72 | steps: 73 | 74 | * Add (or update) command parser located ino `parse_templates/cli` 75 | 76 | * Update the `vars/get_facts_command_map.yaml` file to map the CLI command 77 | to the parser 78 | 79 | The `get_facts_command_map.yaml` file provides a mapping between CLI command 80 | and parser used to transform the output into Ansible facts. 81 | 82 | ### Understanding the mapping file 83 | 84 | The command map file provides the mapping between show command and parser file. 85 | The format of the file is a list of objects. Each object supports a set of 86 | keys that can be configured to provide granular control over how each command 87 | is implemented. 88 | 89 | Command map entries support the following keys: 90 | 91 | #### command 92 | 93 | The `command` key is required and specifies the actual CLI command to execute 94 | on the target device. The output from the command is then passed to the parser 95 | for further processing. 96 | 97 | #### parser 98 | 99 | The `parser` key provides the name of the parser used to accept the output from 100 | the command. The parser value shoule be the command parser filename either 101 | relative to `parser_templates/cli` or absolute path. This value is required. 102 | 103 | #### engine 104 | 105 | This key accepts one of two values, either `command_parser` or `textfsm_parser`. 106 | This value instructs the the parsing function as to which parsing engine to 107 | use to parse the output from the CLI command. 108 | 109 | This key is not required and, if not provided, the engine will assumed to be 110 | `command_parser` 111 | 112 | #### groups 113 | 114 | Commands can be contained in one (or more) groups to make it easy for playbook 115 | designers to filter specific facts to retreive from the network device. The 116 | `groups` key must be a list and contain the groups the this command should be 117 | associated with. 118 | 119 | #### pre_hook 120 | 121 | The `pre_hook` key provides the path to the set of tasks to include prior 122 | to running the command on the CLI. This is useful if there is a need to check 123 | if a command is available or supported on a particular version. 124 | 125 | #### post_hook 126 | 127 | The `post_hook` key provides the path to the set of tasks to include after the 128 | command has been run on the target device and its results have been parsed by 129 | the parser. 130 | 131 | ## Arguments 132 | 133 | ### ios_get_facts_subset 134 | 135 | Defines the subset of facts to collection when the `get_facts` function is 136 | called. This value must be a list value and contain only the sub keys for the 137 | facts you wish to return. 138 | 139 | The default value is `default` 140 | 141 | #### Aliases 142 | 143 | * subset 144 | 145 | #### Current supported values for subset are 146 | 147 | * default 148 | * all 149 | * interfaces 150 | * bgp 151 | * lldp 152 | 153 | ### ios_get_facts_command_map 154 | 155 | Defines the command / parser mapping file to use when the call to `get_facts` 156 | is made by the playbook. Normally this value does not need to be modified but 157 | can be used to pass a custom command map to the function. 158 | 159 | The default value is `vars/get_facts_command_map.yaml` 160 | 161 | 162 | ## Notes 163 | 164 | None 165 | 166 | 167 | -------------------------------------------------------------------------------- /filter_plugins/ios.py: -------------------------------------------------------------------------------- 1 | # 2 | # (c) 2018 Red Hat, Inc. 3 | # 4 | # Copyright (c) 2017 Ansible Project 5 | # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) 6 | # 7 | # Make coding more python3-ish 8 | from __future__ import (absolute_import, division, print_function) 9 | __metaclass__ = type 10 | 11 | import re 12 | 13 | 14 | INTERFACE_NAMES = { 15 | 'Gi': 'GigabitEthernet', 16 | } 17 | 18 | 19 | def expand_interface_name(name): 20 | match = re.match('([a-zA-Z]*)', name) 21 | if match and match.group(1) in INTERFACE_NAMES: 22 | matched = match.group(1) 23 | name = name.replace(matched, INTERFACE_NAMES[matched]) 24 | return name 25 | 26 | 27 | class FilterModule(object): 28 | """Filters for working with output from network devices""" 29 | 30 | filter_map = { 31 | 'expand_interface_name': expand_interface_name 32 | } 33 | 34 | def filters(self): 35 | return self.filter_map 36 | -------------------------------------------------------------------------------- /handlers/main.yml: -------------------------------------------------------------------------------- 1 | --- 2 | # handlers file for ansible-network.cisco_ios 3 | -------------------------------------------------------------------------------- /includes/args_adapter.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | # Playbook to ingest config manager args into ios provider specific args 3 | # 4 | 5 | - name: convert config_manager_text 6 | set_fact: 7 | ios_config_text: "{{ config_manager_text }}" 8 | when: config_manager_text is defined 9 | 10 | - name: convert config_manager_file 11 | set_fact: 12 | ios_config_file: "{{ config_manager_file }}" 13 | when: config_manager_file is defined 14 | -------------------------------------------------------------------------------- /includes/checkpoint/create.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | - name: validate ios_checkpoint_filename is defined 3 | fail: 4 | msg: "missing required var: ios_checkpoint_filename" 5 | when: ios_checkpoint_filename is undefined 6 | 7 | - name: get current files on disk 8 | cli: 9 | command: dir 10 | register: ios_dir_listing 11 | 12 | - name: remove old checkpoint file (if necessary) 13 | cli: 14 | command: "delete /force flash:/{{ ios_checkpoint_filename }}" 15 | when: ios_checkpoint_filename in ios_dir_listing.stdout 16 | 17 | # copy the current running-config to the local flash disk on the target device. 18 | # This will be used both for restoring the current config if a failure happens 19 | # as well as performing a configuration diff once the new config has been 20 | # loaded. 21 | - name: create a checkpoint of the current running-config 22 | ios_command: 23 | commands: 24 | - command: "copy running-config flash:{{ ios_checkpoint_filename }}" 25 | prompt: ["\\? "] 26 | answer: "{{ ios_checkpoint_filename }}" 27 | -------------------------------------------------------------------------------- /includes/checkpoint/remove.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | - name: validate ios_checkpoint_filename is defined 3 | fail: 4 | msg: "missing required var: ios_checkpoint_filename" 5 | when: ios_checkpoint_filename is undefined 6 | 7 | - name: get current files on disk 8 | cli: 9 | command: dir 10 | register: ios_dir_listing 11 | 12 | - name: remove checkpoint file from remote device 13 | cli: 14 | command: "delete /force flash:/{{ ios_checkpoint_filename }}" 15 | when: ios_checkpoint_filename in ios_dir_listing.stdout 16 | -------------------------------------------------------------------------------- /includes/checkpoint/restore.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | - name: validate ios_checkpoint_filename is defined 3 | fail: 4 | msg: "missing required var: ios_checkpoint_filename" 5 | when: ios_checkpoint_filename is undefined 6 | 7 | - name: get current files on disk 8 | cli: 9 | command: dir 10 | register: ios_dir_listing 11 | 12 | - name: verify checkpoint file exists 13 | fail: 14 | msg: "missing checkpoint file {{ ios_checkpoing_filename }}" 15 | when: ios_checkpoint_filename not in ios_dir_listing.stdout 16 | 17 | - name: checkpoint configuration restore pre hook 18 | include_tasks: "{{ ios_checkpoint_restore_pre_hook }}" 19 | when: ios_checkpoint_restore_pre_hook is defined 20 | 21 | - name: restore checkpoint configuration 22 | cli: 23 | command: "config replace flash:/{{ ios_checkpoint_filename }} force" 24 | register: ios_rollback_results 25 | 26 | - name: checkpoint configuration restore post hook 27 | include_tasks: "{{ ios_checkpoint_restore_post_hook }}" 28 | when: ios_checkpoint_restore_post_hook is defined 29 | 30 | - name: remove checkpoint file from remote device 31 | cli: 32 | command: "delete /force flash:/{{ ios_checkpoint_filename }}" 33 | -------------------------------------------------------------------------------- /includes/configure/merge.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | - name: validate ios_config_text is defined 3 | fail: 4 | msg: "missing required arg: ios_config_text" 5 | when: ios_config_text is undefined 6 | 7 | - name: set the ios_config_temp_file name 8 | set_fact: 9 | ios_config_temp_file: "tmp_ansible" 10 | 11 | - name: create temp working dir 12 | tempfile: 13 | state: directory 14 | register: ios_config_temp_dir 15 | 16 | - name: write the config text to disk 17 | copy: 18 | content: "{{ ios_config_text }}" 19 | dest: "{{ ios_config_temp_dir.path }}/{{ ios_config_temp_file }}" 20 | 21 | - name: get current list of files on remote device 22 | cli: 23 | command: dir 24 | register: ios_dir_listing 25 | 26 | - name: remove temporary files from target device 27 | cli: 28 | command: "delete /force flash:/{{ ios_config_temp_file }}" 29 | when: ios_config_temp_file in ios_dir_listing.stdout 30 | 31 | - name: enable the ios scp server 32 | cli: 33 | command: "{{ line }}" 34 | loop: 35 | - configure terminal 36 | - ip scp server enable 37 | - end 38 | loop_control: 39 | loop_var: line 40 | 41 | - name: copy configuration to device 42 | net_put: 43 | src: "{{ ios_config_temp_dir.path }}/{{ ios_config_temp_file }}" 44 | dest: "flash:/{{ ios_config_temp_file }}" 45 | changed_when: false 46 | 47 | - name: merge with current active configuration 48 | cli: 49 | command: "{{ line }}" 50 | loop: 51 | - "copy flash:/{{ ios_config_temp_file }} force" 52 | - "delete /force flash:/{{ ios_config_temp_file }}" 53 | loop_control: 54 | loop_var: line 55 | 56 | - name: remove local temp working dir 57 | file: 58 | path: "{{ ios_config_temp_dir.path }}" 59 | state: absent 60 | -------------------------------------------------------------------------------- /includes/configure/replace.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | - name: validate ios_config_text is defined 3 | fail: 4 | msg: "missing required arg: ios_config_text" 5 | when: ios_config_text is undefined 6 | 7 | - name: set the ios_config_temp_file name 8 | set_fact: 9 | ios_config_temp_file: "tmp_ansible" 10 | 11 | - name: create temp working dir 12 | tempfile: 13 | state: directory 14 | register: ios_config_temp_dir 15 | 16 | - name: write the config text to disk 17 | copy: 18 | content: "{{ ios_config_text }}" 19 | dest: "{{ ios_config_temp_dir.path }}/{{ ios_config_temp_file }}" 20 | 21 | - name: get current list of files on remote device 22 | cli: 23 | command: dir 24 | register: ios_dir_listing 25 | 26 | - name: remove temporary files from target device 27 | cli: 28 | command: "delete /force flash:/{{ ios_config_temp_file }}" 29 | when: ios_config_temp_file in ios_dir_listing.stdout and ios_config_remove_temp_files 30 | 31 | - name: enable the ios scp server 32 | cli: 33 | command: "{{ line }}" 34 | loop: 35 | - configure terminal 36 | - ip scp server enable 37 | - end 38 | loop_control: 39 | loop_var: line 40 | 41 | - name: copy configuration to device 42 | net_put: 43 | src: "{{ ios_config_temp_dir.path }}/{{ ios_config_temp_file }}" 44 | dest: "flash:/{{ ios_config_temp_file }}" 45 | changed_when: false 46 | 47 | - name: replace current active configuration 48 | cli: 49 | command: "{{ line }}" 50 | loop: 51 | - "config replace flash:/{{ ios_config_temp_file }} force" 52 | - "delete /force flash:/{{ ios_config_temp_file }}" 53 | loop_control: 54 | loop_var: line 55 | 56 | - name: remove local temp working dir 57 | file: 58 | path: "{{ ios_config_temp_dir.path }}" 59 | state: absent 60 | -------------------------------------------------------------------------------- /includes/configure/terminal.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | # this block is responsible for loading the configuration on to the target 3 | # device line by line from config model. 4 | - name: load configuration onto target device 5 | block: 6 | - name: load configuration lines into target device 7 | block: 8 | - name: extract banners from configs if present 9 | extract_banners: 10 | config: "{{ ios_config_text }}" 11 | register: result 12 | 13 | - name: load configuration lines into target device except banner 14 | cli_config: 15 | config: "{{ result['config'] }}" 16 | register: ios_config_output 17 | 18 | - name: enter configuration mode 19 | cli: 20 | command: "configure terminal" 21 | 22 | - name: load banner lines into target device 23 | cli_command: 24 | command: "{{ item }}" 25 | sendonly: true 26 | with_items: "{{ result['banners'] }}" 27 | register: banner_config_output 28 | 29 | - name: exit configuration mode 30 | cli: 31 | command: end 32 | 33 | rescue: 34 | - name: exit configuration mode 35 | cli: 36 | command: end 37 | 38 | - name: set host failed 39 | fail: 40 | msg: "error loading configuration lines" 41 | when: not ansible_check_mode 42 | -------------------------------------------------------------------------------- /includes/init.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | - name: set role basic facts 3 | set_fact: 4 | ansible_network_ios_path: "{{ role_path }}" 5 | ansible_network_ios_version: "v2.7.0" 6 | 7 | - name: display the role version to stdout 8 | debug: 9 | msg: "ansible_network.cisco_ios version is {{ ansible_network_ios_version }}" 10 | 11 | - name: validate ansible_network_os == 'ios' 12 | fail: 13 | msg: "expected ansible_network_os to be `ios`, got `{{ ansible_network_os }}`" 14 | when: ansible_network_os != 'ios' 15 | 16 | - name: validate ansible_connection == 'network_cli' 17 | fail: 18 | msg: "expected ansible_network to be `network_cli`, got `{{ ansible_connection }}`" 19 | when: ansible_connection != 'network_cli' 20 | 21 | - name: Validate we have required installed version of dependent roles 22 | verify_dependent_role_version: 23 | role_path: "{{ role_path }}" 24 | depends_map: 25 | - name: 'ansible-network.network-engine' 26 | version: "{{ ios_network_engine_req_ver_override }}" 27 | when: ios_dependent_role_check is defined and ios_dependent_role_check 28 | and ios_network_engine_req_ver_override is defined 29 | 30 | - name: Validate we have required installed version of dependent roles from meta 31 | verify_dependent_role_version: 32 | role_path: "{{ role_path }}" 33 | when: ios_dependent_role_check is defined and ios_dependent_role_check 34 | and ios_network_engine_req_ver_override is not defined 35 | -------------------------------------------------------------------------------- /includes/run_cli.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | - name: run cli command pre hook 3 | include_tasks: "{{ ios_run_cli_command_pre_hook }}" 4 | when: ios_run_cli_command_pre_hook is defined and ios_run_cli_command_pre_hook 5 | 6 | - name: run command and parse output 7 | cli: 8 | command: "{{ ios_command }}" 9 | parser: "{{ parser }}" 10 | engine: "{{ ios_parser_engine | default(None) }}" 11 | name: "{{ ios_name | default(None) }} " 12 | with_first_found: 13 | - files: 14 | - "{{ ios_parser }}" 15 | paths: 16 | - "{{ playbook_dir }}/parser_templates/ios" 17 | - "~/.ansible/ansible_network/parser_templates/ios" 18 | - "/etc/ansible/ansible_network/parser_templates/ios" 19 | - "{{ role_path }}/parser_templates" 20 | loop_control: 21 | loop_var: parser 22 | 23 | - name: run cli command post hook 24 | include_tasks: "{{ ios_run_cli_command_post_hook }}" 25 | when: ios_run_cli_command_post_hook is defined and ios_run_cli_command_post_hook 26 | -------------------------------------------------------------------------------- /includes/wrapper.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | - name: initialize function 3 | include_tasks: includes/init.yaml 4 | 5 | - name: validate ios_config_includes is defined 6 | fail: 7 | msg: "missing required arg: ios_config_includes" 8 | when: ios_config_includes is undefined 9 | 10 | - name: set ios checkpoint filename 11 | set_fact: 12 | ios_checkpoint_filename: "chk_ansible" 13 | 14 | # initiate creating a checkpoint of the existing running-config 15 | - name: create checkpoint of current configuration 16 | include_tasks: "{{ role_path }}/includes/checkpoint/create.yaml" 17 | 18 | - name: configure the target device 19 | block: 20 | # iterate over the set of includes to configure the device 21 | - name: iterate over configuration tasks 22 | include_tasks: "{{ task }}" 23 | loop: "{{ ios_config_includes }}" 24 | loop_control: 25 | loop_var: task 26 | 27 | rescue: 28 | # since the host has failed during the configuration load, the role by 29 | # default will initiate a restore sequence. the restore sequence will 30 | # load the previous running-config with the replace option enabled. 31 | - name: display message 32 | debug: 33 | msg: "error configuring device, starting rollback" 34 | when: ios_config_rollback_enabled 35 | 36 | - name: initiate configuration rollback 37 | include_tasks: "{{ role_path }}/includes/checkpoint/restore.yaml" 38 | 39 | - name: display message 40 | debug: 41 | msg: "successfully completed configuration rollback" 42 | when: ios_config_rollback_enabled 43 | 44 | - name: fail host due to config load error 45 | fail: 46 | msg: "error loading configuration onto target device" 47 | 48 | - name: set the ios_active_config fact 49 | set_fact: 50 | ios_active_config: "cfg_ansible" 51 | 52 | # check if any reminents are left over from a previous run and remove them 53 | # prior to starting the configuration tasks. 54 | - name: check if stale temporarary files exist on target device 55 | cli: 56 | command: dir 57 | register: ios_dir_listing 58 | 59 | - name: remove temporary files from target device 60 | cli: 61 | command: "delete /force flash:/{{ ios_active_config }}" 62 | when: ios_active_config in ios_dir_listing.stdout 63 | 64 | # copy the updated running-config to the local flash device to be used to 65 | # generate a configuration diff between the before and after 66 | # running-configurations. 67 | - name: copy running-config to active config 68 | ios_command: 69 | commands: 70 | - command: "copy running-config flash:{{ ios_active_config }}" 71 | prompt: ["\\? "] 72 | answer: "{{ ios_active_config }}" 73 | 74 | # generate the configuration diff and display the diff to stdout. only set 75 | # changed if there are lines in the diff that have changed 76 | - name: generate ios diff 77 | cli: 78 | command: "show archive config differences flash:{{ ios_checkpoint_filename }} flash:{{ ios_active_config }}" 79 | register: ios_config_diff 80 | changed_when: "'No changes were found' not in ios_config_diff.stdout" 81 | 82 | - name: display config diff 83 | debug: 84 | msg: "{{ ios_config_diff.stdout.splitlines() }}" 85 | when: not ansible_check_mode 86 | 87 | # refresh the list of files currently on the target network device flash 88 | # drive and remote all temp files 89 | - name: update local directory listing 90 | cli: 91 | command: dir 92 | register: ios_dir_listing 93 | 94 | - name: remove remote temp files from flash 95 | cli: 96 | command: "delete /force flash:/{{ filename }}" 97 | loop: 98 | - "{{ ios_active_config }}" 99 | - "{{ ios_checkpoint_filename }}" 100 | loop_control: 101 | loop_var: filename 102 | when: filename in ios_dir_listing.stdout 103 | -------------------------------------------------------------------------------- /library/ios_capabilities.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # 3 | # This file is part of Ansible 4 | # 5 | # Ansible is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # Ansible is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with Ansible. If not, see . 17 | # 18 | 19 | ANSIBLE_METADATA = {'metadata_version': '1.1', 20 | 'status': ['preview'], 21 | 'supported_by': 'network'} 22 | 23 | 24 | DOCUMENTATION = """ 25 | --- 26 | module: ios_capabilities 27 | version_added: "2.7" 28 | short_description: Collect device capabilities from Cisco IOS 29 | description: 30 | - Collect basic fact capabilities from Cisco NX-OS devices and return 31 | the capabilities as Ansible facts. 32 | author: 33 | - Ansible Netowrk Community (ansible-network) 34 | options: {} 35 | """ 36 | 37 | EXAMPLES = """ 38 | - facts: 39 | """ 40 | 41 | RETURN = """ 42 | """ 43 | from ansible.module_utils.basic import AnsibleModule 44 | from ansible.module_utils.connection import Connection 45 | 46 | 47 | def main(): 48 | """ main entry point for Ansible module 49 | """ 50 | argument_spec = {} 51 | 52 | module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) 53 | 54 | connection = Connection(module._socket_path) 55 | facts = connection.get_capabilities() 56 | facts = module.from_json(facts) 57 | result = { 58 | 'changed': False, 59 | 'ansible_facts': {'cisco_ios': {'capabilities': facts['device_info']}} 60 | } 61 | module.exit_json(**result) 62 | 63 | 64 | if __name__ == '__main__': 65 | main() 66 | -------------------------------------------------------------------------------- /library/ios_command.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # 3 | # This file is part of Ansible 4 | # 5 | # Ansible is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # Ansible is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with Ansible. If not, see . 17 | # 18 | 19 | ANSIBLE_METADATA = {'metadata_version': '1.1', 20 | 'status': ['preview'], 21 | 'supported_by': 'network'} 22 | 23 | 24 | DOCUMENTATION = """ 25 | --- 26 | module: ios_command 27 | version_added: "2.1" 28 | author: "Peter Sprygada (@privateip)" 29 | short_description: Run commands on remote devices running Cisco IOS 30 | description: 31 | - Sends arbitrary commands to an ios node and returns the results 32 | read from the device. This module includes an 33 | argument that will cause the module to wait for a specific condition 34 | before returning or timing out if the condition is not met. 35 | - This module does not support running commands in configuration mode. 36 | Please use M(ios_config) to configure IOS devices. 37 | extends_documentation_fragment: ios 38 | notes: 39 | - Tested against IOS 15.6 40 | options: 41 | commands: 42 | description: 43 | - List of commands to send to the remote ios device over the 44 | configured provider. The resulting output from the command 45 | is returned. If the I(wait_for) argument is provided, the 46 | module is not returned until the condition is satisfied or 47 | the number of retries has expired. If a command sent to the 48 | device requires answering a prompt, it is possible to pass 49 | a dict containing I(command), I(answer) and I(prompt). 50 | Common answers are 'y' or "\\r" (carriage return, must be 51 | double quotes). See examples. 52 | required: true 53 | wait_for: 54 | description: 55 | - List of conditions to evaluate against the output of the 56 | command. The task will wait for each condition to be true 57 | before moving forward. If the conditional is not true 58 | within the configured number of retries, the task fails. 59 | See examples. 60 | aliases: ['waitfor'] 61 | version_added: "2.2" 62 | match: 63 | description: 64 | - The I(match) argument is used in conjunction with the 65 | I(wait_for) argument to specify the match policy. Valid 66 | values are C(all) or C(any). If the value is set to C(all) 67 | then all conditionals in the wait_for must be satisfied. If 68 | the value is set to C(any) then only one of the values must be 69 | satisfied. 70 | default: all 71 | choices: ['any', 'all'] 72 | version_added: "2.2" 73 | retries: 74 | description: 75 | - Specifies the number of retries a command should by tried 76 | before it is considered failed. The command is run on the 77 | target device every retry and evaluated against the 78 | I(wait_for) conditions. 79 | default: 10 80 | interval: 81 | description: 82 | - Configures the interval in seconds to wait between retries 83 | of the command. If the command does not pass the specified 84 | conditions, the interval indicates how long to wait before 85 | trying the command again. 86 | default: 1 87 | """ 88 | 89 | EXAMPLES = r""" 90 | tasks: 91 | - name: run show version on remote devices 92 | ios_command: 93 | commands: show version 94 | 95 | - name: run show version and check to see if output contains IOS 96 | ios_command: 97 | commands: show version 98 | wait_for: result[0] contains IOS 99 | 100 | - name: run multiple commands on remote nodes 101 | ios_command: 102 | commands: 103 | - show version 104 | - show interfaces 105 | 106 | - name: run multiple commands and evaluate the output 107 | ios_command: 108 | commands: 109 | - show version 110 | - show interfaces 111 | wait_for: 112 | - result[0] contains IOS 113 | - result[1] contains Loopback0 114 | - name: run commands that require answering a prompt 115 | ios_command: 116 | commands: 117 | - command: 'clear counters GigabitEthernet0/1' 118 | prompt: 'Clear "show interface" counters on this interface \[confirm\]' 119 | answer: 'y' 120 | - command: 'clear counters GigabitEthernet0/2' 121 | prompt: '[confirm]' 122 | answer: "\r" 123 | """ 124 | 125 | RETURN = """ 126 | stdout: 127 | description: The set of responses from the commands 128 | returned: always apart from low level errors (such as action plugin) 129 | type: list 130 | sample: ['...', '...'] 131 | stdout_lines: 132 | description: The value of stdout split into a list 133 | returned: always apart from low level errors (such as action plugin) 134 | type: list 135 | sample: [['...', '...'], ['...'], ['...']] 136 | failed_conditions: 137 | description: The list of conditionals that have failed 138 | returned: failed 139 | type: list 140 | sample: ['...', '...'] 141 | """ 142 | import re 143 | import time 144 | 145 | from ansible.module_utils.network.ios.ios import run_commands 146 | from ansible.module_utils.network.ios.ios import ios_argument_spec, check_args 147 | from ansible.module_utils.basic import AnsibleModule 148 | from ansible.module_utils.network.common.utils import ComplexList 149 | from ansible.module_utils.network.common.parsing import Conditional 150 | from ansible.module_utils.six import string_types 151 | 152 | 153 | def to_lines(stdout): 154 | for item in stdout: 155 | if isinstance(item, string_types): 156 | item = str(item).split('\n') 157 | yield item 158 | 159 | 160 | def parse_commands(module, warnings): 161 | command = ComplexList(dict( 162 | command=dict(key=True), 163 | prompt=dict(), 164 | answer=dict() 165 | ), module) 166 | commands = command(module.params['commands']) 167 | for item in list(commands): 168 | configure_type = re.match(r'conf(?:\w*)(?:\s+(\w+))?', item['command']) 169 | if module.check_mode: 170 | if configure_type and configure_type.group(1) not in ('confirm', 'replace', 'revert', 'network'): 171 | module.fail_json( 172 | msg='ios_command does not support running config mode ' 173 | 'commands. Please use ios_config instead' 174 | ) 175 | return commands 176 | 177 | 178 | def main(): 179 | """main entry point for module execution 180 | """ 181 | argument_spec = dict( 182 | commands=dict(type='list', required=True), 183 | 184 | wait_for=dict(type='list', aliases=['waitfor']), 185 | match=dict(default='all', choices=['all', 'any']), 186 | 187 | retries=dict(default=10, type='int'), 188 | interval=dict(default=1, type='int') 189 | ) 190 | 191 | argument_spec.update(ios_argument_spec) 192 | 193 | module = AnsibleModule(argument_spec=argument_spec, 194 | supports_check_mode=True) 195 | 196 | result = {'changed': False} 197 | 198 | warnings = list() 199 | check_args(module, warnings) 200 | commands = parse_commands(module, warnings) 201 | result['warnings'] = warnings 202 | 203 | wait_for = module.params['wait_for'] or list() 204 | conditionals = [Conditional(c) for c in wait_for] 205 | 206 | retries = module.params['retries'] 207 | interval = module.params['interval'] 208 | match = module.params['match'] 209 | 210 | while retries > 0: 211 | responses = run_commands(module, commands) 212 | 213 | for item in list(conditionals): 214 | if item(responses): 215 | if match == 'any': 216 | conditionals = list() 217 | break 218 | conditionals.remove(item) 219 | 220 | if not conditionals: 221 | break 222 | 223 | time.sleep(interval) 224 | retries -= 1 225 | 226 | if conditionals: 227 | failed_conditions = [item.raw for item in conditionals] 228 | msg = 'One or more conditional statements have not been satisfied' 229 | module.fail_json(msg=msg, failed_conditions=failed_conditions) 230 | 231 | result.update({ 232 | 'changed': False, 233 | 'stdout': responses, 234 | 'stdout_lines': list(to_lines(responses)) 235 | }) 236 | 237 | module.exit_json(**result) 238 | 239 | 240 | if __name__ == '__main__': 241 | main() 242 | -------------------------------------------------------------------------------- /library/ios_user_manager.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | 4 | # Copyright 2018 Red Hat 5 | # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) 6 | 7 | from __future__ import absolute_import, division, print_function 8 | __metaclass__ = type 9 | 10 | 11 | ANSIBLE_METADATA = {'metadata_version': '1.1', 12 | 'status': ['preview'], 13 | 'supported_by': 'network'} 14 | 15 | 16 | DOCUMENTATION = ''' 17 | --- 18 | module: ios_user_manager 19 | short_description: Manage an aggregate of users in IOS device(s) 20 | description: 21 | - Allows the `cisco_ios` provider role to manage aggregate of users 22 | by providing idempotency and other utility functions while running 23 | the `configure_user` task 24 | version_added: "2.7" 25 | options: 26 | new_users: 27 | description: 28 | - Aggregate of local users to be configured on IOS device(s) 29 | required: true 30 | user_config: 31 | description: 32 | - User config lines extracted from the devices' running-configuration 33 | required: true 34 | author: 35 | - Nilashish Chakraborty (@NilashishC) 36 | ''' 37 | RETURN = """ 38 | stdout: 39 | description: Filtered set of users that should be configured on the device 40 | returned: always apart from low-level errors (such as action plugin) 41 | type: list 42 | sample: [{"name": "ansible", "privilege": 15}, {"name": "test_user", "privilege": 15, "view": "sh_int"}] 43 | """ 44 | EXAMPLES = ''' 45 | - ios_user_manager: 46 | new_users: "{{ users }}" 47 | user_config: "{{ existing_user_config.stdout }}" 48 | ''' 49 | -------------------------------------------------------------------------------- /meta/main.yml: -------------------------------------------------------------------------------- 1 | --- 2 | galaxy_info: 3 | author: Ansible Network Community (ansible-network) 4 | description: | 5 | This role provides an implementation for automating the configuration of 6 | Cisco IOS/IOS-XE devices. It provides implementations of Ansible Network 7 | configuration abstractions. 8 | company: Ansible 9 | 10 | license: GPLv3 11 | 12 | min_ansible_version: 2.7 13 | 14 | # If this a Container Enabled role, provide the minimum Ansible Container version. 15 | # min_ansible_container_version: 16 | 17 | # Optionally specify the branch Galaxy will use when accessing the GitHub 18 | # repo for this role. During role install, if no tags are available, 19 | # Galaxy will use this branch. During import Galaxy will access files on 20 | # this branch. If Travis integration is configured, only notifications for this 21 | # branch will be accepted. Otherwise, in all cases, the repo's default branch 22 | # (usually master) will be used. 23 | # github_branch: 24 | 25 | # 26 | # platforms is a list of platforms, and each platform has a name and a list of versions. 27 | # 28 | platforms: 29 | - name: ios 30 | version: 31 | - any 32 | 33 | galaxy_tags: 34 | - network 35 | - cisco 36 | - ios 37 | - iosxe 38 | 39 | dependencies: 40 | - src: ansible-network.network-engine 41 | version: v2.7.3 42 | -------------------------------------------------------------------------------- /parser_templates/cli/show_cdp_neighbors_detail.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | - name: parser meta data 3 | parser_metadata: 4 | version: 1.0 5 | command: show cdp neighbors detail 6 | network_os: ios 7 | 8 | - name: match sections 9 | pattern_match: 10 | regex: "^-----.*" 11 | match_all: true 12 | match_greedy: true 13 | register: context 14 | 15 | - name: parse cdp neighbors 16 | pattern_group: 17 | - name: parse local port 18 | pattern_match: 19 | regex: '^Interface: ([^,]*)' 20 | content: "{{ item }}" 21 | register: local_port 22 | 23 | - name: parse remote prort 24 | pattern_match: 25 | regex: 'Port ID \(outgoing port\): (.*)$' 26 | content: "{{ item }}" 27 | register: remote_port 28 | 29 | - name: parse remote host 30 | pattern_match: 31 | regex: 'Device ID: (.*)$' 32 | content: "{{ item }}" 33 | register: remote_host 34 | 35 | loop: "{{ context }}" 36 | register: matches 37 | 38 | - name: build cdp neighbor facts 39 | loop: "{{ matches }}" 40 | register: cdp 41 | export: true 42 | export_as: dict 43 | extend: "{{ toplevel | default('cisco_ios') }}" 44 | json_template: 45 | template: 46 | - key: "{{ item.local_port.matches.0 | expand_interface_name }}" 47 | object: 48 | - key: neighbor 49 | value: "{{ item.remote_host.matches.0 }}" 50 | - key: neighbor_port 51 | value: "{{ item.remote_port.matches.0 }}" 52 | -------------------------------------------------------------------------------- /parser_templates/cli/show_interfaces.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | - name: parser meta data 3 | parser_metadata: 4 | version: 1.0 5 | command: show interfaces 6 | network_os: ios 7 | 8 | - name: match sections 9 | pattern_match: 10 | regex: "^\\S+ is (up|down|administratively down)," 11 | match_all: true 12 | match_greedy: true 13 | register: context 14 | 15 | - name: match interface values 16 | pattern_group: 17 | - name: match name 18 | pattern_match: 19 | regex: "^(\\S+)" 20 | content: "{{ item }}" 21 | register: name 22 | 23 | - name: match hardware 24 | pattern_match: 25 | regex: "Hardware is (.*(?=,)|.*)" 26 | content: "{{ item }}" 27 | register: type 28 | 29 | - name: match mtu 30 | pattern_match: 31 | regex: "MTU (\\d+)" 32 | content: "{{ item }}" 33 | register: mtu 34 | 35 | - name: match interface description 36 | pattern_match: 37 | regex: "Description: (.+)" 38 | content: "{{ item }}" 39 | register: description 40 | 41 | - name: match administrative state 42 | pattern_match: 43 | regex: "(administratively down)" 44 | content: "{{ item }}" 45 | register: enabled 46 | 47 | - name: match line protocol 48 | pattern_match: 49 | regex: "line protocol is (\\S+)" 50 | content: "{{ item }}" 51 | register: operstatus 52 | 53 | - name: match in packets 54 | pattern_match: 55 | regex: "(\\d+) packets input, (\\d+)" 56 | content: "{{ item }}" 57 | register: in_pkts_octets 58 | 59 | - name: match input broadcast 60 | pattern_match: 61 | regex: "Received (\\d+) broadcasts \\(\\d+" 62 | content: "{{ item }}" 63 | register: in_bcast_mcast 64 | 65 | - name: match out packets 66 | pattern_match: 67 | regex: "(\\d+) packets output, (\\d+) bytes" 68 | content: "{{ item }}" 69 | register: out_pkts_octets 70 | 71 | - name: match out errors 72 | pattern_match: 73 | regex: "(\\d+) output errors" 74 | content: "{{ item }}" 75 | register: out_errors 76 | 77 | loop: "{{ context }}" 78 | register: values 79 | 80 | - name: template interface values 81 | loop: "{{ values }}" 82 | register: interfaces 83 | export: true 84 | export_as: dict 85 | extend: cisco_ios 86 | json_template: 87 | template: 88 | - key: "{{ item.name.matches.0 }}" 89 | object: 90 | - key: name 91 | value: "{{ item.name.matches.0 }}" 92 | - key: type 93 | value: "{{ item.type.matches.0 }}" 94 | - key: mtu 95 | value: "{{ item.mtu.matches.0 }}" 96 | - key: description 97 | value: "{{ item.description.matches.0 }}" 98 | - key: enabled 99 | value: "{{ item.enabled.matches.0 is undefined }}" 100 | - key: admin-status 101 | value: "{{ item.enabled.matches.0 is undefined | ternary ('enabled', 'disabled') }}" 102 | - key: oper-status 103 | value: "{{ item.operstatus.matches.0 }}" 104 | - key: counters 105 | object: 106 | - key: in-octets 107 | value: "{{ item.in_pkts_octets.matches.0 }}" 108 | - key: in-unicast-pkts 109 | value: "{{ item.in_pkts_octets.matches.1 }}" 110 | - key: in-broadcast-pkts 111 | value: "{{ item.in_bcast_mcast.matches.0 }}" 112 | - key: in-multicast-pkts 113 | value: "{{ item.in_bcast_mcast.matches.1 }}" 114 | - key: out-octets 115 | value: "{{ item.out_pkts_octets.matches.0 }}" 116 | - key: out-unicast-pkts 117 | value: "{{ item.out_pkts_octets.matches.1 }}" 118 | - key: out-errors 119 | value: "{{ item.out_errors.matches.0 }}" 120 | -------------------------------------------------------------------------------- /parser_templates/cli/show_interfaces_transceiver.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | - name: parser meta data 3 | parser_metadata: 4 | version: 1.0 5 | command: show interfaces transceiver 6 | network_os: ios 7 | 8 | - name: match sections 9 | pattern_match: 10 | regex: '(^\S{2}\d+/\d/\d+).*' 11 | match_all: true 12 | match_greedy: true 13 | register: context 14 | 15 | - name: match interface transceiver 16 | pattern_group: 17 | - name: match transceiver 18 | pattern_match: 19 | regex: '(^\S{2}\d+/\d/\d+)' 20 | content: "{{ item }}" 21 | register: transceiver 22 | 23 | - name: match temperature 24 | pattern_match: 25 | regex: '(^\S{2}\d+/\d/\d+)\s*(\d+\.\d+)\s*(\d+\.\d+)\s*(\d+\.\d+)*\s*(-?\d+\.\d+)\s*(-?\d+\.\d+)*\s*([-\+]*)$' 26 | content: "{{ item }}" 27 | register: temperature 28 | 29 | - name: match voltage 30 | pattern_match: 31 | regex: '(^\S{2}\d+/\d/\d+)\s*(\d+\.\d+)\s*(\d+\.\d+)\s*(\d+\.\d+)*\s*(-?\d+\.\d+)\s*(-?\d+\.\d+)*\s*([-\+]*)$' 32 | content: "{{ item }}" 33 | register: voltage 34 | 35 | - name: match TxPower 36 | pattern_match: 37 | regex: '(^\S{2}\d+/\d/\d+)\s*(\d+\.\d+)\s*(\d+\.\d+)\s*(\d+\.\d+)*\s*(-?\d+\.\d+)\s*(-?\d+\.\d+)*\s*([-\+]*)$' 38 | content: "{{ item }}" 39 | register: txpower 40 | 41 | - name: match RxPower 42 | pattern_match: 43 | regex: '(^\S{2}\d+/\d/\d+)\s*(\d+\.\d+)\s*(\d+\.\d+)\s*(\d+\.\d+)*\s*(-?\d+\.\d+)\s*(-?\d+\.\d+)*\s*([-\+]*)$' 44 | content: "{{ item }}" 45 | register: rxpower 46 | 47 | - name: match Alarm 48 | pattern_match: 49 | regex: '(^\S{2}\d+/\d/\d+)\s*(\d+\.\d+)\s*(\d+\.\d+)\s*(\d+\.\d+)*\s*(-?\d+\.\d+)\s*(-?\d+\.\d+)*\s*([-\+]*)$' 50 | content: "{{ item }}" 51 | register: alarm 52 | 53 | loop: "{{ context }}" 54 | register: values 55 | 56 | - name: template interface values 57 | loop: "{{ values }}" 58 | register: transceiver 59 | export: true 60 | export_as: dict 61 | extend: cisco_ios 62 | json_template: 63 | template: 64 | - key: "{{ item.transceiver.matches.0 | expand_interface_name}}" 65 | object: 66 | - key: temperature 67 | value: "{{ item.temperature.matches.1 }}" 68 | - key: voltage 69 | value: "{{ item.voltage.matches.2 }}" 70 | - key: tx 71 | value: "{{ item.txpower.matches.4 }}" 72 | - key: rx 73 | value: "{{ item.rxpower.matches.5 }}" 74 | - key: alarm 75 | value: "{{ item.rxpower.matches.6 }}" 76 | -------------------------------------------------------------------------------- /parser_templates/cli/show_ip_bgp_summary.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | 3 | - name: show_ip_bgp_summary 4 | parser_metadata: 5 | version: 1.0 6 | command: show ip bgp summary 7 | network_os: ios 8 | 9 | - name: match not active 10 | register: not_active 11 | pattern_match: 12 | regex: "BGP not active" 13 | match_all: true 14 | 15 | - name: set_vars bgp state active 16 | set_vars: 17 | process_state: "active" 18 | 19 | - name: set_vars bgp state not active 20 | set_vars: 21 | process_state: "not active" 22 | when: "not_active.0.matches == 'BGP not active'" 23 | 24 | - name: match sections 25 | register: context 26 | pattern_match: 27 | regex: "Neighbor.+" 28 | match_all: true 29 | match_greedy: true 30 | when: process_state == 'active' 31 | 32 | - name: match lines 33 | register: lines 34 | pattern_match: 35 | regex: "^[0-9a-f.]+" 36 | content: "{{ context.0 }}" 37 | match_all: true 38 | match_greedy: true 39 | when: process_state == 'active' 40 | 41 | - name: match neighbors 42 | register: matched_neighbors 43 | loop: "{{ lines }}" 44 | pattern_match: 45 | regex: "(?P[0-9a-f.]+)\\s+(?P\\d+)\\s+(?P\\d+)\\s+(?P\\d+)\\s+(?P\\d+)\\s+(?P\\d+)\\s+(?P\\d+)\\s+(?P\\d+)\\s+(?P\\S+)\\s+(?P\\S+)" 46 | content: "{{ item }}" 47 | when: process_state == 'active' 48 | 49 | - name: template bgp values 50 | extend: cisco_ios.vrf.DEFAULT.protocols 51 | register: bgp 52 | export: true 53 | export_as: dict 54 | json_template: 55 | template: 56 | - key: "process_state" 57 | value: "{{ process_state }}" 58 | 59 | - name: template bgp neighbor entries 60 | extend: cisco_ios.vrf.DEFAULT.protocols.bgp 61 | register: neighbors 62 | export: true 63 | export_as: dict 64 | loop: "{{ matched_neighbors }}" 65 | when: process_state == 'active' 66 | json_template: 67 | template: 68 | - key: "{{ item.ip }}" 69 | object: 70 | - key: state_pfxrcd 71 | value: "{{ item.state }}" 72 | - key: asn 73 | value: "{{ item.asn }}" 74 | - key: timer 75 | value: "{{ item.timer }}" 76 | - key: ip_version 77 | value: "{{ item.version }}" 78 | -------------------------------------------------------------------------------- /parser_templates/cli/show_ip_vrf_detail.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | 3 | - name: show_ip_vrf_detail 4 | parser_metadata: 5 | version: 1.0 6 | command: show ip vrf detail 7 | network_os: ios 8 | 9 | - name: match vrf sections 10 | register: vrf_section 11 | pattern_match: 12 | regex: "^VRF \\S+(?: \\(VRF Id = \\d+\\)|); default RD" 13 | match_all: true 14 | match_greedy: true 15 | 16 | - name: match vrf section values 17 | loop: "{{ vrf_section }}" 18 | register: vrf_section_values 19 | pattern_group: 20 | 21 | - name: match name 22 | pattern_match: 23 | regex: "^VRF (\\S+)(?: \\(VRF Id = \\d+\\)|); default RD" 24 | content: "{{ item }}" 25 | register: name 26 | 27 | - name: match description 28 | pattern_match: 29 | regex: "^ Description: (.*)" 30 | content: "{{ item }}" 31 | register: description 32 | 33 | - name: match route distinguisher 34 | pattern_match: 35 | regex: ".*; default RD (\\d+:\\d+|)" 36 | content: "{{ item }}" 37 | register: rd 38 | 39 | - name: match interface section 40 | pattern_match: 41 | regex: "^ Interfaces:([\\s\\S]*)(?:Address family|VRF Table ID)" 42 | content: "{{ item }}" 43 | match_all: true 44 | match_greedy: false 45 | register: interface_section 46 | 47 | - name: match export route target section 48 | pattern_match: 49 | regex: "(?:No|)Export VPN route-target communities([\\s\\S]*) (?:No |)Import VPN" 50 | content: "{{ item }}" 51 | match_all: true 52 | match_greedy: false 53 | register: export_rt_section 54 | 55 | - name: match import route target section 56 | pattern_match: 57 | regex: "Import VPN route-target communities([\\s\\S]*) (?:No |)import" 58 | content: "{{ item }}" 59 | match_all: true 60 | match_greedy: false 61 | register: import_rt_section 62 | 63 | - name: match vrf nested section values 64 | loop: "{{ vrf_section_values }}" 65 | register: vrf_nested_section_values 66 | loop_control: 67 | loop_var: vrf_item 68 | pattern_group: 69 | 70 | - name: match vrf name 71 | pattern_match: 72 | regex: "(.*)" 73 | content: "{{ vrf_item.name.matches.0 }}" 74 | register: name 75 | 76 | - name: match description 77 | pattern_match: 78 | regex: "(.*)" 79 | content: "{{ vrf_item.description.matches.0 }}" 80 | register: description 81 | 82 | - name: match route distinguisher 83 | pattern_match: 84 | regex: "(.*)" 85 | content: "{{ vrf_item.rd.matches.0 }}" 86 | register: rd 87 | 88 | - name: match interfaces 89 | pattern_match: 90 | regex: "\\s+(\\S+)\\s" 91 | content: "{{ vrf_item.interface_section.0.matches }}" 92 | match_all: true 93 | register: interface 94 | 95 | - name: match export route targets 96 | pattern_match: 97 | regex: "\\s+RT:(\\d+:\\d+)" 98 | content: "{{ vrf_item.export_rt_section.0.matches }}" 99 | match_all: true 100 | register: export_rt 101 | 102 | - name: match import route targets 103 | pattern_match: 104 | regex: "\\s+RT:(\\d+:\\d+)" 105 | content: "{{ vrf_item.import_rt_section.0.matches }}" 106 | match_all: true 107 | register: import_rt 108 | 109 | - name: template export json object 110 | export: true 111 | loop: "{{ vrf_nested_section_values }}" 112 | loop_control: 113 | loop_var: vrf_nested_item 114 | register: vrf 115 | extend: cisco_ios 116 | export_as: dict 117 | json_template: 118 | template: 119 | - key: "{{ vrf_nested_item.name.matches.0 }}" 120 | object: 121 | - key: name 122 | value: "{{ vrf_nested_item.name.matches.0 }}" 123 | - key: description 124 | value: "{{ vrf_nested_item.description.matches.0 }}" 125 | - key: rd 126 | value: "{{ vrf_nested_item.rd.matches.0 }}" 127 | - key: export_rt 128 | elements: "{{ export_rt_item.matches }}" 129 | repeat_for: "{{ vrf_nested_item.export_rt }}" 130 | repeat_var: export_rt_item 131 | - key: import_rt 132 | elements: "{{ import_rt_item.matches }}" 133 | repeat_for: "{{ vrf_nested_item.import_rt }}" 134 | repeat_var: import_rt_item 135 | - key: interface 136 | elements: "{{ interface_item.matches }}" 137 | repeat_for: "{{ vrf_nested_item.interface }}" 138 | repeat_var: interface_item 139 | -------------------------------------------------------------------------------- /parser_templates/cli/show_lldp_neighbors_detail.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | - name: parser meta data 3 | parser_metadata: 4 | version: 1.0 5 | command: show lldp neighbors detail 6 | network_os: ios 7 | 8 | - name: match sections 9 | pattern_match: 10 | regex: "^-----.*" 11 | match_all: true 12 | match_greedy: true 13 | register: context 14 | 15 | - name: parse lldp neighbors 16 | pattern_group: 17 | - name: parse local port 18 | pattern_match: 19 | regex: "Local Intf: (.+)" 20 | content: "{{ item }}" 21 | register: local_port 22 | 23 | - name: parse remote prort 24 | pattern_match: 25 | regex: "Port id: (.+)" 26 | content: "{{ item }}" 27 | register: remote_port 28 | 29 | - name: parse remote host 30 | pattern_match: 31 | regex: "System Name: (.+)" 32 | content: "{{ item }}" 33 | register: remote_host 34 | 35 | loop: "{{ context }}" 36 | register: matches 37 | 38 | - name: build lldp neighbor facts 39 | register: lldp 40 | export: true 41 | extend: "{{ toplevel | default('cisco_ios') }}" 42 | json_template: 43 | template: 44 | - key: neighbors 45 | elements: 46 | - key: port 47 | value: "{{ item.local_port.matches.0 | expand_interface_name }}" 48 | - key: neighbor 49 | value: "{{ item.remote_host.matches.0 }}" 50 | - key: neighbor_port 51 | value: "{{ item.remote_port.matches.0 }}" 52 | repeat_for: "{{ matches }}" 53 | -------------------------------------------------------------------------------- /parser_templates/cli/show_version.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | - name: parser meta data 3 | parser_metadata: 4 | version: 1.0 5 | command: show version 6 | network_os: ios 7 | 8 | - name: match softare version 9 | pattern_match: 10 | regex: "Cisco IOS Software.*, Version (\\S+)," 11 | register: version 12 | 13 | - name: match model 14 | pattern_match: 15 | regex: "[Cc]isco (.+) \\(" 16 | register: model 17 | 18 | - name: match hostname 19 | pattern_match: 20 | regex: "^(\\S+) uptime is" 21 | register: hostname 22 | 23 | - name: match image 24 | pattern_match: 25 | regex: "^System image file is (\\S+)" 26 | register: image 27 | 28 | - name: match restart conditions 29 | pattern_match: 30 | regex: "^System restarted at (?P