Cyber Deals - Get up to 65% off on CKA, CKAD, CKS, KCNA, KCSA exams and courses!

Ansible for Network Automation

Read: How Network Automation is Different

References

Privilege Escalation for Network Devices in Ansible

Sample environment variable

ansible_connection: network_cli
ansible_network_os: ios
ansible_become: yes
ansible_become_method: enable

Communication Protocols

ansible_connectionProtocolRequiresPersistent?
network_cliCLI over SSHnetwork_os settingyes
netconfXML over SSHnetwork_os settingyes
httpapiAPI over HTTP/HTTPSnetwork_os settingyes
localdepends on providerprovider settingno

Network Modules

  • Arista EOS = eos_*
  • Cisco IOS/IOS-XE = ios_*
  • Cisco NX-OS = nxos_*
  • Cisco IOS-XR = iosxr_*
  • F5 BIG-IP = bigip_*
  • F5 BIG-IQ = bigiq_*
  • Juniper Junos = junos_*
  • VyOS = vyos_*

And modules as:

  • *_facts
  • *_command
  • *_config

Ansible Network Playbooks

Sample playbook for ios

- name: configure cisco routers
  hosts: routers
  connection: network_cli
  gather_facts: no
  vars:
    dns: "8.8.8.8 8.8.4.4"

  tasks:
   - name: configure hostname
     ios_config:
       lines: hostname {{ inventory_hostname }}

   - name: configure DNS
     ios_config:
       lines: ip name-server {{dns}}

Another one for interface config Ansible Playbook

Ansible Network Roles

https://galaxy.ansible.com/ansible-network

network-engine This role provides the foundation for building network roles by providing modules and plugins that are common to all Ansible Network roles. Galaxy

config_manager This role is designed to provide a network platform agnostic approach to managing the active (running) configuration file on a remote device. This role requires one (or more) platform provider roles to execute properly. Galaxy

Install roles

ansible-galaxy install ansible-network.cisco_ios
ansible-galaxy install ansible-network.config_manager

Update existing role

ansible-galaxy install ansible-network.network_engine,v2.7.0 --force

GNS3 Lab Setup

  • Install GNS3 GUI
  • Install and setup GNS3 VM

First Lab to test GNS3 setup

  • Create a lab with 2 PC and 1 SW
  • Add IP address for PCs
PC1> ip 10.1.1.1 255.255.255.0
  • Test a ping from one PC to another
  • Remember to save device configuration

Importing image to GNS3

Go to Edit -> Preferences -> Dynamips -> ISO Routers

  • Click New -> Browse the image (bin)
  • Choose Yes when asked to decompress
  • Remember to refer to the Cisco/GNS3 site for minimum memory requirement

Importing appliance to GNS3

https://docs.gns3.com/1_3RdgLWgfk4ylRr99htYZrGMoFlJcmKAAaUAc8x9Ph8/index.html

  • Download appliance file from the website

Configure a router

sh ip int br                    # show ip interface details
conf t                          # configure terminal
copy running-config startup-config
                                 # save running configuration to startup

NetworkAutomation Component

  • Download the NetworkAutomation component appliance from the marketplace, a docker image with Ansible pre-installed.

Ansible Ad Hoc Commands

Ref:

root@NetworkAutomation-1:~# ansible S1 -m raw -a "show version" -u david -k

root@NetworkAutomation-1:~# ansible S1 -m raw -a "show run" -u david -k

root@NetworkAutomation-1:~# ansible gns3-core -i ./gns3hosts -m raw -a "show version" -u david -k

root@NetworkAutomation-1:~# ansible gns3-core -i ./gns3hosts -m raw -a "show version" -u david -k | grep flash0

root@NetworkAutomation-1:~# ansible gns3-core -i ./gns3hosts -m raw -a "show version" -u david -k | grep 'SUCCESS\|Software'

root@NetworkAutomation-1:~# ansible gns3-core -i ./gns3hosts -m raw -a "show version" -u david -k | grep 'SUCCESS\|Version'

root@NetworkAutomation-1:~# ansible gns3-core -i ./gns3hosts -m raw -a "show run" -u david -k | grep 'username'

root@NetworkAutomation-1:~# ansible gns3-core -i ./gns3hosts -m raw -a "show run" -u david -k | grep 'SUCCESS\|username'

root@NetworkAutomation-1:~# ansible gns3-core -i ./gns3hosts -m raw -a "show run" -u david -k | grep 'username' > usernames.txt

root@NetworkAutomation-1:~# cat usernames.txt

root@NetworkAutomation-1:~# ansible gns3-core -i ./gns3hosts -m raw -a "show run" -u david -k > shrun.txt

root@NetworkAutomation-1:~# cat shrun.txt

root@NetworkAutomation-1:~# more shrun.txt

root@NetworkAutomation-1:~# ansible gns3-core -i ./gns3hosts -m raw -a "show ver" -u david -k > shver.txt

root@NetworkAutomation-1:~# more shver.txt | grep Version

root@NetworkAutomation-1:~# more shver.txt | grep 'SUCCESS\|Version'

root@NetworkAutomation-1:~# ansible all -i gns3hosts -m raw -a "show arp" -u david -k

root@NetworkAutomation-1:~# ansible all -i gns3hosts -m raw -a "show arp" -u david -k | grep 71

root@NetworkAutomation-1:~# ansible all -i gns3hosts -m raw -a "show arp" -u david -k | grep 'SUCCESS\|71'

root@NetworkAutomation-1:~# ansible all -i gns3hosts -m raw -a "show arp" -u david -k | grep 'SUCCESS\|\.71'

root@NetworkAutomation-1:~# ansible all -i gns3hosts -m raw -a "show mac address-table" -u david -k

root@NetworkAutomation-1:~# ansible all -i gns3hosts -m raw -a "show mac address-table" -u david -k | grep 7a

root@NetworkAutomation-1:~# ansible all -i gns3hosts -m raw -a "show mac address-table" -u david -k | grep 'SUCCESS\|fe7a'

root@NetworkAutomation-1:~# cat gns3hosts

Task Reference

Using username and password for authentication

- name: User username
  vars:
    cli:
      username: user1
      password: password
      transport: cli
  tasks:
    - name: Test Login
      ios_config:
        provider: "{{ cli }}"

Reboot ios device

---
- name: reboot ios device
  cli_command:
    command: reload
    prompt:
      - Save?
      - confirm
    answer:
     - y
     - y

  # To make sure the current connection to the network device
  # is closed so that the socket can be reestablished to the network
  # device after the reboot takes place.
- name: reset the connection
  meta: reset_connection

- name: Wait for the network device to reload
  wait_for_connection:
    delay: 10

Backup eos

Backup configuration

---
- name: BACKUP NETWORK CONFIGURATIONS
  hosts: arista
  gather_facts: false

  tasks:

    - name: BACKUP CONFIG
      eos_config:
        backup: yes

Backup using cli_command - run arbitrary commands on network devices

---
- name: RUN COMMAND AND PRINT TO TERMINAL WINDOW
  hosts: arista
  gather_facts: false

  tasks:

    - name: RUN ARISTA COMMAND
      cli_command:
        command: show run
      register: backup

    - name: PRINT TO TERMINAL WINDOW
      copy:
        content: "{{backup.stdout}}"
        dest: "{{inventory_hostname}}.backup"

Change config

# vars
show_interfaces: "show ip interface brief"
backup: "show running-config"
save: "write memory"
ntp_commands: ntp server 192.168.1.1

---
- name: CHANGE CONFIGURATION
  hosts: routers
  gather_facts: false

  tasks:

    - name: LOAD NTP CONFIGURATION
      cli_config:
        config: "{{ntp_commands}}"
      notify:
        - SAVE CONFIGURATION

  handlers:

    - name: SAVE CONFIGURATION
      cli_command:
        command: "{{save}}"

# Show interface
    - name: RUN SHOW COMMAND
      cli_command:
        command: "{{show_interfaces}}"
      register: command_output

Add VLAN nxos

---
- name: deploy vlans
  hosts: cisco
  gather_facts: no

  tasks:
    - name: ensure vlans exist
      nxos_vlan:
        vlan_id: 100
        admin_state: up
        name: WEB

Add ACL (Access Control List)

https://dodgydudes.se/ansible-net104/

Add config iso_config

---
- name: snmp ro/rw string configuration
  hosts: cisco
  gather_facts: no
  tasks:
    - name: ensure snmp strings are present
      ios_config:
        lines:
          - snmp-server community ansible-public RO
          - snmp-server community ansible-private RW

VLAN & IP Configuration Reference

Add IP to VM

sudo ip addr add 192.168.1.14/24 dev eth0
sudo ip link set dev eth0 up
sudo ip route add default via 192.168.1.1

sudo vi /etc/network/interfaces

sudo /etc/init.d/networking restart

To configure a dynamic or static IP address

auto eth0
iface eth0 inet dhcp

## Or configure a static IP
auto eth0
iface eth0 inet static
  address 192.168.1.14
  gateway 192.168.1.1
  netmask 255.255.255.0
  network 192.168.1.0
  broadcast 192.168.1.255

Configure VLAN with IP

conf t
int vlan 100
ip address IP subnet

VLANs

show vlans

ac-02#vlan database
ac-02(vlan)#

ac-02(config)#int vlan 100
                            # create vlan interface
ac-02(config)#no interface vlan 100
                            # delete vlan interface

Assign to port

ac-02(config)#interface range fastEthernet 1/0 - 5
ac-02(config-if-range)#switchport mode access
ac-02(config-if-range)#switchport access vlan 100

Assign IP to VLAN

ac-02(config)#interface vlan 100
ac-02(config-if)#ip address 10.1.10.70 255.255.255.0

Ref: https://srijit.com/working-cisco-ios-gns3/

Configure HP Switch (5130)

Refs:

Ansible modules

Configuring password authentication for console login

<HPE> system-view
[HPE] line aux 0
[HPE-line-aux0] authentication-mode password

# Password is password
[HPE-line-aux0] set authentication password simple <PASSWORD>
[HPE-line-aux0] user-role network-admin

# save config
[HPE-line-aux0] save force

SSH on vty

[ds-01]line vty 0
[ds-01-line-vty0]authentication-mode scheme
[ds-01-line-vty0]set authentication password simple password
[ds-01-line-vty0]protocol inbound ssh
[ds-01-line-vty0]user-role network-admin

Configuring SSH login on the device

  1. Create a key
<ds-01>system-view
System View: return to User View with Ctrl+Z.
[ds-01]public-key local create rsa name ansiblekey
The range of public key modulus is (512 ~ 2048).
If the key modulus is greater than 512, it will take a few minutes.
Press CTRL+C to abort.
Input the modulus length [default = 1024]:
Generating Keys...
.
Create the key pair successfully.
  1. Enable SSH
[ds-01]ssh server enable
[ds-01]ssh user hp service-type all authentication-type password
[ds-01]netconf ssh server enable
[ds-01]sftp server enable
scp server enable

Enabling NETCONF over SSH

[ds-01]sftp server enable

Configuring the user lines for SSH login, and a client’s host public key

[ds-01]display public-key local rsa public

then find the key and copy for the next command

[ds-01]public-key peer ansible-nw
Enter public key view. Return to system view with "peer-public-key end" command.
[ds-01-pkey-public-key-ansible-nw] <enter key here>
[ds-01-pkey-public-key-ansible-nw]peer-public-key end
  1. Create an SSH user
#
local-user hp
 password simple hp123
 service-type ssh http https
 authorization-attribute user-role network-admin
#
line vty 0 15
 authentication-mode scheme
 user-role network-admin

And specify the authentication mode. By default, no SSH user is configured on the device.

[ds-01]ssh user ansible service-type stelnet authentication-type password
  1. Enter VTY line view or class view
[ds-01]line vty 0
[ds-01-line-vty0]authentication-mode scheme
[ds-01-line-vty0]protocol inbound ssh

Install HP Comware 7 Python Library

Latest from source:

$ git clone https://github.com/HPENetworking/pyhpecw7.git
$ cd pyhpecw7
$ sudo python setup.py install

Latest stable release via pip (not supported yet):

$ sudo pip install pyhpecw7

Install HP Ansible Modules

$ cd
$ git clone https://github.com/HPENetworking/ansible-hpe-cw7
$ cd hp-ansible

How to enable NETCONF on Comware 7

https://networkgeekstuff.com/networking/hp-networking-comware-netconf-interface-quick-tutorial-using-pythons-ncclient-and-pyhpecw7/

Configuration snapshot that enables NETCONF over SSH and creates a user “admin” with password “admin” to access it:

ssh server enable
netconf ssh server enable

local-user admin class manage
 password simple admin
 service-type telnet ssh terminal
 authorization-attribute user-role network-admin

line vty 0 15
 authentication-mode scheme
 user-role network-operator
 idle-timeout 15 0

Check Comware Ansible documentation

$ ansible-doc -M library/ comware_vlan

Assign port with VLAN

[ds-01]interface ge3/0
[ds-01-GigabitEthernet3/0]port link-mode bridge
[ds-01-GigabitEthernet3/0]port link-type access
[ds-01-GigabitEthernet3/0]port access vlan 100

Troubleshooting

Ref: https://docs.ansible.com/ansible/latest/network/user_guide/network_debug_troubleshooting.html

SSH Error

root@NW-Auto-100:~/ansible# ssh cisco@\10.1.10.51
ssh: error while loading shared libraries: libgssapi_krb5.so.2: cannot open shared object file: No such file or directory

Solution:

root@NW-Auto-100:~/ansible# /sbin/ldconfig -v

discovered_interpreter_python error

fatal: [ac-02]: FAILED! => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python"}, "changed": false, "msg": "[Errno -2] Name or service not known"}

Ref: https://www.toptechskills.com/ansible-tutorials-courses/how-to-fix-usr-bin-python-not-found-error-tutorial/

Ansible with netconf

Enable scp on IOS device

scp ~/Downloads/c2960x-universalk9-mz.152-2.E5.bin [email protected]:flash2:/
Password:
Administratively disabled.

To fix that, get into config mode and run:

ip scp server enable

Ref: https://www.ispcolohost.com/2016/08/16/scping-an-ios-image-to-a-cisco-2960xr-stack/

Sometimes this happens due to an encryption or integrity mismatch between the SCP server and ASA. Support all cipher methods with:

ssh cipher encryption all
ssh cipher integrity all

Backup Reference

To take a full backup:

terminal length 0
show run

Appendix

HP: https://docs.gns3.com/appliances/hp-vsr1001.html

Nested Virtualization - VirtualBox: https://www.virtualbox.org/manual/ch09.html#nested-virt

Driver is probably stuck stopping/starting

Steps:

  1. Navigate to C:\Program Files\Oracle\VirtualBox\drivers\vboxdrv
  2. Right click on VBoxDrv.inf and select Install
  3. Open the console as administrator and run the following command

vboxmanage cli

Ref: https://blog.scottlowe.org/2016/11/10/intro-to-vbox-cli/

vboxmanage startvm k8s
vboxmanage list runningvms

Ref: https://www.virtualbox.org/manual/ch08.html#vboxmanage-modifyvm

vboxmanage modifyvm Ubuntu --nested-hw-virt on

Install VMware Workstation on Ubuntu

https://phoenixnap.com/kb/install-vmware-workstation-ubuntu

Download IOS Images

Resources

DEVNET: developer.cisco.com -> https://developer.cisco.com/site/sandbox/ -> https://devnetsandbox.cisco.com/

Example - IOS XE on CSR Latest Code Always On: https://devnetsandbox.cisco.com/RM/Diagram/Index/38ded1f0-16ce-43f2-8df5-43a40ebf752e?diagramType=Topology

Add variables:

[routers:vars]
ansile_user=developer
ansible_password=password
ansible_connection=network_cli
ansible_network_os=iso
ansible_port=8181 #if diff port

Connect GNS3 to the Internet (local server): https://docs.gns3.com/1vFs-KENh2uUFfb47Q2oeSersmEK4WahzWX-HrMIMd00/index.html

Reference Repos