Gineadh agus lìonadh fèin-ghluasadach de eileamaidean rèiteachaidh inneal lìonra a ’cleachdadh Nornir

Gineadh agus lìonadh fèin-ghluasadach de eileamaidean rèiteachaidh inneal lìonra a ’cleachdadh Nornir

Hi Habr!

O chionn ghoirid nochd artaigil an seo Mikrotik agus Linux. Gnàth-shìde agus fèin-ghluasad far an deach duilgheadas coltach ris a rèiteachadh le bhith a’ cleachdadh dhòighean fosail. Agus ged a tha an obair gu tur àbhaisteach, chan eil dad coltach ris mu dheidhinn air Habré. Tha mi airson mo bhaidhsagal a thabhann don choimhearsnachd IT air a bheil meas.

Chan e seo a’ chiad bhaidhsagal airson a leithid de dh’ obair. Chaidh a’ chiad roghainn a chuir an gnìomh grunn bhliadhnaichean air ais cunntachail tionndadh 1.x.x. Is ann ainneamh a chaidh am baidhsagal a chleachdadh agus mar sin bha e an-còmhnaidh air a mheirgeadh. Anns an fhaireachdainn nach eil an obair fhèin ag èirigh cho tric 's a bhios dreachan air an ùrachadh cunntachail. Agus a h-uile uair a dh'fheumas tu dràibheadh, bidh an t-seine a 'tuiteam dheth no a' chuibhle a 'tuiteam dheth. Ach, tha a 'chiad phàirt, a' cruthachadh configs, an-còmhnaidh ag obair gu math soilleir, gu fortanach gìn 2 Tha an einnsean stèidhichte o chionn fhada. Ach mar as trice thug an dàrna pàirt - cuir a-steach configs - iongnadh. Agus leis gu feum mi an rèiteachadh a chuir a-mach air astar gu leth cheud inneal, cuid dhiubh suidhichte mìltean de chilemeatairean air falbh, bha cleachdadh an inneil seo beagan dòrainneach.

An seo feumaidh mi aideachadh gu bheil mo mhì-chinnt as coltaiche a’ laighe leis an dìth eòlas agam air cunntachailseach anns na h-easbhaidhean aige. Agus tha seo, leis an t-slighe, na phuing cudromach. cunntachail na raon eòlais gu tur air leth, leis an DSL aige fhèin (Cànan Sònraichte Domain), a dh’ fheumar a chumail aig ìre mhisneachail. Uill, an uair sin cunntachail Tha e a 'leasachadh gu math luath, agus gun aire shònraichte air co-fhreagarrachd air ais, chan eil e a' cur ri misneachd.

Mar sin, chan eil cho fada air ais chaidh an dàrna dreach den bhaidhsagal a chuir an gnìomh. An turas seo air adhart python, no an àite sin air frèam sgrìobhte ann python agus airson python fon ainm Nornir

Mar sin - Nornir 's e microframework a tha sgrìobhte ann python agus airson python agus air a dhealbhadh airson fèin-ghluasad. An aon rud sa chùis le cunntachail, gus fuasgladh fhaighinn air duilgheadasan an seo, tha feum air ullachadh dàta comasach, i.e. clàr de luchd-aoigheachd agus na crìochan aca, ach chan eil sgriobtaichean sgrìobhte ann an DSL air leth, ach san aon rud chan eil iad glè shean, ach fìor mhath p[i|i]ton.

Bheir sinn sùil air na tha e a’ cleachdadh an eisimpleir beò a leanas.

Tha lìonra meur agam le grunn dhusan oifis air feadh na dùthcha. Tha router WAN aig gach oifis a chuireas crìoch air grunn shianalan conaltraidh bho dhiofar ghnìomhaichean. Is e am protocol slighe BGP. Bidh routers WAN a ’tighinn ann an dà sheòrsa: Cisco ISG no Juniper SRX.

A-nis an obair: feumaidh tu subnet sònraichte a rèiteachadh airson Sgrùdadh Bhidio air port air leth air a h-uile router WAN den lìonra meòir - sanas an subnet seo ann am BGP - rèitich crìoch astair a’ phuirt shònraichte.

An toiseach, feumaidh sinn teamplaid no dhà ullachadh, air bunait dè na rèiteachaidhean a thèid a chruthachadh air leth airson Cisco agus Juniper. Tha e cuideachd riatanach dàta ullachadh airson gach puing agus crìochan ceangail, i.e. cruinnich an aon stoc

Teamplaid deiseil airson 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

Teamplaid airson 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

Chan eil teamplaidean, gu dearbh, a 'tighinn a-mach à èadhar tana. Tha iad sin gu ìre mhòr eadar-dhealaichte eadar na rèiteachaidhean obrach a bha agus a bha às deidh dhaibh an obair fhuasgladh air dà router sònraichte de dhiofar mhodalan.

Bho na teamplaidean againn chì sinn sin gus an duilgheadas fhuasgladh, chan fheum sinn ach dà pharamadair airson Juniper agus 3 paramadairean airson Cisco. seo iad:

  • mas ainm
  • iar-leasachan
  • asn

A-nis feumaidh sinn na crìochan sin a shuidheachadh airson gach inneal, i.e. dean an aon rud Clàr-seilbhe.

airson Clàr-seilbhe Leanaidh sinn gu teann ris na sgrìobhainnean Nornir a’ tòiseachadh

is e sin, cruthaichidh sinn an aon cnàimhneach faidhle:

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

Is e am faidhle config.yaml am faidhle rèiteachaidh àbhaisteach nornir

$ 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"

Seallaidh sinn na prìomh pharamadairean san fhaidhle luchd-aoigheachd.yaml, buidheann (anns a’ chùis agam is iad sin logins / faclan-faire) a-steach buidhnean.yaml, agus a-steach easbhuidh.yaml Cha bhith sinn a ’comharrachadh dad, ach feumaidh tu trì minuses a chuir a-steach an sin - a’ nochdadh gu bheil e iaml tha am faidhle falamh ge-tà.

Seo cò ris a tha hosts.yaml coltach:

---
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

Agus seo buidhnean.yaml:

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

juniper:
    platform: junos
    username: admin2
    password: juniper2

Seo mar a thachair Clàr-seilbhe airson ar n-obair. Aig àm tòiseachaidh, tha crìochan bho fhaidhlichean tasgaidh air am mapadh gu modail an nì Element Clàr-seilbhe.

Fon spoiler tha diagram den mhodail 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"
                }
            }
        }
    }
}

Faodaidh am modail seo coimhead beagan troimh-chèile, gu sònraichte an toiseach. Gus obrachadh a-mach, am modh eadar-ghnìomhach a-steach 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'

Agus mu dheireadh, gluaisidh sinn air adhart chun sgriobt fhèin. Chan eil dad agam airson a bhith moiteil às an seo. Cha do ghabh mi ach eisimpleir deiseil bho teagaisg agus chleachd e cha mhòr gun atharrachadh. Seo mar a tha an sgriobt obrach crìochnaichte coltach:

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)

Thoir aire don pharamadair dry_run=Fìor ann an loidhne tòiseachaidh nì nr.
An seo mar a tha ann an cunntachail chaidh ruith deuchainn a chuir an gnìomh anns a bheil ceangal ris an router air a dhèanamh, tha rèiteachadh atharraichte ùr air ullachadh, a tha an uairsin air a dhearbhadh leis an inneal (ach chan eil seo cinnteach; tha e an urra ri taic an inneil agus buileachadh an draibhear ann an NAPALM) , ach chan eil an rèiteachadh ùr air a chuir an sàs gu dìreach. Airson cleachdadh sabaid, feumaidh tu am paramadair a thoirt air falbh tioram_ruith no atharraich a luach gu ceàrr.

Nuair a thèid an sgriobt a chuir gu bàs, bidh Nornir a’ toirt a-mach logaichean mionaideach don consol.

Fon spoiler tha toradh ruith sabaid air dà router deuchainn:

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 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

A’ falach faclan-faire ann an ansible_vault

Aig toiseach an artaigil chaidh mi beagan air bòrd cunntachail, ach chan eil e uile cho dona. Is fìor thoil leam iad sneachda leithid, a tha air a dhealbhadh gus fiosrachadh mothachail fhalach a-mach à sealladh. Agus is dòcha gu bheil mòran air mothachadh gu bheil na logaichean / faclan-faire againn airson a h-uile router sabaid a’ deàrrsadh ann an cruth fosgailte ann am faidhle gorups.yaml. Chan eil e breagha, gu dearbh. Nach dìon sinn an dàta seo le sneachda.

Nach gluais sinn na crìochan bho groups.yaml gu creds.yaml, agus cuir a-steach e le AES256 le facal-faire 20-digit:

$ 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

Tha e cho sìmplidh sin. Tha e fhathast airson ar teagasg Nornir-script gus an dàta seo fhaighinn air ais agus a chuir an sàs.
Gus seo a dhèanamh, nar sgriobt às deidh an loidhne tòiseachaidh nr = InitNornir(config_file=… cuir an còd a leanas ris:

...
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
...

Gu dearbh, cha bu chòir vault.passwd a bhith suidhichte ri taobh creds.yaml mar a tha san eisimpleir agam. Ach tha e ceart gu leòr airson a chluich.

Tha sin uile airson a-nis. Tha artaigil no dhà eile ann mu dheidhinn Cisco + Zabbix a ’tighinn, ach chan eil seo beagan mu dheidhinn fèin-ghluasad. Agus a dh'aithghearr tha mi an dùil sgrìobhadh mu RESTCONF ann an Cisco.

Source: www.habr.com

Cuir beachd ann