Автогенерация и заливка элементов конфигураций сетевых устройств с помощью Nornir

Автогенерация и заливка элементов конфигураций сетевых устройств с помощью Nornir

Hei Habr!

Ina tata nei ka puta mai tetahi tuhinga ki konei Mikrotik me Linux. Ko nga mahinga me te mahi aunoa i whakatauhia he rapanga rite ma te whakamahi i nga tikanga parapara. A ahakoa he tino angamaheni te mahi, kaore he mea e rite ana ki a Habré. Ka maia ahau ki te tuku i taku paihikara ki te hapori IT rongonui.

Ehara tenei i te paihikara tuatahi mo taua mahi. Ko te whiringa tuatahi i whakatinanahia i etahi tau ki muri kitea версии 1.x.х. Велосипед использовался редко и поэтому постоянно ржавел. В том смысле, что сама задача возникает не так часто как обновляются версии kitea. A, i nga wa katoa e hiahia ana koe ki te taraiwa, ka hinga te mekameka, ka hinga ranei te wira. Heoi, ko te wahanga tuatahi, ko te whakaputa whirihora, he tino marama te mahi, he waimarie jinja2 Kua roa te miihini. Engari ko te waahanga tuarua - ko te huri i nga whirihora - he mea ohorere. A, i te mea me huri atu e au te whirihora ki te haurua rau taputapu, ko etahi kei te mano kiromita te tawhiti, he iti noa te hoha ki te whakamahi i tenei taputapu.

I konei me whakaae ahau ko taku kore tino mohio kei te kore ahau e mohio kitea, чем в его недостатках. И вот это, кстати, важный момент. kitea he tino motuhake, ko tana ake waahanga matauranga me tana ake DSL (Reo Motuhake Rohe), me mau tonu ki te taumata maia. Ana, i tera wa kitea Kei te tino tere te whanake, me te kore whakaaro motuhake mo te hototahi whakamuri, kaore e taapiri i te maia.

No reira, kare i roa i mua ka whakatinanahia te putanga tuarua o te paihikara. I tenei wa nānati, i runga ranei i te anga kua tuhia ki roto nānati a mo nānati i karangatia Nornir

Na - Nornir he microframework kua tuhia ki roto nānati a mo nānati me te hoahoa mo te aunoatanga. Ko te rite i roto i te take ki kitea, ki te whakaoti rapanga i konei, ka hiahiatia te whakarite raraunga mohio, i.e. rārangi o nga kaihautu me o ratou tawhā, engari karekau i tuhia nga tuhinga ki tetahi DSL motuhake, engari i roto i te ahua kaore i tino tawhito, engari he p[i|i]ton pai rawa atu.

Давайте рассмотрим что оно такое на следующем живом примере.

He whatunga manga taku me nga tari maha tatini puta noa i te motu. Kei ia tari he pouara WAN e whakamutua ana te maha o nga hongere korero mai i nga kaiwhakahaere rereke. Ko te kawa ararere he BGP. E rua nga momo pouara WAN: Cisco ISG, Juniper SRX ranei.

Inaianei ko te mahi: me whirihora e koe he kupengaroto i whakatapua mo te Tirohanga Ataata i runga i te tauranga motuhake i runga i nga pouara WAN katoa o te kupenga manga - panuitia tenei kupengaroto i BGP - whirihora i te rohe tere o te tauranga whakatapua.

Сначала нам необходимо подготовить пару шаблонов, на основе которых будут генерироваться конфигурации отдельно по Cisco и Juniper. А так же необходимо подготовить данные по каждой точке и параметры подключения т.е. собрать то самое inventory

Kua rite te tauira mo Cisco:

$ cat templates/ios/base.j2 
class-map match-all VIDEO_SURV
 match access-group 111

policy-map VIDEO_SURV
 class VIDEO_SURV
    police 1500000 conform-action transmit  exceed-action drop

interface {{ host.task_data.ifname }}
  description VIDEOSURV
  ip address 10.10.{{ host.task_data.ipsuffix }}.254 255.255.255.0
  service-policy input VIDEO_SURV

router bgp {{ host.task_data.asn }}
  network 10.40.{{ host.task_data.ipsuffix }}.0 mask 255.255.255.0

access-list 11 permit 10.10.{{ host.task_data.ipsuffix }}.0 0.0.0.255
access-list 111 permit ip 10.10.{{ host.task_data.ipsuffix }}.0 0.0.0.255 any

Шаблон для Juniper:

$ cat templates/junos/base.j2 
set interfaces {{ host.task_data.ifname }} unit 0 description "Video surveillance"
set interfaces {{ host.task_data.ifname }} unit 0 family inet filter input limit-in
set interfaces {{ host.task_data.ifname }} unit 0 family inet address 10.10.{{ host.task_data.ipsuffix }}.254/24
set policy-options policy-statement export2bgp term 1 from route-filter 10.10.{{ host.task_data.ipsuffix }}.0/24 exact
set security zones security-zone WAN interfaces {{ host.task_data.ifname }}
set firewall policer policer-1m if-exceeding bandwidth-limit 1m
set firewall policer policer-1m if-exceeding burst-size-limit 187k
set firewall policer policer-1m then discard
set firewall policer policer-1.5m if-exceeding bandwidth-limit 1500000
set firewall policer policer-1.5m if-exceeding burst-size-limit 280k
set firewall policer policer-1.5m then discard
set firewall filter limit-in term 1 then policer policer-1.5m
set firewall filter limit-in term 1 then count limiter

Ko nga tauira, ko te tikanga, kaore e puta mai i te hau kikokore. He tino rerekee enei i waenga i nga whirihoranga mahi i mua i muri i te whakaoti i te mahi i runga i nga pouara motuhake e rua o nga tauira rereke.

Из наших шабонов мы видим, что нам для решения задачи достаточно двух параметров для Juniper и 3 параметра для Cisco. вот они:

  • ifingoa
  • ipsuffix
  • asn

Теперь нам необходимо задать эти параметры для каждого устройства, т.е. сделать то самое rārangi.

Ki rārangi будем четко следовать документации Te timatanga o Nornir

ara, me hanga taua anga kōiwi ano:

.
├── config.yaml
├── inventory
│   ├── defaults.yaml
│   ├── groups.yaml
│   └── hosts.yaml

Ko te kōnae config.yaml te kōnae whirihoranga nornir paerewa

$ cat config.yaml 
---
core:
    num_workers: 10

inventory:
    plugin: nornir.plugins.inventory.simple.SimpleInventory
    options:
        host_file: "inventory/hosts.yaml"
        group_file: "inventory/groups.yaml"
        defaults_file: "inventory/defaults.yaml"

Ka tohuhia e matou nga tawhā matua i roto i te konae hosts.yaml, групповые (в моем случае это логины/пароли) в groups.yaml, a roto defaults.yaml Kaore matou e tohu i tetahi mea, engari me whakauru e koe nga waahanga e toru ki reira - e tohu ana ko tera yaml he kau te kōnae ahakoa.

Koinei te ahua o hosts.yaml:

---
srx-test:
    hostname: srx-test
    groups: 
        - juniper
    data:
        task_data:
            ifname: fe-0/0/2
            ipsuffix: 111

cisco-test:
    hostname: cisco-test
    groups: 
        - cisco
    data:
        task_data:
            ifname: GigabitEthernet0/1/1
            ipsuffix: 222
            asn: 65111

А вот так groups.yaml:

---
cisco:
    platform: ios
    username: admin1
    password: cisco1

juniper:
    platform: junos
    username: admin2
    password: juniper2

Koinei te mea i tupu rārangi для нашей задачи. При инициализации параметры из inventory-файлов мапятся на объектную модель InventoryElement.

Kei raro i te kaipahua he hoahoa o te tauira InventoryElement

print(json.dumps(InventoryElement.schema(), indent=4))
{
    "title": "InventoryElement",
    "type": "object",
    "properties": {
        "hostname": {
            "title": "Hostname",
            "type": "string"
        },
        "port": {
            "title": "Port",
            "type": "integer"
        },
        "username": {
            "title": "Username",
            "type": "string"
        },
        "password": {
            "title": "Password",
            "type": "string"
        },
        "platform": {
            "title": "Platform",
            "type": "string"
        },
        "groups": {
            "title": "Groups",
            "default": [],
            "type": "array",
            "items": {
                "type": "string"
            }
        },
        "data": {
            "title": "Data",
            "default": {},
            "type": "object"
        },
        "connection_options": {
            "title": "Connection_Options",
            "default": {},
            "type": "object",
            "additionalProperties": {
                "$ref": "#/definitions/ConnectionOptions"
            }
        }
    },
    "definitions": {
        "ConnectionOptions": {
            "title": "ConnectionOptions",
            "type": "object",
            "properties": {
                "hostname": {
                    "title": "Hostname",
                    "type": "string"
                },
                "port": {
                    "title": "Port",
                    "type": "integer"
                },
                "username": {
                    "title": "Username",
                    "type": "string"
                },
                "password": {
                    "title": "Password",
                    "type": "string"
                },
                "platform": {
                    "title": "Platform",
                    "type": "string"
                },
                "extras": {
                    "title": "Extras",
                    "type": "object"
                }
            }
        }
    }
}

He ahua rangirua te ahua o tenei tauira, ina koa i te tuatahi. Kia mohio ai, ka uru te aratau tauwhitiwhiti python.

 $ ipython3
Python 3.6.9 (default, Nov  7 2019, 10:44:02) 
Type 'copyright', 'credits' or 'license' for more information
IPython 7.1.1 -- An enhanced Interactive Python. Type '?' for help.

In [1]: from nornir import InitNornir                                                                           

In [2]: nr = InitNornir(config_file="config.yaml", dry_run=True)                                                

In [3]: nr.inventory.hosts                                                                                      
Out[3]: 
{'srx-test': Host: srx-test, 'cisco-test': Host: cisco-test}

In [4]: nr.inventory.hosts['srx-test'].data                                                                                    
Out[4]: {'task_data': {'ifname': 'fe-0/0/2', 'ipsuffix': 111}}

In [5]: nr.inventory.hosts['srx-test']['task_data']                                                     
Out[5]: {'ifname': 'fe-0/0/2', 'ipsuffix': 111}

In [6]: nr.inventory.hosts['srx-test'].platform                                                                                
Out[6]: 'junos'

A, ka mutu, me neke atu ki te tuhinga ake. Karekau he mea hei tino whakahīhī māku i konei. I tango noa ahau i tetahi tauira kua rite mai i akoranga me te whakamahi tata tonu kaore i rereke. Koinei te ahua o te tuhinga mahi kua oti:

from nornir import InitNornir
from nornir.plugins.tasks import networking, text
from nornir.plugins.functions.text import print_title, print_result

def config_and_deploy(task):
    # Transform inventory data to configuration via a template file
    r = task.run(task=text.template_file,
                 name="Base Configuration",
                 template="base.j2",
                 path=f"templates/{task.host.platform}")

    # Save the compiled configuration into a host variable
    task.host["config"] = r.result

    # Save the compiled configuration into a file
    with open(f"configs/{task.host.hostname}", "w") as f:
        f.write(r.result)

    # Deploy that configuration to the device using NAPALM
    task.run(task=networking.napalm_configure,
             name="Loading Configuration on the device",
             replace=False,
             configuration=task.host["config"])

nr = InitNornir(config_file="config.yaml", dry_run=True) # set dry_run=False, cross your fingers and run again

# run tasks
result = nr.run(task=config_and_deploy)
print_result(result)

Kia tupato ki te tawhā dry_run=Tono i te arawhiti ahanoa raina nr.
I konei he rite ano ki roto kitea kua whakatinanahia he oma whakamatautau i honoa ai he hononga ki te pouara, kua whakaritea he whirihoranga whakarereke hou, katahi ka whakamanahia e te taputapu (engari kaore tenei i te tino mohio; ka whakawhirinaki ki te tautoko taputapu me te whakatinanatanga taraiwa i NAPALM) , engari ko te whirihoranga hou kaore i te tono tika. Mo te whakamahi whawhai, me tango e koe te tawhā rere_maroke huri ranei tona uara ki teka.

Ka mahia te tuhinga, ka whakaputa a Nornir i nga raarangi taipitopito ki te papatohu.

Kei raro i te kaipahua te putanga o te oma whawhai i runga i nga pouara whakamatautau e rua:

config_and_deploy***************************************************************
* cisco-test ** changed : True *******************************************
vvvv config_and_deploy ** changed : True vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv INFO
---- Base Configuration ** changed : True ------------------------------------- INFO
class-map match-all VIDEO_SURV
 match access-group 111

policy-map VIDEO_SURV
 class VIDEO_SURV
    police 1500000 conform-action transmit  exceed-action drop

interface GigabitEthernet0/1/1
  description VIDEOSURV
  ip address 10.10.222.254 255.255.255.0
  service-policy input VIDEO_SURV

router bgp 65001
  network 10.10.222.0 mask 255.255.255.0

access-list 11 permit 10.10.222.0 0.0.0.255
access-list 111 permit ip 10.10.222.0 0.0.0.255 any
---- Loading Configuration on the device ** changed : True --------------------- INFO
+class-map match-all VIDEO_SURV
+ match access-group 111
+policy-map VIDEO_SURV
+ class VIDEO_SURV
+interface GigabitEthernet0/1/1
+  description VIDEOSURV
+  ip address 10.10.222.254 255.255.255.0
+  service-policy input VIDEO_SURV
+router bgp 65001
+  network 10.10.222.0 mask 255.255.255.0
+access-list 11 permit 10.10.222.0 0.0.0.255
+access-list 111 permit ip 10.10.222.0 0.0.0.255 any
^^^^ END config_and_deploy ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
* srx-test ** changed : True *******************************************
vvvv config_and_deploy ** changed : True vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv INFO
---- Base Configuration ** changed : True ------------------------------------- INFO
set interfaces fe-0/0/2 unit 0 description "Video surveillance"
set interfaces fe-0/0/2 unit 0 family inet filter input limit-in
set interfaces fe-0/0/2 unit 0 family inet address 10.10.111.254/24
set policy-options policy-statement export2bgp term 1 from route-filter 10.10.111.0/24 exact
set security zones security-zone WAN interfaces fe-0/0/2
set firewall policer policer-1m if-exceeding bandwidth-limit 1m
set firewall policer policer-1m if-exceeding burst-size-limit 187k
set firewall policer policer-1m then discard
set firewall policer policer-1.5m if-exceeding bandwidth-limit 1500000
set firewall policer policer-1.5m if-exceeding burst-size-limit 280k
set firewall policer policer-1.5m then discard
set firewall filter limit-in term 1 then policer policer-1.5m
set firewall filter limit-in term 1 then count limiter
---- Loading Configuration on the device ** changed : True --------------------- INFO
[edit interfaces]
+   fe-0/0/2 {
+       unit 0 {
+           description "Video surveillance";
+           family inet {
+               filter {
+                   input limit-in;
+               }
+               address 10.10.111.254/24;
+           }
+       }
+   }
[edit]
+  policy-options {
+      policy-statement export2bgp {
+          term 1 {
+              from {
+                  route-filter 10.10.111.0/24 exact;
+              }
+          }
+      }
+  }
[edit security zones]
     security-zone test-vpn { ... }
+    security-zone WAN {
+        interfaces {
+            fe-0/0/2.0;
+        }
+    }
[edit]
+  firewall {
+      policer policer-1m {
+          if-exceeding {
+              bandwidth-limit 1m;
+              burst-size-limit 187k;
+          }
+          then discard;
+      }
+      policer policer-1.5m {
+          if-exceeding {
+              bandwidth-limit 1500000;
+              burst-size-limit 280k;
+          }
+          then discard;
+      }
+      filter limit-in {
+          term 1 {
+              then {
+                  policer policer-1.5m;
+                  count limiter;
+              }
+          }
+      }
+  }
^^^^ END config_and_deploy ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Huna kupuhipa i roto i te ansible_vault

I te timatanga o te tuhinga i haere ahau ki te moana kitea, engari ehara i te mea tino kino. He tino pai ki a au kikorangi penei, i hangaia hei huna i nga korero tairongo kei kitea. A he tokomaha pea kua kite kei a matou nga takiuru/kupuhipa katoa mo nga pouara whawhai katoa e whiti ana i roto i te puka tuwhera i roto i te konae. gorups.yaml. Некрасиво это конечно. Давайте защитим эти данные с помощью kikorangi.

Me whakawhiti nga tawhā mai i groups.yaml ki creds.yaml, ka whakamuna ki te AES256 me te kupuhipa 20-mati:

$ cd inventory
$ cat creds.yaml
---
cisco:
    username: admin1
    password: cisco1

juniper:
    username: admin2
    password: juniper2

$ pwgen 20 -N 1 > vault.passwd
ansible-vault encrypt creds.yaml --vault-password-file vault.passwd  
Encryption successful
$ cat creds.yaml 
$ANSIBLE_VAULT;1.1;AES256
39656463353437333337356361633737383464383231366233386636333965306662323534626131
3964396534396333363939373539393662623164373539620a346565373439646436356438653965
39643266333639356564663961303535353364383163633232366138643132313530346661316533
6236306435613132610a656163653065633866626639613537326233653765353661613337393839
62376662303061353963383330323164633162386336643832376263343634356230613562643533
30363436343465306638653932366166306562393061323636636163373164613630643965636361
34343936323066393763323633336366366566393236613737326530346234393735306261363239
35663430623934323632616161636330353134393435396632663530373932383532316161353963
31393434653165613432326636616636383665316465623036376631313162646435

He maamaa noa. Ka noho tonu ki te whakaako i a maatau Nornir-скрипт доставать и применять эти данные.
Ki te mahi i tenei, i roto i to maatau tuhinga i muri i te raina arawhiti nr = InitNornir(config_file=… tāpirihia te waehere e whai ake nei:

...
nr = InitNornir(config_file="config.yaml", dry_run=True) # set dry_run=False, cross your fingers and run again

# enrich Inventory with the encrypted vault data
from ansible_vault import Vault
vault_password_file="inventory/vault.passwd"
vault_file="inventory/creds.yaml"
with open(vault_password_file, "r") as fp:
    password = fp.readline().strip()   
    vault = Vault(password)
    vaultdata = vault.load(open(vault_file).read())

for a in nr.inventory.hosts.keys():
    item = nr.inventory.hosts[a]
    item.username = vaultdata[item.groups[0]]['username']
    item.password = vaultdata[item.groups[0]]['password']
    #print("hostname={}, username={}, password={}n".format(item.hostname, item.username, item.password))

# run tasks
...

Ae ra, kaua e noho te vault.passwd ki te taha o creds.yaml penei i taku tauira. Engari he pai mo te takaro.

Heoi ano mo naianei. He tokorua nga korero mo Cisco + Zabbix e haere mai ana, engari ehara tenei i te mea mo te automation. A i roto i nga wa e heke mai nei ka whakamahere ahau ki te tuhi mo RESTCONF i Cisco.

Source: will.com

Tāpiri i te kōrero